Skip to content

Beautiful Open-Source Form Builder

Reduce SSR memory retention and speed up public page loading (#1363)

Julien Nahum24193de86c03
diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml
index e10b33b45..39073fa09 100644
--- a/.github/workflows/ci-cd.yml
+++ b/.github/workflows/ci-cd.yml
@@ -141,7 +141,7 @@ jobs:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
- name: Check public form bundle
- run: npm run check:public-form-bundle && npm run check:built-css
+ run: npm run check:public-form-bundle && npm run check:landing-bundle && npm run check:built-css
- name: Preserve client manifest for browser chunk tests
run: |
diff --git a/README.md b/README.md
index cd51c61ba..17443b6b6 100644
--- a/README.md
+++ b/README.md
@@ -141,3 +141,7 @@ See [October 2026 deployment and compatibility notes](docs/security-remediation-
Public submissions use the form's language for API validation messages. When adding a translated validation message, update the catalogs under `api/resources/lang/` for all languages in `Form::LANGUAGES`, preserving placeholders such as `:attribute`, `:min`, and `:max`.
Run `vendor/bin/pest --filter=FormValidationTranslationsTest` from `api/` to check supported catalogs and render invalid date range, rating, selection, and Arabic file-type errors. The tests do not require a database. The catalog check excludes custom attribute aliases and the legacy password key, whose structure differs between Laravel versions. Client text coverage is checked separately by `test/unit/form-locale-keys.test.ts` in `client/`.
+
+## Production performance
+
+See [runtime limits, caching and reproducible local measurements](docs/reports/production-performance-2026-10.md).
diff --git a/api/app/Http/Kernel.php b/api/app/Http/Kernel.php
index c604a04ac..6859372d4 100644
--- a/api/app/Http/Kernel.php
+++ b/api/app/Http/Kernel.php
@@ -158,7 +158,7 @@ class Kernel extends HttpKernel
$appEnv = (string) ($_ENV['APP_ENV'] ?? $_SERVER['APP_ENV'] ?? 'production');
if (!in_array($appEnv, ['testing', 'e2e'], true)) {
- array_unshift($this->middlewareGroups['api'], 'throttle:100,1');
+ $this->prependMiddlewareToGroup('api', 'throttle:internal-api');
}
}
}
diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.php
index cb14b1a5f..488bb76b3 100644
--- a/api/app/Providers/RouteServiceProvider.php
+++ b/api/app/Providers/RouteServiceProvider.php
@@ -52,6 +52,21 @@ class RouteServiceProvider extends ServiceProvider
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
+ RateLimiter::for('internal-api', function (Request $request) {
+ // Public SSR reads share the renderer's IP. Give authenticated
+ // renderers a separate, bounded bucket without trusting client IP headers.
+ $secret = (string) config('app.front_api_secret');
+ if ($request->isMethod('GET') && $secret !== ''
+ && hash_equals($secret, (string) $request->header('x-api-secret', ''))
+ && $request->route()?->named('forms.show', 'content.feature-flags', 'content.plans')) {
+ return Limit::perMinute(max(1, (int) config('app.ssr_reads_per_minute', 6000)))
+ ->by('ssr-read:'.$request->ip());
+ }
+
+ return Limit::perMinute(100)->by($request->user()?->getAuthIdentifier()
+ ?: $request->route()->getDomain().'|'.$request->ip());
+ });
+
RateLimiter::for('integration-retries', function (Request $request) {
return Limit::perMinute(10)->by($request->user()?->id ?: $request->ip());
});
diff --git a/api/config/app.php b/api/config/app.php
index 78aa9ddc9..a1bc218f2 100644
--- a/api/config/app.php
+++ b/api/config/app.php
@@ -78,6 +78,7 @@ return [
'front_url' => env('FRONT_URL', null),
'front_api_secret' => env('FRONT_API_SECRET', null),
+ 'ssr_reads_per_minute' => env('SSR_READS_PER_MINUTE', 6000),
/*
|--------------------------------------------------------------------------
diff --git a/api/routes/api.php b/api/routes/api.php
index f0ec992de..d12ea8767 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -58,23 +58,23 @@ if (config('app.self_hosted')) {
Route::middleware('mcp.enabled')->group(function () {
Route::prefix('agent-drafts')->name('agent-drafts.')->middleware('mcp.guest-drafts')->group(function () {
Route::get('/preview/{draft}', [AgentFormDraftController::class, 'preview'])
- ->withoutMiddleware('throttle:100,1')
+ ->withoutMiddleware('throttle:internal-api')
->middleware(['signed', 'throttle:agent-draft-preview'])
->name('preview');
Route::post('/handoff/consume', [AgentFormDraftController::class, 'consume'])
- ->withoutMiddleware('throttle:100,1')
+ ->withoutMiddleware('throttle:internal-api')
->middleware('throttle:agent-draft-handoff')
->name('handoff.consume');
Route::get('/editor/current', [AgentFormDraftController::class, 'current'])
- ->withoutMiddleware('throttle:100,1')
+ ->withoutMiddleware('throttle:internal-api')
->middleware('throttle:agent-draft-editor')
->name('editor.current');
Route::put('/editor/current', [AgentFormDraftController::class, 'replace'])
- ->withoutMiddleware('throttle:100,1')
+ ->withoutMiddleware('throttle:internal-api')
->middleware('throttle:agent-draft-editor')
->name('editor.replace');
Route::post('/editor/claim', [AgentFormDraftController::class, 'claim'])
- ->withoutMiddleware('throttle:100,1')
+ ->withoutMiddleware('throttle:internal-api')
->middleware(['auth.multi', 'throttle:30,1'])
->name('editor.claim');
});
@@ -259,16 +259,16 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::get('/{submission_id}', [FormSubmissionController::class, 'fetch'])->name('fetch');
Route::put('/{submission_id}', [FormSubmissionController::class, 'update'])->name('update');
Route::post('/export', [FormSubmissionController::class, 'export'])
- ->withoutMiddleware(['throttle:100,1'])
+ ->withoutMiddleware(['throttle:internal-api'])
->middleware('throttle:export')
->name('export');
Route::get('/export/status/{jobId}', [FormSubmissionController::class, 'exportStatus'])
- ->withoutMiddleware(['throttle:100,1'])
+ ->withoutMiddleware(['throttle:internal-api'])
->middleware('throttle:export-status')
->name('export.status');
Route::get('/file/{filename}', [FormSubmissionController::class, 'submissionFile'])
->middleware(['signed:relative', 'throttle:submission-files'])
- ->withoutMiddleware(['auth.multi', 'throttle:100,1'])
+ ->withoutMiddleware(['auth.multi', 'throttle:internal-api'])
->name('file');
Route::delete('/{submission_id}', [FormSubmissionController::class, 'destroy'])->name('destroy');
Route::post('/multi', [FormSubmissionController::class, 'destroyMulti'])->name('destroy-multi');
@@ -579,4 +579,4 @@ Route::get('caddy/ask-certificate/{secret?}', [\App\Http\Controllers\CaddyContro
->name('caddy.ask')->middleware(\App\Http\Middleware\CaddyRequestMiddleware::class);
Route::post('/aws/sns/ses/integration-events', \App\Http\Controllers\Integrations\SesIntegrationFeedbackController::class)
- ->withoutMiddleware(['throttle:100,1', 'throttle:150,1', 'throttle:api']);
+ ->withoutMiddleware(['throttle:internal-api', 'throttle:150,1', 'throttle:api']);
diff --git a/api/tests/Feature/Forms/FileDownloadSecurityTest.php b/api/tests/Feature/Forms/FileDownloadSecurityTest.php
index 29e81233c..d5aefa93f 100644
--- a/api/tests/Feature/Forms/FileDownloadSecurityTest.php
+++ b/api/tests/Feature/Forms/FileDownloadSecurityTest.php
@@ -93,7 +93,7 @@ it('keeps signed attachment requests separate from the general API quota', funct
$this->withMiddleware(\Illuminate\Routing\Middleware\ThrottleRequests::class);
$router = app('router');
$middleware = $router->getMiddlewareGroups()['api'];
- array_unshift($middleware, 'throttle:100,1');
+ array_unshift($middleware, 'throttle:internal-api');
$router->middlewareGroup('api', $middleware);
$user = $this->actingAsProUser();
diff --git a/api/tests/Feature/Forms/FormSubmissionExportTest.php b/api/tests/Feature/Forms/FormSubmissionExportTest.php
index b352c61c6..dc7c2af57 100644
--- a/api/tests/Feature/Forms/FormSubmissionExportTest.php
+++ b/api/tests/Feature/Forms/FormSubmissionExportTest.php
@@ -510,7 +510,7 @@ it('allows export status polling when the general api rate limit is exhausted',
$router = app('router');
$apiMiddleware = $router->getMiddlewareGroups()['api'];
- array_unshift($apiMiddleware, 'throttle:100,1');
+ array_unshift($apiMiddleware, 'throttle:internal-api');
$router->middlewareGroup('api', $apiMiddleware);
$user = $this->actingAsProUser();
diff --git a/api/tests/Feature/SsrReadRateLimitTest.php b/api/tests/Feature/SsrReadRateLimitTest.php
new file mode 100644
index 000000000..acaa8d2cf
--- /dev/null
+++ b/api/tests/Feature/SsrReadRateLimitTest.php
@@ -0,0 +1,90 @@
+<?php
+
+use Illuminate\Http\Request;
+use Illuminate\Routing\Route;
+use Illuminate\Support\Facades\RateLimiter;
+
+it('isolates authenticated renderer reads in a bounded bucket', function (string $name) {
+ config(['app.front_api_secret' => 'local-ssr-secret', 'app.ssr_reads_per_minute' => 120]);
+ $request = Request::create('/fixture', 'GET', server: ['REMOTE_ADDR' => '172.18.0.4']);
+ $request->headers->set('x-api-secret', 'local-ssr-secret');
+ $route = (new Route('GET', '/fixture', fn () => null))->name($name);
+ $request->setRouteResolver(fn () => $route);
+ $limit = RateLimiter::limiter('internal-api')($request);
+ expect($limit->maxAttempts)->toBe(120)->and($limit->key)->toBe('ssr-read:172.18.0.4');
+})->with(['forms.show', 'content.feature-flags', 'content.plans']);
+
+it('keeps ordinary limits for missing credentials, forged credentials, writes and private routes', function ($secret, $header, $method, $name) {
+ config(['app.front_api_secret' => $secret]);
+ $request = Request::create('/fixture', $method, server: ['REMOTE_ADDR' => '172.18.0.4']);
+ if ($header !== null) {
+ $request->headers->set('x-api-secret', $header);
+ }
+ $route = (new Route($method, '/fixture', fn () => null))->name($name);
+ $request->setRouteResolver(fn () => $route);
+ $limit = RateLimiter::limiter('internal-api')($request);
+ expect($limit->maxAttempts)->toBe(100)->and($limit->key)->toBe('|172.18.0.4');
+})->with([
+ ['secret', null, 'GET', 'forms.show'],
+ ['secret', 'wrong', 'GET', 'forms.show'],
+ ['', '', 'GET', 'forms.show'],
+ [null, '', 'GET', 'forms.show'],
+ ['secret', 'secret', 'POST', 'forms.show'],
+ ['secret', 'secret', 'GET', 'open.forms.show'],
+ ['secret', 'secret', 'GET', 'forms.fetchSubmission'],
+ ['secret', 'secret', 'GET', 'forms.assets.show'],
+]);
+
+
+function enableProductionSsrApiThrottle($test): void
+{
+ $previousEnv = $_ENV['APP_ENV'] ?? null;
+ $_ENV['APP_ENV'] = 'production';
+ try {
+ $kernel = new \App\Http\Kernel(app(), app('router'));
+ } finally {
+ if ($previousEnv === null) {
+ unset($_ENV['APP_ENV']);
+ } else {
+ $_ENV['APP_ENV'] = $previousEnv;
+ }
+ }
+ app()->instance(\Illuminate\Contracts\Http\Kernel::class, $kernel);
+ $test->withMiddleware(\Illuminate\Routing\Middleware\ThrottleRequests::class);
+}
+
+it('enforces the SSR quota on real public routes with the production kernel', function (string $name) {
+ enableProductionSsrApiThrottle($this);
+ config(['app.front_api_secret' => 'local-ssr-secret', 'app.ssr_reads_per_minute' => 2]);
+ $parameters = [];
+ if ($name === 'forms.show') {
+ $user = $this->createUser();
+ $workspace = $this->createUserWorkspace($user);
+ $parameters['form'] = $this->createForm($user, $workspace)->slug;
+ }
+ $url = route($name, $parameters);
+ $this->withHeader('x-api-secret', 'local-ssr-secret');
+ $this->getJson($url)->assertOk()->assertHeader('X-RateLimit-Limit', '2');
+ $this->getJson($url)->assertOk();
+ $this->getJson($url)->assertTooManyRequests();
+ $this->withHeader('x-api-secret', 'forged')->getJson($url)
+ ->assertOk()->assertHeader('X-RateLimit-Limit', '100');
+})->with(['forms.show', 'content.feature-flags', 'content.plans']);
+
+it('shares the ordinary internal quota across routes without consuming the renderer bucket', function () {
+ enableProductionSsrApiThrottle($this);
+ config(['app.front_api_secret' => 'local-ssr-secret', 'app.ssr_reads_per_minute' => 2]);
+ for ($i = 0; $i < 100; $i++) {
+ $name = $i % 2 === 0 ? 'content.feature-flags' : 'content.plans';
+ $this->getJson(route($name))->assertOk()->assertHeader('X-RateLimit-Limit', '100');
+ }
+ $this->getJson(route('content.plans'))->assertTooManyRequests();
+ $this->withHeader('x-api-secret', 'local-ssr-secret')
+ ->getJson(route('content.feature-flags'))->assertOk()->assertHeader('X-RateLimit-Limit', '2');
+});
+
+it('preserves the external API quota', function () {
+ $request = Request::create('/fixture', 'GET', server: ['REMOTE_ADDR' => '172.18.0.4']);
+ $limit = RateLimiter::limiter('api')($request);
+ expect($limit->maxAttempts)->toBe(60);
+});
diff --git a/client/app.vue b/client/app.vue
index 8688c4474..c5b5f4440 100644
--- a/client/app.vue
+++ b/client/app.vue
@@ -12,6 +12,7 @@
<!-- Third-party services and modals - only load when not on public form pages -->
<ClientOnly v-if="!isPublicFormPage">
<div
+ v-if="authStore.isImpersonating"
class="fixed z-[9999] left-0 bottom-0 p-4" id="admin-actions"
>
<UFieldGroup size="sm">
@@ -19,17 +20,24 @@
</UFieldGroup>
</div>
- <LazyVendorClarity />
- <LazyVendorFeatureBase />
- <LazyQuickRegister />
+ <LazyVendorClarity v-if="vendorsReady && authStore.token && config.public.clarityProjectId" />
+ <LazyVendorFeatureBase v-if="vendorsReady && authStore.token && config.public.featureBaseOrganization" />
+ <LazyQuickRegister v-if="appStore.quickLoginModal || appStore.quickRegisterModal || appStore.isUnauthorizedError" />
</ClientOnly>
</div>
</AppProvider>
</template>
<script setup>
+const vendorsReady = ref(false)
+let vendorTimer
+onMounted(() => { vendorTimer = setTimeout(() => { vendorsReady.value = true }, 1500) })
+onBeforeUnmount(() => clearTimeout(vendorTimer))
+const appStore = useAppStore()
+const authStore = useAuthStore()
const config = useRuntimeConfig()
const route = useRoute()
+const { locale } = useI18n()
// Check if current page is a public form page (for performance optimization)
const isPublicFormPage = computed(() => route.name === 'forms-slug')
@@ -67,7 +75,8 @@ useHead({
}
],
htmlAttrs: () => ({
- dir: 'ltr'
+ dir: 'ltr',
+ lang: locale.value
})
})
</script>
diff --git a/client/components/dashboard/WorkspaceDropdown.vue b/client/components/dashboard/WorkspaceDropdown.vue
index e8772b489..99dd17505 100644
--- a/client/components/dashboard/WorkspaceDropdown.vue
+++ b/client/components/dashboard/WorkspaceDropdown.vue
@@ -85,12 +85,14 @@
<!-- Create Workspace Modal -->
<CreateWorkspaceModal
+ v-if="showCreateModal"
v-model="showCreateModal"
@created="onWorkspaceCreated"
@close="showCreateModal = false"
/>
<WorkspacesSettingsInviteUser
+ v-if="showInviteUserModal"
v-model="showInviteUserModal"
@user-added="onUserAdded"
/>
@@ -99,8 +101,8 @@
<script setup>
import { computed, ref } from "vue"
import WorkspaceIcon from "~/components/workspaces/WorkspaceIcon.vue"
-import CreateWorkspaceModal from "~/components/workspaces/CreateWorkspaceModal.vue"
-import WorkspacesSettingsInviteUser from '~/components/workspaces/settings/InviteUser.vue'
+const CreateWorkspaceModal = defineAsyncComponent(() => import("~/components/workspaces/CreateWorkspaceModal.vue"))
+const WorkspacesSettingsInviteUser = defineAsyncComponent(() => import('~/components/workspaces/settings/InviteUser.vue'))
import ScrollableContainer from '~/components/dashboard/ScrollableContainer.vue'
diff --git a/client/components/global/Navbar.vue b/client/components/global/Navbar.vue
index 0dc5c4ec8..b44e9c047 100644
--- a/client/components/global/Navbar.vue
+++ b/client/components/global/Navbar.vue
@@ -13,7 +13,7 @@
>{{ isSelfHosted ? instanceName : 'OpnForm' }}</span
>
</NuxtLink>
- <WorkspaceDropdown class="ml-6">
+ <WorkspaceDropdown v-if="user" class="ml-6">
<template #default="{ workspace }">
<button
v-if="workspace"
@@ -136,7 +136,7 @@
class="flex items-center"
dusk="nav-dropdown-button"
>
- <img :src="user.photo_url" class="rounded-full w-6 h-6" />
+ <img :src="user.photo_url" class="rounded-full w-6 h-6" alt="Your profile" width="24" height="24" />
<p class="ml-2 hidden sm:inline max-w-20 truncate">
{{ user.name }}
</p>
@@ -177,9 +177,9 @@
import { computed } from "vue"
import { useRoute } from "#imports"
-import WorkspaceDropdown from "../dashboard/WorkspaceDropdown.vue"
+const WorkspaceDropdown = defineAsyncComponent(() => import("../dashboard/WorkspaceDropdown.vue"))
import WorkspaceIcon from "~/components/workspaces/WorkspaceIcon.vue"
-import UserDropdown from "../dashboard/UserDropdown.vue"
+const UserDropdown = defineAsyncComponent(() => import("../dashboard/UserDropdown.vue"))
import opnformConfig from "~/opnform.config.js"
import { useFeatureFlag } from "~/composables/useFeatureFlag"
diff --git a/client/components/pages/OpenFormFooter.vue b/client/components/pages/OpenFormFooter.vue
index cefb74a34..1464a503f 100644
--- a/client/components/pages/OpenFormFooter.vue
+++ b/client/components/pages/OpenFormFooter.vue
@@ -7,8 +7,9 @@
class="relative rounded-4xl overflow-hidden bg-linear-to-br from-blue-600 via-blue-700 to-blue-800 pt-8 sm:pt-10 lg:pt-14 xl:pt-24 pl-8 md:pl-10 lg:pl-14 xl:pl-35"
>
<img
- src="/img/pages/welcome/powerForm-bg.png"
- class="absolute min-h-full inset-0 opacity-30"
+ src="/img/pages/welcome/powerForm-bg.webp"
+ loading="lazy" decoding="async" width="1000" height="1000" alt="" aria-hidden="true"
+ class="absolute w-full h-full inset-0 object-cover opacity-30"
/>
<div class="grid lg:grid-cols-2 relative z-10">
<div
@@ -111,7 +112,8 @@
class="relative w-full overflow-hidden flex justify-end items-end"
>
<img
- src="/img/pages/welcome/product-cover-half.png"
+ src="/img/pages/welcome/product-cover-half.webp"
+ loading="lazy" decoding="async" width="748" height="844"
alt="Product screenshot"
class="w-full max-w-128.25 h-auto"
/>
diff --git a/client/components/pages/welcome/Features.vue b/client/components/pages/welcome/Features.vue
index e4bbec6be..58331422d 100644
--- a/client/components/pages/welcome/Features.vue
+++ b/client/components/pages/welcome/Features.vue
@@ -72,6 +72,9 @@
<div class="flex justify-center lg:justify-end">
<img
:src="panel.imageSrc"
+ :srcset="panelSrcset(panel)"
+ sizes="(min-width: 1024px) 480px, (min-width: 640px) 400px, calc(100vw - 130px)"
+ :width="panel.imageWidth" :height="panel.imageWidth" decoding="async"
:alt="panel.eyebrow"
class="w-full max-w-100 lg:max-w-120 mx-auto h-auto rounded-2xl"
loading="lazy"
@@ -164,6 +167,8 @@
<img
:key="activeDesktopImage.eyebrow"
:src="activeDesktopImage.imageSrc"
+ :srcset="panelSrcset(activeDesktopImage)"
+ sizes="480px" :width="activeDesktopImage.imageWidth" :height="activeDesktopImage.imageWidth" decoding="async"
:alt="activeDesktopImage.eyebrow"
class="w-full max-w-120 h-auto rounded-[28px]"
loading="lazy"
@@ -329,6 +334,12 @@ const desktopPanelRefs = ref([])
const activeDesktopPanel = ref(0)
let desktopPanelObserver = null
+function panelSrcset(panel) {
+ const src = panel.imageSrc
+ if (panel.imageWidth <= 640) return `${src} ${panel.imageWidth}w`
+ return `${src.replace('.webp', '-480.webp')} 480w, ${src.replace('.webp', '-640.webp')} 640w, ${src} 968w`
+}
+
const panels = [
{
eyebrow: "Modern Form Builder",
@@ -374,12 +385,13 @@ const panels = [
iconClass: "text-blue-600",
},
],
- imageSrc: "/img/pages/welcome/feature-1.png",
+ imageSrc: "/img/pages/welcome/feature-1.webp",
+ imageWidth: 484,
link: null,
},
{
eyebrow: "Unlimited Submissions",
- eyebrowClass: "text-emerald-600",
+ eyebrowClass: "text-emerald-700",
title: "Collect as many responses as you need, even on the free plan.",
description:
"No per-response charges. No hidden quotas. No unexpected overages. OpnForm grows with your team.",
@@ -388,27 +400,28 @@ const panels = [
title: "Unlimited submissions",
icon: "i-ph-infinity-bold",
iconWrapClass: "bg-emerald-50 ring-emerald-100",
- iconClass: "text-emerald-600",
+ iconClass: "text-emerald-700",
},
{
title: "Generous free tier",
icon: "i-heroicons-gift",
iconWrapClass: "bg-emerald-50 ring-emerald-100",
- iconClass: "text-emerald-600",
+ iconClass: "text-emerald-700",
},
{
title: "Fair, transparent pricing",
icon: "i-heroicons-banknotes",
iconWrapClass: "bg-emerald-50 ring-emerald-100",
- iconClass: "text-emerald-600",
+ iconClass: "text-emerald-700",
},
],
- imageSrc: "/img/pages/welcome/feature-2.png",
+ imageSrc: "/img/pages/welcome/feature-2.webp",
+ imageWidth: 484,
link: null,
},
{
eyebrow: "Integrations & Automation",
- eyebrowClass: "text-violet-600",
+ eyebrowClass: "text-violet-700",
title: "Connect OpnForm to the tools you already use.",
description:
"Automate your workflows with native integrations or connect anything with webhooks and our public API.",
@@ -417,38 +430,39 @@ const panels = [
title: "Slack, Discord, Telegram",
icon: "i-heroicons-chat-bubble-left-right",
iconWrapClass: "bg-violet-50 ring-violet-100",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
{
title: "Google Sheets & Zapier",
icon: "i-heroicons-table-cells",
iconWrapClass: "bg-violet-50 ring-violet-100",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
{
title: "Stripe payments",
icon: "i-heroicons-credit-card",
iconWrapClass: "bg-violet-50 ring-violet-100",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
{
title: "Webhooks + REST API",
icon: "i-heroicons-link",
iconWrapClass: "bg-violet-50 ring-violet-100",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
{
title: "Auto-notifications & routing",
icon: "i-heroicons-arrow-path-rounded-square",
iconWrapClass: "bg-violet-50 ring-violet-100",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
],
- imageSrc: "/img/pages/welcome/feature-3.png",
+ imageSrc: "/img/pages/welcome/feature-3.webp",
+ imageWidth: 968,
link: {
to: { name: "pricing" },
label: "Explore All Features",
- class: "text-violet-600 hover:text-violet-700 hover:no-underline",
+ class: "text-violet-700 hover:text-violet-700 hover:no-underline",
},
},
]
diff --git a/client/components/pages/welcome/LiveDemo.vue b/client/components/pages/welcome/LiveDemo.vue
index c742667dc..a53465bbd 100644
--- a/client/components/pages/welcome/LiveDemo.vue
+++ b/client/components/pages/welcome/LiveDemo.vue
@@ -48,13 +48,20 @@
</div>
</div>
- <div class="relative min-h-[460px] bg-white sm:min-h-[620px]">
- <LiveDemoForm
+ <div ref="demoContainer" class="relative min-h-[460px] bg-white sm:min-h-[620px]">
+ <LazyLiveDemoForm
+ v-if="hasBeenVisible"
:key="scenario.key"
:scenario="scenario"
:primary-cta-to="primaryCtaTo"
:secondary-cta-to="secondaryCtaTo"
/>
+ <div v-else class="min-h-[460px] sm:min-h-[620px] flex flex-col justify-center gap-5 p-8 sm:p-12" aria-busy="true" aria-label="Loading live demo">
+ <div class="h-6 w-32 rounded bg-neutral-100" aria-hidden="true" />
+ <div class="h-12 w-3/4 rounded bg-neutral-100" aria-hidden="true" />
+ <div class="h-4 w-full rounded bg-neutral-50" aria-hidden="true" />
+ <div class="h-4 w-2/3 rounded bg-neutral-50" aria-hidden="true" />
+ </div>
</div>
</div>
</div>
@@ -62,21 +69,27 @@
</template>
<script setup>
-import LiveDemoForm from "~/components/pages/welcome/LiveDemoForm.vue"
import { useIsAuthenticated } from "~/composables/useIsAuthenticated.js"
import {
- getLiveDemoMediaPreloads,
getLiveDemoScenario,
} from "~/data/live-demo-scenarios.js"
-useHead({
- link: getLiveDemoMediaPreloads().map((href) => ({
- rel: "preload",
- href,
- as: "image",
- type: "image/webp",
- })),
+const demoContainer = ref(null)
+const hasBeenVisible = ref(false)
+let observer
+onMounted(() => {
+ if (!window.IntersectionObserver) {
+ hasBeenVisible.value = true
+ return
+ }
+ observer = new IntersectionObserver((entries) => {
+ if (!entries.some(entry => entry.isIntersecting && entry.intersectionRatio >= 0.35)) return
+ hasBeenVisible.value = true
+ observer.disconnect()
+ }, { threshold: 0.35 })
+ observer.observe(demoContainer.value)
})
+onBeforeUnmount(() => observer?.disconnect())
const props = defineProps({
variant: {
diff --git a/client/components/pages/welcome/LiveDemoForm.vue b/client/components/pages/welcome/LiveDemoForm.vue
index b477ff6f1..e67633099 100644
--- a/client/components/pages/welcome/LiveDemoForm.vue
+++ b/client/components/pages/welcome/LiveDemoForm.vue
@@ -61,8 +61,8 @@
import { tailwindcssPaletteGenerator } from "~/lib/colors.js"
import { useFormManager } from "~/lib/forms/composables/useFormManager"
import { FormMode } from "~/lib/forms/FormModeStrategy.js"
-import OpenForm from "~/components/open/forms/OpenForm.vue"
-import OpenFormFocused from "~/components/open/forms/OpenFormFocused.vue"
+const OpenForm = defineAsyncComponent(() => import("~/components/open/forms/OpenForm.vue"))
+const OpenFormFocused = defineAsyncComponent(() => import("~/components/open/forms/OpenFormFocused.vue"))
const props = defineProps({
scenario: {
diff --git a/client/components/pages/welcome/MoreFeatures.vue b/client/components/pages/welcome/MoreFeatures.vue
index 0c17ee609..64452ba20 100644
--- a/client/components/pages/welcome/MoreFeatures.vue
+++ b/client/components/pages/welcome/MoreFeatures.vue
@@ -101,6 +101,7 @@
>
<img
src="/img/pages/welcome/Graphic.svg"
+ loading="lazy" decoding="async" alt="" aria-hidden="true"
class="pointer-events-none absolute top-[45%] left-0 right-0 min-w-full object-cover min-h-[55%]"
/>
<div
@@ -368,7 +369,7 @@ const securityPills = [
label: "SSO & SAML support",
icon: "i-heroicons-lock-closed",
iconWrapClass: "bg-violet-50",
- iconClass: "text-violet-600",
+ iconClass: "text-violet-700",
},
{
label: "Form & submission audit logs",
@@ -392,7 +393,7 @@ const securityPills = [
label: "End-to-end data encryption",
icon: "i-heroicons-lock-closed",
iconWrapClass: "bg-emerald-50",
- iconClass: "text-emerald-600",
+ iconClass: "text-emerald-700",
},
]
diff --git a/client/components/pages/welcome/TrustedTeams.vue b/client/components/pages/welcome/TrustedTeams.vue
index 9b96cf3b6..2efbf99ed 100644
--- a/client/components/pages/welcome/TrustedTeams.vue
+++ b/client/components/pages/welcome/TrustedTeams.vue
@@ -19,6 +19,7 @@
<div class="w-fit">
<img
src="/img/pages/welcome/vanguard-1.png"
+ width="94" height="20" loading="lazy" decoding="async"
alt="Trusted Teams"
class="w-full"
/>
@@ -26,6 +27,7 @@
<div class="w-fit">
<img
src="/img/pages/welcome/logo-berkeley-2.png"
+ width="100" height="19" loading="lazy" decoding="async"
alt="Trusted Teams"
class="w-full"
/>
@@ -33,6 +35,7 @@
<div class="w-fit">
<img
src="/img/pages/welcome/UN_emblem_blue-2.png"
+ width="47" height="40" loading="lazy" decoding="async"
alt="Trusted Teams"
class="w-full"
/>
@@ -40,6 +43,7 @@
<div class="w-fit">
<img
src="/img/pages/welcome/Frame-47.png"
+ width="90" height="21" loading="lazy" decoding="async"
alt="Trusted Teams"
class="w-full"
/>
@@ -47,6 +51,7 @@
<div class="w-fit">
<img
src="/img/pages/welcome/Zomato_Logo-2.png"
+ width="94" height="20" loading="lazy" decoding="async"
alt="Trusted Teams"
class="w-full"
/>
diff --git a/client/components/vendor/Clarity.vue b/client/components/vendor/Clarity.vue
index 0df2083b3..0d9175184 100644
--- a/client/components/vendor/Clarity.vue
+++ b/client/components/vendor/Clarity.vue
@@ -1,7 +1,10 @@
<template />
<script setup>
-import Clarity from '@microsoft/clarity'
+let clarity = null
+let clarityPromise = null
+let disposed = false
+onBeforeUnmount(() => { disposed = true })
import { useIsAuthenticated } from '~/composables/useIsAuthenticated.js'
const authStore = useAuthStore()
@@ -12,19 +15,23 @@ const runtimeConfig = useRuntimeConfig()
const clarityProjectId = computed(() => runtimeConfig.public.clarityProjectId || null)
const { isAuthenticated } = useIsAuthenticated()
-async function loadClarity() {
+function loadClarity() {
const projectId = clarityProjectId.value
if (!projectId || !isAuthenticated.value || isIframe || loaded.value) return
- try {
- Clarity.init(projectId)
- if (user.value?.id) {
- Clarity.identify(String(user.value.id), null, null, String(user.value.id))
- }
+ clarityPromise ||= import('@microsoft/clarity').then(({ default: sdk }) => {
+ clarity = sdk
+ return sdk
+ }).catch((error) => {
+ clarityPromise = null
+ throw error
+ })
+ return clarityPromise.then((sdk) => {
+ if (disposed || !isAuthenticated.value || isIframe || loaded.value) return
+ sdk.init(projectId)
+ if (user.value?.id) sdk.identify(String(user.value.id), null, null, String(user.value.id))
loaded.value = true
- } catch (error) {
- console.error('[Clarity] Failed to init', error)
- }
+ }).catch((error) => console.error('[Clarity] Failed to init', error))
}
watch(isAuthenticated, (val) => {
@@ -36,7 +43,7 @@ watch(user, (val) => {
if (!loaded.value || !isAuthenticated.value || isIframe) return
if (val?.id) {
try {
- Clarity.identify(String(val.id), null, null, String(val.id))
+ clarity.identify(String(val.id), null, null, String(val.id))
} catch (error) {
console.error('[Clarity] Failed to identify user', error)
}
diff --git a/client/components/vendor/FeatureBase.vue b/client/components/vendor/FeatureBase.vue
index 0a4813f06..fc02668b8 100644
--- a/client/components/vendor/FeatureBase.vue
+++ b/client/components/vendor/FeatureBase.vue
@@ -1,7 +1,9 @@
<template>
<button
v-if="user && featureBaseOrganization"
- v-show="scriptLoaded && appStore.featureBaseButtonVisible"
+ v-show="appStore.featureBaseButtonVisible"
+ @click="openFeedback"
+ ref="feedbackButton"
data-featurebase-feedback
class="fixed -right-9 top-1/2 -translate-y-1/2 z-20 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-3 rounded-t-lg shadow-lg transition-all duration-200 hover:shadow-xl transform hover:scale-105 flex items-center space-x-1 -rotate-90 origin-center"
>
@@ -10,10 +12,15 @@
</button>
</template>
<script setup>
-import { onMounted } from "vue"
-import { default as _has } from "lodash/has"
-const scriptLoaded = ref(false)
+const scriptLoaded = ref(import.meta.client && document.getElementById('featurebase-sdk')?.dataset.loaded === 'true')
+let disposed = false
+let setupQueued = false
+const widgetReady = ref(false)
+const changelogReady = ref(false)
+const changelogRequested = useState('featurebase-changelog-requested', () => false)
+const feedbackButton = ref(null)
+let feedbackRequested = false
let setupQueue = []
const authStore = useAuthStore()
@@ -34,18 +41,36 @@ const runSetupQueue = () => {
}
}
+const resetFailedSetup = (event) => {
+ event.currentTarget?.remove()
+ feedbackRequested = false
+ setupQueue = []
+ setupQueued = false
+ changelogRequested.value = false
+}
+
const loadScript = () => {
if (scriptLoaded.value || !user.value || !featureBaseOrganization) return
- if (document.getElementById("featurebase-sdk")) return
+ const existing = document.getElementById('featurebase-sdk')
+ if (existing) {
+ existing.addEventListener('load', () => {
+ scriptLoaded.value = true
+ if (!disposed) runSetupQueue()
+ }, { once: true })
+ existing.addEventListener('error', resetFailedSetup, { once: true })
+ return
+ }
const script = document.createElement("script")
script.src = "https://do.featurebase.app/js/sdk.js"
script.id = "featurebase-sdk"
document.head.appendChild(script)
script.onload = () => {
+ script.dataset.loaded = 'true'
scriptLoaded.value = true
- runSetupQueue()
+ if (!disposed) runSetupQueue()
}
+ script.onerror = resetFailedSetup
}
const setupForUser = () => {
@@ -73,6 +98,10 @@ const setupForUser = () => {
alwaysShow: true,
fullscreenPopup: true,
usersName: user.value?.name,
+ }, (error, event) => {
+ if (disposed || error || event?.action !== 'unreadChangelogsCountChanged') return
+ changelogReady.value = true
+ openRequestedChangelog()
})
window.Featurebase("initialize_feedback_widget", {
@@ -80,13 +109,25 @@ const setupForUser = () => {
theme: "light",
email: user.value?.email,
usersName: user.value?.name,
+ }, (error, event) => {
+ if (error || event?.action !== 'widgetReady') return
+ widgetReady.value = true
+ if (feedbackRequested) {
+ feedbackRequested = false
+ feedbackButton.value?.click()
+ }
})
}
const scheduleSetup = () => {
if (import.meta.server) return
- setupQueue.push(setupForUser)
+ if (setupQueued) return
+ setupQueued = true
+ setupQueue.push(() => {
+ setupQueued = false
+ setupForUser()
+ })
if (scriptLoaded.value) {
runSetupQueue()
@@ -95,28 +136,49 @@ const scheduleSetup = () => {
}
}
-onMounted(() => {
- if (import.meta.server || !user.value) return
-
- // Setup base
- if (
- !_has(window, "Featurebase") ||
- typeof window.Featurebase !== "function"
- ) {
+// The first feedback interaction loads the SDK; closed widgets cost no JS.
+function ensureSdk() {
+ if (typeof window.Featurebase !== 'function') {
window.Featurebase = function () {
;(window.Featurebase.q = window.Featurebase.q || []).push(arguments)
}
}
+ scheduleSetup()
+}
+
+function openFeedback() {
+ if (!user.value || isImpersonating.value || widgetReady.value) return
+ feedbackRequested = true
+ ensureSdk()
+}
- if (user.value) {
- scheduleSetup()
+function openRequestedChangelog() {
+ if (!changelogRequested.value || !user.value || isImpersonating.value) return
+ if (!changelogReady.value) {
+ ensureSdk()
+ return
}
+ changelogRequested.value = false
+ window.Featurebase('manually_open_changelog_popup')
+}
+
+watch(changelogRequested, openRequestedChangelog, { immediate: true, flush: 'sync' })
+
+onBeforeUnmount(() => {
+ disposed = true
+ setupQueue = []
+ changelogRequested.value = false
+ if (!scriptLoaded.value || typeof window.Featurebase !== 'function') return
+ window.Featurebase('destroy_feedback_widget')
+ window.Featurebase('destroy_changelog_widget')
})
watch(
user,
(val) => {
- if (val) {
+ if (val && changelogRequested.value) {
+ openRequestedChangelog()
+ } else if (val && scriptLoaded.value) {
scheduleSetup()
}
},
diff --git a/client/composables/components/useSharedNavigation.js b/client/composables/components/useSharedNavigation.js
index 70627b6f3..6f735597d 100644
--- a/client/composables/components/useSharedNavigation.js
+++ b/client/composables/components/useSharedNavigation.js
@@ -3,6 +3,7 @@ import opnformConfig from "~/opnform.config.js"
export const useSharedNavigation = () => {
const appStore = useAppStore()
const crisp = useCrisp()
+ const changelogRequested = useState('featurebase-changelog-requested', () => false)
const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))
const featurebaseLoaded = computed(() => {
@@ -17,8 +18,8 @@ export const useSharedNavigation = () => {
// Open changelog modal
function openChangelog() {
- if (import.meta.server || !window.Featurebase) return
- window.Featurebase("manually_open_changelog_popup")
+ if (import.meta.server) return
+ changelogRequested.value = true
}
// Default button configuration
@@ -142,4 +143,4 @@ export const useSharedNavigation = () => {
createNavItem,
defaultButtonProps
}
-}
\ No newline at end of file
+}
diff --git a/client/composables/useOpnApi.js b/client/composables/useOpnApi.js
index 239911276..72c24ff9b 100644
--- a/client/composables/useOpnApi.js
+++ b/client/composables/useOpnApi.js
@@ -42,6 +42,8 @@ function addCustomDomainHeader(request, options) {
export function getOpnRequestsOptions(request, opts) {
const nuxtApp = useNuxtApp()
const config = useRuntimeConfig()
+ const requestAuthStore = useAuthStore()
+ const requestToken = requestAuthStore.token
if (opts.body && opts.body instanceof FormData) {
opts.headers = {
@@ -73,7 +75,10 @@ export function getOpnRequestsOptions(request, opts) {
// Do not run token-expiry UX during SSR. Server-side bootstrap requests can
// fail for context-specific reasons and should be retried client-side first.
if (import.meta.client) {
+ // A deferred read from an earlier session must not expire a newer login.
+ if (requestAuthStore.token !== requestToken) return
const authFlow = await import('~/composables/useAuthFlow')
+ if (requestAuthStore.token !== requestToken) return
const { handleTokenExpiry } = nuxtApp.runWithContext(() => authFlow.useAuthFlow())
await handleTokenExpiry()
}
diff --git a/client/css/fonts.css b/client/css/fonts.css
index 290c2371f..45b2adaf7 100644
--- a/client/css/fonts.css
+++ b/client/css/fonts.css
@@ -1,43 +1,8 @@
-/* @font-face {
- font-family: "Inter-Variable";
- src: url("/fonts/inter/Inter-VariableFont_opsz,wght.ttf") format("truetype");
- font-weight: 100 900;
- font-display: swap;
- font-style: normal;
-}
-
-@font-face {
- font-family: "Inter-Variable";
- src: url("/fonts/inter/Inter-Italic-VariableFont_opsz,wght.ttf")
- format("truetype");
- font-weight: 100 900;
- font-display: swap;
- font-style: italic;
-} */
-
-/* Add Inter alias */
-/* @font-face {
- font-family: "Inter";
- src: url("/fonts/inter/Inter-VariableFont_opsz,wght.ttf") format("truetype");
- font-weight: 100 900;
- font-display: swap;
- font-style: normal;
-}
-
-@font-face {
- font-family: "Inter";
- src: url("/fonts/inter/Inter-Italic-VariableFont_opsz,wght.ttf")
- format("truetype");
- font-weight: 100 900;
- font-display: swap;
- font-style: italic;
-} */
-
@font-face {
font-family: "euclid-circular-b";
src:
- url("/fonts/euclid-circular-b/Euclid-Circular-B-Regular.ttf"),
- format("truetype");
+ url("/fonts/euclid-circular-b/Euclid-Circular-B-Regular.woff2")
+ format("woff2");
font-weight: 400; /* Font weight = 400 */
font-display: swap;
font-style: normal;
@@ -45,8 +10,8 @@
@font-face {
font-family: "euclid-circular-b";
- src: url("/fonts/euclid-circular-b/Euclid-Circular-B-Medium.ttf")
- format("truetype") format("truetype");
+ src: url("/fonts/euclid-circular-b/Euclid-Circular-B-Medium.woff2")
+ format("woff2");
font-weight: 500; /* Font weight = 500 */
font-display: swap;
font-style: normal;
@@ -54,8 +19,8 @@
@font-face {
font-family: "euclid-circular-b";
- src: url("/fonts/euclid-circular-b/Euclid-Circular-B-SemiBold.ttf")
- format("truetype");
+ src: url("/fonts/euclid-circular-b/Euclid-Circular-B-SemiBold.woff2")
+ format("woff2");
font-weight: 600; /* Font weight = 600 */
font-display: swap;
font-style: normal;
@@ -63,8 +28,8 @@
@font-face {
font-family: "euclid-circular-b";
- src: url("/fonts/euclid-circular-b/Euclid-Circular-B-Italic.ttf")
- format("truetype");
+ src: url("/fonts/euclid-circular-b/Euclid-Circular-B-Italic.woff2")
+ format("woff2");
font-weight: 100 900;
font-display: swap;
font-style: italic; /* Font style = italic */
diff --git a/client/lib/marketing-route.js b/client/lib/marketing-route.js
new file mode 100644
index 000000000..034d9e928
--- /dev/null
+++ b/client/lib/marketing-route.js
@@ -0,0 +1,4 @@
+// This allowlist never includes private app routes, auth callbacks or setup.
+export function isMarketingRoute(route) {
+ return /^\/(?:$|pricing\/?$|features\/?$|enterprise\/?$|industry(?:\/|$)|integrations(?:\/|$)|opnform-vs-[a-z0-9-]+\/?$|ai-form-builder\/?$|mcp\/?$)/.test(route.path)
+}
diff --git a/client/lib/ssr-query-cache.js b/client/lib/ssr-query-cache.js
new file mode 100644
index 000000000..261420fbf
--- /dev/null
+++ b/client/lib/ssr-query-cache.js
@@ -0,0 +1,7 @@
+export function registerSsrQueryCleanup(nuxt, queryClient, state, dehydrate) {
+ nuxt.hooks.hook('app:rendered', () => {
+ state.value = dehydrate(queryClient)
+ queryClient.clear()
+ })
+ nuxt.hooks.hook('app:error', () => queryClient.clear())
+}
diff --git a/client/middleware/01.check-auth.global.js b/client/middleware/01.check-auth.global.js
index d362e4898..e5abf34e4 100644
--- a/client/middleware/01.check-auth.global.js
+++ b/client/middleware/01.check-auth.global.js
@@ -1,3 +1,4 @@
+import { isMarketingRoute } from '~/lib/marketing-route.js'
import { useQueryClient } from '@tanstack/vue-query'
const AUTH_COOKIE_NAME = 'opnform_token'
@@ -35,38 +36,54 @@ export default defineNuxtRouteMiddleware(async (to, _from) => {
return
}
- // Check for already cached user data (from SSR or previous fetch)
- let userData = queryClient.getQueryData(['user'])
+ const bootstrap = async () => {
+ const bootstrapToken = authStore.token
+ // Check for already cached user data (from SSR or previous fetch)
+ let userData = queryClient.getQueryData(['user'])
- // Fetch user & workspaces only if not cached yet
- if (!userData) {
- try {
- const userQuery = useAuth().user()
- const workspacesQuery = useWorkspaces().list()
- await Promise.all([userQuery.suspense(), workspacesQuery.suspense()])
+ // Fetch user & workspaces only if not cached yet
+ if (!userData) {
+ try {
+ const userQuery = useAuth().user()
+ const workspacesQuery = useWorkspaces().list()
+ await Promise.all([userQuery.suspense(), workspacesQuery.suspense()])
- userData = queryClient.getQueryData(['user'])
- } catch (error) {
- // A server-side bootstrap request can 401 even when the browser still has a
- // valid token (for example if SSR auth validation differs from the browser
- // request context). Do not destroy auth state during SSR; let the client
- // retry before treating it as a real logout.
- if (error?.status === 401) {
- if (import.meta.client) {
- authStore.clearToken()
- authStore.updateUser(null)
- queryClient.clear()
+ userData = queryClient.getQueryData(['user'])
+ } catch (error) {
+ // A server-side bootstrap request can 401 even when the browser still has a
+ // valid token (for example if SSR auth validation differs from the browser
+ // request context). Do not destroy auth state during SSR; let the client
+ // retry before treating it as a real logout.
+ if (error?.status === 401 && authStore.token === bootstrapToken) {
+ if (import.meta.client) {
+ authStore.clearToken()
+ authStore.updateUser(null)
+ queryClient.clear()
+ }
}
+ return
}
- return
+ }
+
+ // Initialize service clients on client side (no-op on server)
+ if (userData && authStore.token === bootstrapToken) {
+ authStore.updateUser(userData)
+ await import('~/composables/useServiceClients.js').then((serviceClients) => {
+ if (authStore.token === bootstrapToken) {
+ nuxtApp.runWithContext(() => serviceClients.initServiceClients(userData))
+ }
+ })
}
}
- // Initialize service clients on client side (no-op on server)
- if (userData) {
- authStore.updateUser(userData)
- await import('~/composables/useServiceClients.js').then((serviceClients) => {
- nuxtApp.runWithContext(() => serviceClients.initServiceClients(userData))
- })
+ if (isMarketingRoute(to)) {
+ if (import.meta.server) return
+ if (nuxtApp.isHydrating) {
+ nuxtApp.hook('app:mounted', () => nuxtApp.runWithContext(bootstrap))
+ } else {
+ void nuxtApp.runWithContext(bootstrap)
+ }
+ return
}
+ return bootstrap()
})
diff --git a/client/nuxt.config.ts b/client/nuxt.config.ts
index 2a7b44e0d..457ae97bd 100644
--- a/client/nuxt.config.ts
+++ b/client/nuxt.config.ts
@@ -18,7 +18,13 @@ export default defineNuxtConfig({
buildDir: buildDir || '.nuxt',
...(viteCacheDir ? {vite: {cacheDir: viteCacheDir}} : {}),
css: ['~/css/app.css'],
- nitro: { awsAmplify: { runtime: 'nodejs24.x' } },
+ nitro: { awsAmplify: { runtime: 'nodejs24.x' }, compressPublicAssets: { gzip: true, brotli: true } },
+ routeRules: {
+ '/_nuxt/**': { headers: { 'cache-control': 'public, max-age=31536000, immutable' } },
+ '/_nuxt/builds/latest.json': { headers: { 'cache-control': 'no-store' } },
+ '/fonts/**': { headers: { 'cache-control': 'public, max-age=3600' } },
+ '/img/**': { headers: { 'cache-control': 'public, max-age=3600' } },
+ },
content: {
experimental: { sqliteConnector: 'native' },
},
@@ -26,6 +32,23 @@ export default defineNuxtConfig({
postcss: { plugins: { '@tailwindcss/postcss': {} } },
hooks: {
+ 'vite:extendConfig': (config, { isClient }) => {
+ if (!isClient) return
+ config.build ||= {}
+ config.build.rolldownOptions ||= {}
+ config.build.rolldownOptions.output = {
+ ...config.build.rolldownOptions.output,
+ codeSplitting: {
+ groups: [{
+ name: 'shared-runtime',
+ // Consolidate common library code without pulling in optional app modules.
+ test: /node_modules\/(?:@vue\/|vue\/|vue-router\/|pinia\/|@vueuse\/|@unhead\/|unhead\/|@tanstack\/|reka-ui\/|defu\/|destr\/|ufo\/|ofetch\/|h3\/|unctx\/|hookable\/|klona\/|tailwind-variants\/|tailwind-merge\/)/,
+ minShareCount: 20,
+ includeDependenciesRecursively: false,
+ }],
+ },
+ }
+ },
'build:manifest': (manifest) => {
// Nuxt follows every dynamicImports edge while generating resource hints,
// including all route middleware, locales and optional form/editor code.
@@ -107,6 +130,7 @@ export default defineNuxtConfig({
experimental: {
inlineRouteRules: true,
+ defaults: { nuxtLink: { prefetchOn: { visibility: false, interaction: true } } },
emitRouteChunkError: 'manual'
},
diff --git a/client/package.json b/client/package.json
index 9b0bd73f3..00ed41633 100644
--- a/client/package.json
+++ b/client/package.json
@@ -3,7 +3,7 @@
"private": true,
"type": "module",
"scripts": {
- "build": "npm run build:sdk && NODE_OPTIONS=\"${NODE_OPTIONS:---max-old-space-size=8192}\" nuxt build && npm run check:public-form-bundle && npm run check:built-css",
+ "build": "npm run build:sdk && NODE_OPTIONS=\"${NODE_OPTIONS:---max-old-space-size=8192}\" nuxt build && npm run check:public-form-bundle && npm run check:landing-bundle && npm run check:built-css",
"build:e2e": "npm run build:sdk && E2E=1 NODE_OPTIONS=\"${NODE_OPTIONS:---max-old-space-size=8192}\" nuxt build",
"build:sdk": "esbuild public/widgets/opnform-sdk.js --minify --legal-comments=inline --banner:js='/* eslint-disable */' --outfile=public/widgets/opnform-sdk.min.js",
"dev": "node --import ./scripts/node-localstorage-polyfill.mjs ./node_modules/nuxt/bin/nuxt.mjs dev",
@@ -22,6 +22,7 @@
"test:e2e:headed": "playwright test --headed",
"test:e2e:dev": "PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-http://127.0.0.1:3100} playwright test",
"check:public-form-bundle": "node scripts/check-public-form-bundle.mjs",
+ "check:landing-bundle": "node scripts/check-landing-bundle.mjs",
"check:built-css": "node scripts/check-built-css.mjs",
"build:amplify": "NODE_OPTIONS=\"${NODE_OPTIONS:---max-old-space-size=4096}\" NITRO_PRESET=aws-amplify npm run build && node scripts/check-amplify-output.mjs"
},
diff --git a/client/pages/index.vue b/client/pages/index.vue
index fd3d1e7cc..b80c70499 100644
--- a/client/pages/index.vue
+++ b/client/pages/index.vue
@@ -1,6 +1,6 @@
<template>
<SelfHostedWelcome v-if="isSelfHosted" />
- <div v-else>
+ <main v-else class="marketing-landing">
<section>
<div class="pt-8 sm:pt-16 px-8 lg:px-12 max-w-7xl mx-auto relative">
<div class="max-w-3xl mx-auto text-center">
@@ -94,6 +94,7 @@
<NuxtLink
to="https://www.trustpilot.com/review/opnform.com"
+ aria-label="Read OpnForm reviews on Trustpilot"
target="_blank"
class="flex items-center gap-2"
>
@@ -134,10 +135,9 @@
</div>
<div class="relative pt-12 pb-12 sm:pb-24 px-8 lg:px-12">
<div class="pointer-events-none absolute inset-0">
- <img
- class="pointer-events-none w-full h-full object-cover object-top opacity-[0.20] relative z-1"
- src="/img/pages/ai_form_builder/background-pattern.svg"
- alt="Page abstract background"
+ <div
+ class="pointer-events-none absolute inset-0 z-1 bg-[url('/img/pages/ai_form_builder/background-pattern.svg')] bg-cover bg-top opacity-20"
+ aria-hidden="true"
/>
<div
class="w-full h-full bg-linear-to-b from-white from-35% via-blue-100 via-60% to-white to-85% absolute inset-0"
@@ -165,7 +165,7 @@
<!-- <AiFeature class="pb-8" /> -->
<div class="pt-12 sm:pt-16"><OpenFormFooter /></div>
- </div>
+ </main>
</template>
<script setup>
@@ -179,6 +179,8 @@ definePageMeta({
middleware: ["root-redirect"],
})
+useHead({ link: [{ rel: 'preload', href: '/img/pages/ai_form_builder/background-pattern.svg', as: 'image', fetchpriority: 'high' }] })
+
const { isAuthenticated: authenticated } = useIsAuthenticated()
const featureFlags = useState('featureFlags', () => ({}))
const isSelfHosted = computed(() => !!featureFlags.value.self_hosted)
@@ -194,6 +196,13 @@ useOpnSeoMeta({
</script>
<style lang="scss" scoped>
+.marketing-landing :deep(.bg-primary) {
+ background-color: #2563eb;
+}
+.marketing-landing :deep(.hover\:bg-primary\/75:hover) {
+ background-color: #1d4ed8;
+}
+
.customer-logo-container {
max-width: 130px;
width: 100%;
diff --git a/client/plugins/01.vue-query.ts b/client/plugins/01.vue-query.ts
index 15588aa1d..40ce84006 100644
--- a/client/plugins/01.vue-query.ts
+++ b/client/plugins/01.vue-query.ts
@@ -1,3 +1,4 @@
+import { registerSsrQueryCleanup } from '~/lib/ssr-query-cache.js'
import type {
DehydratedState,
VueQueryPluginOptions,
@@ -21,7 +22,7 @@ export default defineNuxtPlugin((nuxt) => {
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes
- gcTime: 10 * 60 * 1000, // 10 minutes (replaces cacheTime)
+ gcTime: import.meta.server ? Infinity : 10 * 60 * 1000,
retry: (failureCount, error: any) => {
// Don't retry on 4xx errors except 408, 429
if (error?.status >= 400 && error?.status < 500 && ![408, 429].includes(error?.status)) {
@@ -52,9 +53,7 @@ export default defineNuxtPlugin((nuxt) => {
nuxt.vueApp.use(VueQueryPlugin, options)
if (import.meta.server) {
- nuxt.hooks.hook('app:rendered', () => {
- vueQueryState.value = dehydrate(queryClient)
- })
+ registerSsrQueryCleanup(nuxt, queryClient, vueQueryState, dehydrate)
}
if (import.meta.client) {
diff --git a/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Italic.woff2 b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Italic.woff2
new file mode 100644
index 000000000..ea92bc6ab
Binary files /dev/null and b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Italic.woff2 differ
diff --git a/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Medium.woff2 b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Medium.woff2
new file mode 100644
index 000000000..843cd2a54
Binary files /dev/null and b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Medium.woff2 differ
diff --git a/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Regular.woff2 b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Regular.woff2
new file mode 100644
index 000000000..ba702dff8
Binary files /dev/null and b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-Regular.woff2 differ
diff --git a/client/public/fonts/euclid-circular-b/Euclid-Circular-B-SemiBold.woff2 b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-SemiBold.woff2
new file mode 100644
index 000000000..023b7c326
Binary files /dev/null and b/client/public/fonts/euclid-circular-b/Euclid-Circular-B-SemiBold.woff2 differ
diff --git a/client/public/img/pages/welcome/feature-1.webp b/client/public/img/pages/welcome/feature-1.webp
new file mode 100644
index 000000000..e6832cead
Binary files /dev/null and b/client/public/img/pages/welcome/feature-1.webp differ
diff --git a/client/public/img/pages/welcome/feature-2.webp b/client/public/img/pages/welcome/feature-2.webp
new file mode 100644
index 000000000..67bf404d5
Binary files /dev/null and b/client/public/img/pages/welcome/feature-2.webp differ
diff --git a/client/public/img/pages/welcome/feature-3-480.webp b/client/public/img/pages/welcome/feature-3-480.webp
new file mode 100644
index 000000000..212df016f
Binary files /dev/null and b/client/public/img/pages/welcome/feature-3-480.webp differ
diff --git a/client/public/img/pages/welcome/feature-3-640.webp b/client/public/img/pages/welcome/feature-3-640.webp
new file mode 100644
index 000000000..65a6cacb3
Binary files /dev/null and b/client/public/img/pages/welcome/feature-3-640.webp differ
diff --git a/client/public/img/pages/welcome/feature-3.webp b/client/public/img/pages/welcome/feature-3.webp
new file mode 100644
index 000000000..dfa129fbe
Binary files /dev/null and b/client/public/img/pages/welcome/feature-3.webp differ
diff --git a/client/public/img/pages/welcome/powerForm-bg.webp b/client/public/img/pages/welcome/powerForm-bg.webp
new file mode 100644
index 000000000..2c61c98e0
Binary files /dev/null and b/client/public/img/pages/welcome/powerForm-bg.webp differ
diff --git a/client/public/img/pages/welcome/product-cover-half.webp b/client/public/img/pages/welcome/product-cover-half.webp
new file mode 100644
index 000000000..4f2e9c992
Binary files /dev/null and b/client/public/img/pages/welcome/product-cover-half.webp differ
diff --git a/client/scripts/check-landing-bundle.mjs b/client/scripts/check-landing-bundle.mjs
new file mode 100644
index 000000000..55c5cd293
--- /dev/null
+++ b/client/scripts/check-landing-bundle.mjs
@@ -0,0 +1,38 @@
+import { readFileSync, existsSync } from 'node:fs'
+import { gzipSync } from 'node:zlib'
+import { resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+const root = resolve(import.meta.dirname, '..')
+const build = resolve(root, process.env.NUXT_BUILD_DIR || '.nuxt')
+const manifest = (await import(pathToFileURL(resolve(build, 'dist/server/client.manifest.mjs')))).default
+const roots = ['node_modules/nuxt/dist/app/entry.js', 'pages/index.vue']
+const entries = new Set()
+function collect(key) {
+ if (entries.has(key) || !manifest[key]) return
+ entries.add(key)
+ for (const child of manifest[key].imports || []) collect(child)
+}
+for (const entry of roots) {
+ if (!manifest[entry]) throw new Error(`Missing landing entry: ${entry}`)
+ collect(entry)
+}
+let bytes = 0
+let scripts = 0
+const forbidden = ['/codemirror/', '/@codemirror/', '/quill/', '/vue-country-flag-next/', '/crisp-sdk-web/', '/@microsoft/clarity/']
+for (const key of entries) {
+ const entry = manifest[key]
+ if (entry.resourceType !== 'script') continue
+ scripts++
+ const file = resolve(build, 'dist/client/_nuxt', entry.file)
+ bytes += gzipSync(readFileSync(file)).length
+ if (!existsSync(`${file}.map`)) continue
+ const map = JSON.parse(readFileSync(`${file}.map`, 'utf8'))
+ for (const source of map.sources || []) {
+ if (forbidden.some(fragment => source.replaceAll('\\', '/').includes(fragment))) {
+ throw new Error(`Optional dependency in the landing's static graph: ${source}`)
+ }
+ }
+}
+console.log(`Landing static JavaScript: ${(bytes / 1024).toFixed(1)} KiB gzip across ${scripts} files.`)
+if (bytes > 375 * 1024 || scripts > 50) throw new Error('Landing exceeds its 375 KiB gzip / 50 static script budget.')
diff --git a/client/scripts/measure-landing-performance.mjs b/client/scripts/measure-landing-performance.mjs
new file mode 100644
index 000000000..832dd6fc0
--- /dev/null
+++ b/client/scripts/measure-landing-performance.mjs
@@ -0,0 +1,438 @@
+import { createServer, request } from 'node:http'
+import { createSecureServer } from 'node:http2'
+import { gzipSync } from 'node:zlib'
+import { spawn, execFileSync } from 'node:child_process'
+import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs'
+import { chromium } from '@playwright/test'
+import { getLiveDemoScenario } from '../data/live-demo-scenarios.js'
+const [label, build] = process.argv.slice(2)
+const root = process.cwd()
+mkdirSync('.e2e/performance', { recursive: true })
+if (!label || !build)
+ throw new Error(
+ 'Run from the repository root: node client/scripts/measure-landing-performance.mjs LABEL BUILD_DIRECTORY',
+ )
+const listen = (s) =>
+ new Promise((r) => s.listen(0, '127.0.0.1', () => r(s.address().port)))
+const calls = []
+const fixtureForm = {
+ ...getLiveDemoScenario({ variant: 'home' }).form,
+ slug: 'performance-fixture',
+ workspace: { id: 1, settings: {} },
+}
+const api = createServer((req, res) => {
+ calls.push(req.url)
+ res.setHeader('content-type', 'application/json')
+ res.setHeader('access-control-allow-origin', '*')
+ res.setHeader('access-control-allow-headers', 'authorization, content-type')
+ if (req.method === 'OPTIONS') {
+ res.writeHead(204)
+ res.end()
+ return
+ }
+ const body =
+ req.url === '/forms/performance-fixture'
+ ? fixtureForm
+ : req.url.includes('feature-flags')
+ ? {
+ self_hosted: false,
+ setup_required: false,
+ billing: { enabled: true },
+ services: {},
+ custom_domains: { enabled: false },
+ }
+ : req.url.includes('/content/plans')
+ ? {
+ tiers: {
+ free: { name: 'Free', features: [] },
+ pro: { name: 'Pro', features: [] },
+ },
+ }
+ : req.url.includes('/user')
+ ? {
+ id: 1,
+ name: 'Local QA',
+ email: '[email protected]',
+ active_license: null,
+ is_subscribed: false,
+ }
+ : []
+ res.end(JSON.stringify(body))
+})
+const apiPort = await listen(api)
+const reservation = createServer()
+const port = await listen(reservation)
+await new Promise((r) => reservation.close(r))
+const upstreamOrigin = `http://127.0.0.1:${port}`
+let origin = upstreamOrigin
+let proxy
+if (process.env.PERF_HTTP2 === '1') {
+ const certificate = '.e2e/performance/localhost.crt'
+ const privateKey = '.e2e/performance/localhost.key'
+ if (!existsSync(certificate) || !existsSync(privateKey)) {
+ execFileSync(
+ 'openssl',
+ [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'rsa:2048',
+ '-nodes',
+ '-days',
+ '1',
+ '-subj',
+ '/CN=localhost',
+ '-keyout',
+ privateKey,
+ '-out',
+ certificate,
+ ],
+ { stdio: 'ignore' },
+ )
+ }
+ const clean = (headers) =>
+ Object.fromEntries(
+ Object.entries(headers).filter(
+ ([key]) =>
+ !key.startsWith(':') &&
+ ![
+ 'connection',
+ 'keep-alive',
+ 'transfer-encoding',
+ 'upgrade',
+ 'http2-settings',
+ ].includes(key.toLowerCase()),
+ ),
+ )
+ proxy = createSecureServer(
+ {
+ key: readFileSync(privateKey),
+ cert: readFileSync(certificate),
+ allowHTTP1: true,
+ },
+ (req, res) => {
+ const apiRequest = req.url.startsWith('/fixture-api/')
+ const upstream = request(
+ {
+ hostname: '127.0.0.1',
+ port: apiRequest ? apiPort : port,
+ path: apiRequest ? req.url.slice('/fixture-api'.length) : req.url,
+ method: req.method,
+ headers: {
+ ...clean(req.headers),
+ host: new URL(origin).host,
+ 'x-forwarded-proto': 'https',
+ },
+ },
+ (response) => {
+ const chunks = []
+ response.on('data', (chunk) => chunks.push(chunk))
+ response.on('end', () => {
+ let body = Buffer.concat(chunks)
+ const headers = clean(response.headers)
+ if (
+ !headers['content-encoding'] &&
+ /text|javascript|json|svg/.test(headers['content-type'] || '') &&
+ String(req.headers['accept-encoding']).includes('gzip')
+ ) {
+ body = gzipSync(body)
+ headers['content-encoding'] = 'gzip'
+ headers.vary = 'Accept-Encoding'
+ }
+ headers['content-length'] = body.length
+ res.writeHead(response.statusCode, headers)
+ res.end(body)
+ })
+ },
+ )
+ upstream.on('error', () => {
+ if (!res.headersSent) res.writeHead(502)
+ res.end()
+ })
+ req.pipe(upstream)
+ },
+ )
+ origin = `https://127.0.0.1:${await listen(proxy)}`
+}
+const server = spawn(
+ process.execPath,
+ ['--expose-gc', '--inspect=127.0.0.1:0', build + '/server/index.mjs'],
+ {
+ cwd: root,
+ env: {
+ PATH: process.env.PATH,
+ NODE_ENV: 'production',
+ NITRO_HOST: '127.0.0.1',
+ NITRO_PORT: String(port),
+ NUXT_PUBLIC_ENV: 'testing',
+ NUXT_PUBLIC_APP_URL: origin,
+ NUXT_PRIVATE_API_BASE: `http://127.0.0.1:${apiPort}`,
+ NUXT_PUBLIC_API_BASE: proxy
+ ? `${origin}/fixture-api`
+ : `http://127.0.0.1:${apiPort}`,
+ NUXT_API_SECRET: 'fictional-local-qa',
+ },
+ },
+)
+let logs = ''
+server.stdout.on('data', (d) => (logs += d))
+server.stderr.on('data', (d) => (logs += d))
+let browser
+let inspector
+try {
+ for (let i = 0; i < 200 && !logs.includes('Listening on'); i++) {
+ if (server.exitCode !== null) throw Error(logs.slice(-1200))
+ await new Promise((r) => setTimeout(r, 100))
+ }
+ const chrome =
+ process.env.PERF_CHROME_BIN ||
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
+ browser = await chromium.launch({
+ ...(existsSync(chrome) ? { executablePath: chrome } : {}),
+ headless: true,
+ })
+ // Warm both builds identically before measuring browser navigation.
+ for (let i = 0; i < 2; i++) await fetch(upstreamOrigin).then((r) => r.text())
+ inspector = new WebSocket(logs.match(/ws:\/\/127\.0\.0\.1:[^\s]+/)[0])
+ await new Promise((r) =>
+ inspector.addEventListener('open', r, { once: true }),
+ )
+ let messageId = 0
+ const heap = () =>
+ new Promise((resolve) => {
+ const id = ++messageId
+ const handler = (e) => {
+ const data = JSON.parse(e.data)
+ if (data.id === id) {
+ inspector.removeEventListener('message', handler)
+ resolve(JSON.parse(data.result.result.value))
+ }
+ }
+ inspector.addEventListener('message', handler)
+ inspector.send(
+ JSON.stringify({
+ id,
+ method: 'Runtime.evaluate',
+ params: {
+ expression: 'global.gc(); JSON.stringify(process.memoryUsage())',
+ returnByValue: true,
+ },
+ }),
+ )
+ })
+ const results = { label, node: process.version, build, scenarios: [] }
+ for (const authenticated of [false, true]) {
+ const context = await browser.newContext({
+ viewport: { width: 412, height: 823 },
+ deviceScaleFactor: 1,
+ isMobile: true,
+ ignoreHTTPSErrors: true,
+ })
+ await context.route('**/*', (route) =>
+ route.request().url().startsWith(origin) ||
+ route.request().url().startsWith(`http://127.0.0.1:${apiPort}`)
+ ? route.continue()
+ : route.abort(),
+ )
+ if (authenticated)
+ await context.addCookies([
+ {
+ name: 'opnform_token',
+ value: 'fictional-local-token',
+ url: origin,
+ },
+ ])
+ const page = await context.newPage()
+ page.on('console', (m) => {
+ if (m.type() === 'error' || m.type() === 'warning')
+ process.stderr.write(m.text().slice(0, 1000) + '\n')
+ })
+ const cdp = await context.newCDPSession(page)
+ await cdp.send('Network.enable')
+ await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
+ const responses = []
+ const errors = []
+ page.on('pageerror', (e) => {
+ errors.push(e.stack || e.message)
+ process.stderr.write((e.stack || e.message) + '\n')
+ })
+ page.on('response', (r) => {
+ if (r.url().startsWith(origin))
+ responses.push({
+ url: r.url().replace(origin, ''),
+ type: r.request().resourceType(),
+ status: r.status(),
+ })
+ })
+ await page.addInitScript(() => {
+ window.__perf = { lcp: 0, cls: 0, longTasks: 0 }
+ new PerformanceObserver((l) =>
+ l.getEntries().forEach((e) => (window.__perf.lcp = e.startTime)),
+ ).observe({ type: 'largest-contentful-paint', buffered: true })
+ new PerformanceObserver((l) =>
+ l.getEntries().forEach((e) => {
+ if (!e.hadRecentInput) window.__perf.cls += e.value
+ }),
+ ).observe({ type: 'layout-shift', buffered: true })
+ new PerformanceObserver((l) =>
+ l
+ .getEntries()
+ .forEach(
+ (e) => (window.__perf.longTasks += Math.max(0, e.duration - 50)),
+ ),
+ ).observe({ type: 'longtask', buffered: true })
+ })
+ const response = await page.goto(origin, {
+ waitUntil: 'networkidle',
+ timeout: 60000,
+ })
+ if (response.status() !== 200)
+ throw new Error(
+ 'Landing returned ' +
+ response.status() +
+ ': ' +
+ (await page.locator('body').innerText()).slice(0, 500),
+ )
+ await page
+ .locator('h1')
+ .filter({ hasText: 'Beautiful forms' })
+ .waitFor({ timeout: 15000 })
+ await page.waitForTimeout(3000)
+ const metrics = await page.evaluate(() => ({
+ ...window.__perf,
+ ttfb: performance.getEntriesByType('navigation')[0].responseStart,
+ htmlBytes: document.documentElement.outerHTML.length,
+ modulepreloads: document.querySelectorAll('link[rel=modulepreload]')
+ .length,
+ resources: performance.getEntriesByType('resource').map((e) => ({
+ name: e.name,
+ transfer: e.transferSize,
+ decoded: e.decodedBodySize,
+ })),
+ lang: document.documentElement.lang,
+ main: document.querySelectorAll('main').length,
+ }))
+ const own = metrics.resources.filter((r) => r.name.startsWith(origin))
+ results.scenarios.push({
+ authenticated,
+ ...metrics,
+ resources: undefined,
+ transferred: own.reduce((s, r) => s + r.transfer, 0),
+ jsRequests: responses.filter((r) => r.type === 'script').length,
+ imageRequests: responses.filter((r) => r.type === 'image').length,
+ responses,
+ errors,
+ apiCalls: [...calls],
+ })
+ await page.mouse.wheel(0, 700)
+ await page
+ .locator('.live-demo-form')
+ .waitFor({ timeout: 15000 })
+ .catch(async (error) => {
+ writeFileSync('.e2e/performance/debug.html', await page.content())
+ await page.screenshot({ path: '.e2e/performance/debug.png' })
+ throw error
+ })
+ await page.waitForLoadState('networkidle')
+ results.scenarios.at(-1).afterDemoJsRequests = responses.filter(
+ (r) => r.type === 'script',
+ ).length
+ await page.screenshot({
+ path: `.e2e/performance/${label}-${authenticated ? 'member' : 'anonymous'}.png`,
+ fullPage: true,
+ })
+ await context.close()
+ }
+ const formUrl = upstreamOrigin + '/forms/performance-fixture'
+ const formWarmup = await fetch(formUrl)
+ if (formWarmup.status !== 200)
+ throw new Error('SSR form fixture did not render: ' + formWarmup.status)
+ await formWarmup.text()
+ if (process.env.PERF_LIGHTHOUSE === '1') {
+ const args = [
+ '--yes',
+ '--',
+ 'lighthouse',
+ origin,
+ '--quiet',
+ '--only-categories=performance',
+ '--output=json',
+ `--output-path=.e2e/performance/${label}-lighthouse.json`,
+ '--chrome-flags=--headless --no-sandbox --ignore-certificate-errors',
+ '--max-wait-for-load=90000',
+ ]
+ await new Promise((resolve, reject) => {
+ const child = spawn('npx', args, {
+ env: {
+ ...process.env,
+ CHROME_PATH: existsSync(chrome) ? chrome : chromium.executablePath(),
+ },
+ })
+ let output = ''
+ child.stdout.on('data', (d) => {
+ output += d
+ })
+ child.stderr.on('data', (d) => {
+ output += d
+ })
+ child.on('error', reject)
+ child.on('exit', (code) =>
+ code === 0 ? resolve() : reject(new Error(output.slice(-2000))),
+ )
+ })
+ }
+ const heapBefore = await heap()
+ const before = Number(
+ execFileSync('ps', ['-o', 'rss=', '-p', String(server.pid)], {
+ encoding: 'utf8',
+ }).trim(),
+ )
+ for (let b = 0; b < 100; b++)
+ await Promise.all(
+ Array.from({ length: 10 }, () =>
+ fetch(formUrl).then((r) => {
+ if (r.status !== 200) throw new Error('SSR load response ' + r.status)
+ return r.text()
+ }),
+ ),
+ )
+ const heapAfter = await heap()
+ inspector.close()
+ results.ssr = {
+ heapBefore,
+ heapAfter,
+ requests: 1000,
+ rssBeforeKiB: before,
+ rssAfterKiB: Number(
+ execFileSync('ps', ['-o', 'rss=', '-p', String(server.pid)], {
+ encoding: 'utf8',
+ }).trim(),
+ ),
+ }
+ writeFileSync(
+ `.e2e/performance/${label}.json`,
+ JSON.stringify(results, null, 2),
+ )
+ console.log(
+ JSON.stringify(
+ {
+ ...results,
+ scenarios: results.scenarios.map(
+ ({ responses: _responses, apiCalls: _apiCalls, ...s }) => s,
+ ),
+ },
+ null,
+ 2,
+ ),
+ )
+ if (results.scenarios.some((s) => s.errors.length))
+ throw new Error('Browser startup failed; see the saved performance report')
+} finally {
+ inspector?.close()
+ await browser?.close()
+ server.kill('SIGTERM')
+ api.close()
+ proxy?.close()
+}
diff --git a/client/server/plugins/staticAssetErrors.js b/client/server/plugins/staticAssetErrors.js
new file mode 100644
index 000000000..2772cb582
--- /dev/null
+++ b/client/server/plugins/staticAssetErrors.js
@@ -0,0 +1,9 @@
+export default defineNitroPlugin((nitroApp) => {
+ nitroApp.hooks.hook('render:response', (response) => {
+ // Route headers also apply to missing assets. Never retain error documents.
+ if (response.statusCode >= 400) {
+ response.headers['cache-control'] = 'no-store'
+ delete response.headers['Cache-Control']
+ }
+ })
+})
diff --git a/client/test/nuxt/clarity-lazy.spec.ts b/client/test/nuxt/clarity-lazy.spec.ts
new file mode 100644
index 000000000..479c849be
--- /dev/null
+++ b/client/test/nuxt/clarity-lazy.spec.ts
@@ -0,0 +1,25 @@
+import { it, expect, vi } from 'vitest'
+import { mount, flushPromises } from '@vue/test-utils'
+import Clarity from '~/components/vendor/Clarity.vue'
+
+const state = vi.hoisted(() => {
+ let resolve
+ const promise = new Promise(done => { resolve = done })
+ return { promise, resolve, requested: false, init: vi.fn() }
+})
+vi.mock('@microsoft/clarity', async () => {
+ state.requested = true
+ await state.promise
+ return { default: { init: state.init, identify: vi.fn() } }
+})
+
+it('does not initialize an SDK that finishes loading after leaving the page', async () => {
+ useRuntimeConfig().public.clarityProjectId = 'local-test'
+ vi.stubGlobal('useAuthStore', () => ({ token: 'local-session', user: { id: 1 } }))
+ const wrapper = mount(Clarity)
+ await vi.waitFor(() => expect(state.requested).toBe(true))
+ wrapper.unmount()
+ state.resolve()
+ await flushPromises()
+ expect(state.init).not.toHaveBeenCalled()
+})
diff --git a/client/test/nuxt/deferred-auth-failure.spec.ts b/client/test/nuxt/deferred-auth-failure.spec.ts
new file mode 100644
index 000000000..1b1837ddf
--- /dev/null
+++ b/client/test/nuxt/deferred-auth-failure.spec.ts
@@ -0,0 +1,19 @@
+import { beforeEach, it, expect, vi } from 'vitest'
+import { getOpnRequestsOptions } from '~/composables/useOpnApi.js'
+
+const state = vi.hoisted(() => ({ store: { token: 'old-session' }, expire: vi.fn() }))
+vi.mock('~/composables/useAuthFlow', () => ({ useAuthFlow: () => ({ handleTokenExpiry: state.expire }) }))
+vi.mock('~/lib/utils.js', () => ({ customDomainUsed: () => false, getHost: () => '', getDomain: () => '' }))
+beforeEach(() => { state.store.token = 'old-session'; state.expire.mockReset(); vi.stubGlobal('useAuthStore', () => state.store) })
+
+it('does not expire the new session when an older deferred request returns 401', async () => {
+ const options = useNuxtApp().runWithContext(() => getOpnRequestsOptions('/open/user', {}))
+ state.store.token = 'new-session'
+ await options.onResponseError({ response: { status: 401 } })
+ expect(state.expire).not.toHaveBeenCalled()
+})
+it('still handles expiration of the current session', async () => {
+ const options = useNuxtApp().runWithContext(() => getOpnRequestsOptions('/open/user', {}))
+ await options.onResponseError({ response: { status: 401 } })
+ expect(state.expire).toHaveBeenCalledOnce()
+})
diff --git a/client/test/nuxt/featurebase-lazy.spec.ts b/client/test/nuxt/featurebase-lazy.spec.ts
new file mode 100644
index 000000000..50953c4be
--- /dev/null
+++ b/client/test/nuxt/featurebase-lazy.spec.ts
@@ -0,0 +1,127 @@
+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest'
+import { mount } from '@vue/test-utils'
+import { ref, nextTick } from 'vue'
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import FeatureBase from '~/components/vendor/FeatureBase.vue'
+import { useSharedNavigation } from '~/composables/components/useSharedNavigation.js'
+
+const state = vi.hoisted(() => ({ user: null }))
+mockNuxtImport('useAuth', () => () => ({ user: () => ({ data: state.user }) }))
+mockNuxtImport('useCrisp', () => () => null)
+mockNuxtImport('useFeatureFlag', () => () => false)
+
+beforeEach(() => {
+ useRuntimeConfig().public.featureBaseOrganization = 'local-test'
+ state.user = ref({ id: 1, name: 'QA', email: '[email protected]' })
+ vi.stubGlobal('useAuthStore', () => ({ isImpersonating: false }))
+ vi.stubGlobal('useAppStore', () => ({ featureBaseButtonVisible: true, featureBaseEnabled: true }))
+ useState('featurebase-changelog-requested').value = false
+})
+afterEach(() => { document.getElementById('featurebase-sdk')?.remove(); delete window.Featurebase })
+
+function requestChangelog() {
+ useNuxtApp().runWithContext(() => {
+ const navigation = useSharedNavigation()
+ navigation.sharedNavigationSections.value.flatMap(section => section.items)
+ .find(item => item.label === "What's new").onClick()
+ })
+}
+
+describe('feedback SDK loading', () => {
+ it('loads once on first intent and opens the feedback widget once it is ready', async () => {
+ const sdk = vi.fn()
+ window.Featurebase = sdk
+ const wrapper = mount(FeatureBase, { attachTo: document.body, global: { stubs: { Icon: true } } })
+ expect(document.getElementById('featurebase-sdk')).toBeNull()
+ await wrapper.get('button').trigger('click')
+ const script = document.getElementById('featurebase-sdk')
+ await wrapper.get('button').trigger('click')
+ expect(document.querySelectorAll('#featurebase-sdk')).toHaveLength(1)
+ script.dispatchEvent(new Event('load'))
+ const init = sdk.mock.calls.find(call => call[0] === 'initialize_feedback_widget')
+ expect(init).toBeTruthy()
+ const click = vi.fn()
+ wrapper.element.addEventListener('click', click)
+ init[2](null, { action: 'widgetReady' })
+ expect(click).toHaveBeenCalledTimes(1)
+ wrapper.unmount()
+ })
+ it('reuses the loaded SDK after remount while rebuilding the widgets', async () => {
+ const sdk = vi.fn()
+ window.Featurebase = sdk
+ let wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ await wrapper.get('button').trigger('click')
+ const script = document.getElementById('featurebase-sdk')
+ script.dispatchEvent(new Event('load'))
+ wrapper.unmount()
+ expect(sdk).toHaveBeenCalledWith('destroy_feedback_widget')
+ sdk.mockClear()
+ wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ await wrapper.get('button').trigger('click')
+ expect(document.getElementById('featurebase-sdk')).toBe(script)
+ expect(sdk.mock.calls.some(call => call[0] === 'initialize_feedback_widget')).toBe(true)
+ wrapper.unmount()
+ })
+ it('allows retrying a failed SDK download', async () => {
+ const wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ await wrapper.get('button').trigger('click')
+ document.getElementById('featurebase-sdk').dispatchEvent(new Event('error'))
+ expect(document.getElementById('featurebase-sdk')).toBeNull()
+ await wrapper.get('button').trigger('click')
+ expect(document.querySelectorAll('#featurebase-sdk')).toHaveLength(1)
+ wrapper.unmount()
+ })
+ it('allows retrying when the component remounts during a failed SDK download', async () => {
+ let wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ await wrapper.get('button').trigger('click')
+ const script = document.getElementById('featurebase-sdk')
+ wrapper.unmount()
+ wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ await wrapper.get('button').trigger('click')
+ expect(document.getElementById('featurebase-sdk')).toBe(script)
+ script.dispatchEvent(new Event('error'))
+ await wrapper.get('button').trigger('click')
+ expect(document.querySelectorAll('#featurebase-sdk')).toHaveLength(1)
+ expect(document.getElementById('featurebase-sdk')).not.toBe(script)
+ wrapper.unmount()
+ })
+ it('loads and opens changelog as the first interaction, including intent before vendor mount', async () => {
+ requestChangelog()
+ expect(document.getElementById('featurebase-sdk')).toBeNull()
+ const wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ const script = document.getElementById('featurebase-sdk')
+ expect(script).not.toBeNull()
+ const sdk = vi.fn()
+ window.Featurebase = sdk
+ script.dispatchEvent(new Event('load'))
+ const initialize = sdk.mock.calls.find(call => call[0] === 'initialize_changelog_widget')
+ expect(initialize).toBeTruthy()
+ expect(sdk).not.toHaveBeenCalledWith('manually_open_changelog_popup')
+ initialize[2](null, { action: 'unreadChangelogsCountChanged', unreadCount: 0 })
+ expect(sdk.mock.calls.filter(call => call[0] === 'manually_open_changelog_popup')).toHaveLength(1)
+ requestChangelog()
+ await nextTick()
+ expect(sdk.mock.calls.filter(call => call[0] === 'manually_open_changelog_popup')).toHaveLength(2)
+ wrapper.unmount()
+ })
+ it('retains changelog intent while the user query is loading', async () => {
+ state.user.value = null
+ requestChangelog()
+ const wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ expect(document.getElementById('featurebase-sdk')).toBeNull()
+ state.user.value = { id: 1, email: '[email protected]' }
+ await nextTick()
+ expect(document.getElementById('featurebase-sdk')).not.toBeNull()
+ wrapper.unmount()
+ })
+ it('retries a failed changelog download on another navigation click', async () => {
+ const wrapper = mount(FeatureBase, { global: { stubs: { Icon: true } } })
+ requestChangelog()
+ await nextTick()
+ document.getElementById('featurebase-sdk').dispatchEvent(new Event('error'))
+ requestChangelog()
+ await nextTick()
+ expect(document.querySelectorAll('#featurebase-sdk')).toHaveLength(1)
+ wrapper.unmount()
+ })
+})
diff --git a/client/test/nuxt/suspended-auth-expiry.spec.ts b/client/test/nuxt/suspended-auth-expiry.spec.ts
new file mode 100644
index 000000000..10b138146
--- /dev/null
+++ b/client/test/nuxt/suspended-auth-expiry.spec.ts
@@ -0,0 +1,25 @@
+import { it, expect, vi } from 'vitest'
+import { getOpnRequestsOptions } from '~/composables/useOpnApi.js'
+
+const state = vi.hoisted(() => {
+ let resolve
+ const ready = new Promise(done => { resolve = done })
+ return { ready, resolve, loading: false, store: { token: 'old-session' }, expire: vi.fn() }
+})
+vi.mock('~/composables/useAuthFlow', async () => {
+ state.loading = true
+ await state.ready
+ return { useAuthFlow: () => ({ handleTokenExpiry: state.expire }) }
+})
+vi.mock('~/lib/utils.js', () => ({ customDomainUsed: () => false, getHost: () => '', getDomain: () => '' }))
+
+it('keeps a fresh session when login finishes during the auth module download', async () => {
+ vi.stubGlobal('useAuthStore', () => state.store)
+ const options = useNuxtApp().runWithContext(() => getOpnRequestsOptions('/open/user', {}))
+ const pending = options.onResponseError({ response: { status: 401 } })
+ await vi.waitFor(() => expect(state.loading).toBe(true))
+ state.store.token = 'new-session'
+ state.resolve()
+ await pending
+ expect(state.expire).not.toHaveBeenCalled()
+})
diff --git a/client/test/unit/ssr-query-cache.test.ts b/client/test/unit/ssr-query-cache.test.ts
new file mode 100644
index 000000000..f587d6424
--- /dev/null
+++ b/client/test/unit/ssr-query-cache.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect, vi } from 'vitest'
+import { QueryClient, dehydrate } from '@tanstack/vue-query'
+import { registerSsrQueryCleanup } from '../../lib/ssr-query-cache.js'
+import { isMarketingRoute } from '../../lib/marketing-route.js'
+
+describe('SSR request cache lifetime', () => {
+ it('releases every query after dehydration while retaining the response payload', () => {
+ const callbacks = new Map()
+ const nuxt = { hooks: { hook: (event, callback) => callbacks.set(event, callback) } }
+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
+ const state = { value: null }
+ registerSsrQueryCleanup(nuxt, client, state, dehydrate)
+ client.setQueryData(['form'], { title: 'Public form', fields: ['Œ', 'é', '中文'] })
+ callbacks.get('app:rendered')()
+ expect(client.getQueryCache().getAll()).toHaveLength(0)
+ expect(state.value.queries[0].state.data.fields).toEqual(['Œ', 'é', '中文'])
+ })
+ it('clears aborted renders without serializing failed request data', () => {
+ const callbacks = new Map()
+ const client = new QueryClient()
+ const state = { value: null }
+ const dehydrateSpy = vi.fn()
+ registerSsrQueryCleanup({ hooks: { hook: (event, callback) => callbacks.set(event, callback) } }, client, state, dehydrateSpy)
+ client.setQueryData(['user'], { id: 42 })
+ callbacks.get('app:error')()
+ expect(client.getQueryCache().getAll()).toHaveLength(0)
+ expect(dehydrateSpy).not.toHaveBeenCalled()
+ expect(state.value).toBeNull()
+ })
+})
+
+it.each(['/home', '/forms/a/edit', '/settings', '/admin', '/oauth/callback', '/setup', '/forms/create', '/mcp/private'])('keeps private and authentication routes synchronous: %s', (path) => {
+ expect(isMarketingRoute({ path })).toBe(false)
+})
+it.each(['/', '/pricing', '/integrations', '/integrations/slack', '/opnform-vs-typeform', '/ai-form-builder'])('defers private bootstrap on marketing route %s', (path) => {
+ expect(isMarketingRoute({ path })).toBe(true)
+})
diff --git a/client/tests/ssr-config-cache-built.test.mjs b/client/tests/ssr-config-cache-built.test.mjs
index eaac863fe..aaa5e953c 100644
--- a/client/tests/ssr-config-cache-built.test.mjs
+++ b/client/tests/ssr-config-cache-built.test.mjs
@@ -2,7 +2,7 @@ import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import { spawn } from 'node:child_process'
-import { access } from 'node:fs/promises'
+import { access, readdir } from 'node:fs/promises'
const client = new URL('../', import.meta.url)
const listen = (server) => new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port)))
@@ -65,6 +65,24 @@ test('built Nuxt exits setup immediately, then reuses configuration across SSR p
}
assert.equal(calls.get('/content/feature-flags'), 3)
assert.equal(calls.get('/content/plans'), 1)
+ const hashedFile = (await readdir(new URL('.output/public/_nuxt/', client))).find(name => name.endsWith('.js'))
+ assert.ok(hashedFile)
+ const script = await fetch(`${origin}/_nuxt/${hashedFile}`, { headers: { 'accept-encoding': 'br' } })
+ assert.equal(script.status, 200)
+ assert.equal(script.headers.get('cache-control'), 'public, max-age=31536000, immutable')
+ assert.equal(script.headers.get('content-encoding'), 'br')
+ assert.ok((await script.text()).length > 0)
+ const regular = await fetch(`${origin}/img/logo.svg`)
+ assert.equal(regular.status, 200)
+ assert.equal(regular.headers.get('cache-control'), 'public, max-age=3600')
+ const conditional = await fetch(`${origin}/img/logo.svg`, { headers: { 'if-none-match': regular.headers.get('etag') } })
+ assert.equal(conditional.status, 304)
+ const missing = await fetch(`${origin}/img/does-not-exist.png`)
+ assert.equal(missing.status, 404)
+ assert.ok(!/immutable|max-age=[1-9]/.test(missing.headers.get('cache-control') || ''))
+ const login = await fetch(`${origin}/login`)
+ assert.equal(login.headers.get('cache-control'), 'private, no-store')
+
} finally {
if (child && child.exitCode === null) {
const exited = new Promise((resolve) => child.once('exit', resolve))
diff --git a/deploy/scaleway/coolify-service-release.py b/deploy/scaleway/coolify-service-release.py
index f5e574f9a..420ffa108 100644
--- a/deploy/scaleway/coolify-service-release.py
+++ b/deploy/scaleway/coolify-service-release.py
@@ -158,6 +158,22 @@ if($x['apply']){
if(file_exists($file))throw new RuntimeException('Prior promotion needs inspection');
if(file_put_contents($file,$s->docker_compose_raw,LOCK_EX)===false)throw new RuntimeException('Cannot save previous configuration');chmod($file,0600);
foreach($roles as$r)$raw['services'][$r]['image']=$x['native_images'][$r==='frontend'?'frontend':'backend'];
+ $frontend=&$raw['services']['frontend'];
+ $frontend['mem_limit']='2g';
+ if(isset($frontend['deploy']['resources']['limits']['memory']))$frontend['deploy']['resources']['limits']['memory']='2g';
+ $env=$frontend['environment']??[];
+ $nodeOptions='';
+ if(array_is_list($env)){
+ foreach($env as$v)if(str_starts_with($v,'NODE_OPTIONS='))$nodeOptions=substr($v,13);
+ $env=array_values(array_filter($env,fn($v)=>!str_starts_with($v,'NODE_OPTIONS=')));
+ }else{$nodeOptions=$env['NODE_OPTIONS']??'';}
+ $nodeOptions=trim(preg_replace('/(?:^|\\s)--max-old-space-size(?:=|\\s+)\\d+(?=\\s|$)/','',$nodeOptions)).' --max-old-space-size=1536';
+ if(array_is_list($env)){
+ $env[]='NODE_OPTIONS='.trim($nodeOptions);
+ }else{$env['NODE_OPTIONS']=trim($nodeOptions);}
+ $frontend['environment']=$env;
+ unset($frontend);
+
$s->docker_compose_raw=json_encode($raw,JSON_THROW_ON_ERROR);$s->save();$s->parse();$s->saveComposeConfigs();
}
echo json_encode(['service_uuid'=>$s->uuid,'server_id'=>$s->server_id,'images_selected'=>$x['apply'],'containers_restarted'=>false]);
diff --git a/deploy/scaleway/entrypoint.sh b/deploy/scaleway/entrypoint.sh
index 5d6389269..0e111ccec 100644
--- a/deploy/scaleway/entrypoint.sh
+++ b/deploy/scaleway/entrypoint.sh
@@ -5,7 +5,13 @@ case "${APP_ROLE:-api}" in api|jobs|scheduler|migrate) ;; *) echo 'Unknown APP_R
rm -f bootstrap/cache/config.php
php /opt/opnform/preflight.php
# Compile only local runtime configuration. Never flush the shared cache here.
-php artisan config:cache --no-interaction
+(
+ umask 077
+ php artisan config:cache --no-interaction
+ php artisan route:cache --no-interaction
+ php artisan event:cache --no-interaction
+ php artisan view:cache --no-interaction
+)
case "${APP_ROLE:-api}" in
api) exec supervisord -c /etc/opnform/supervisor-api.conf ;;
jobs) exec supervisord -c /etc/opnform/supervisor-jobs.conf ;;
diff --git a/docs/reports/production-performance-2026-10.md b/docs/reports/production-performance-2026-10.md
new file mode 100644
index 000000000..7a033e191
--- /dev/null
+++ b/docs/reports/production-performance-2026-10.md
@@ -0,0 +1,96 @@
+# Production performance qualification
+
+This change prepares an application and image update. It does not deploy it.
+
+## Runtime configuration
+
+The hosted release controller sets the frontend allocation to 2 GiB and the V8 old-space limit to 1536 MiB, preserving other Node options. The remaining allocation covers young-generation heap, native allocations and buffers. Deployment is still an explicit release operation; the plan-only command does not update Compose or restart containers.
+
+Every SSR request owns its QueryClient. Server queries use an infinite garbage-collection interval so that timer closures do not retain completed requests. Rendering dehydrates the response state and clears the request's query cache; error handling clears it too. Browser caches retain their existing ten-minute lifetime. No shared HTML cache is introduced.
+
+Public API reads authenticated by `FRONT_API_SECRET` have a separate bounded quota (`SSR_READS_PER_MINUTE`, default 6000 per renderer IP). Only GET requests to public form details, feature flags and plans qualify. This does not grant permissions or change validation, password protection, private resources, submissions, uploads or ordinary browser quotas. The production `api` middleware group uses `throttle:internal-api`, preserving its shared ordinary 100/minute quota; the separate external API limiter remains 60/minute. Export, signed-download and other dedicated-limiter exemptions are preserved. No forwarded client-IP header is trusted for this exception.
+
+Hosted backend roles compile configuration, routes, events and Blade views after their runtime environment is injected. A failed cache command stops startup. Runtime secrets are stored privately, and no shared Redis flush is performed.
+
+## Browser behavior
+
+Marketing pages defer private user/workspace reads until hydration finishes. Protected app routes retain their authentication bootstrap. Public respondent pages continue to skip it.
+
+The live demo activates when at least 35% of its reserved frame is visible and keeps its minimum height reserved. Only the selected classic or focused renderer is imported. Login and registration dialogs load when opened. Featurebase loads its SDK on the first feedback or changelog interaction, including an intent queued before the vendor component mounts; Clarity is imported only when its existing session and iframe conditions allow it. Images below the fold load lazily, the large footer texture is resized and compressed, and Euclid uses WOFF2 with all original characters retained.
+
+Product illustrations (`feature-1`, `feature-2`, `feature-3` and `product-cover-half`) now use lossless WebP at their original dimensions, with exact preservation of every decoded RGBA pixel and any embedded ICC profile. Their combined full-size weight is 204,346 bytes instead of 385,738 bytes for the source PNGs (47.0% smaller). The 480/640-pixel responsive variants of `feature-3` are also encoded losslessly after Lanczos resizing; resizing remains an intentional spatial reduction, while the original-size variant remains available for higher-density displays. The decorative footer texture retains its earlier lossy encoding and 1000 × 1000 dimensions.
+
+Hashed Nuxt assets have a one-year immutable cache. Mutable images and fonts use one hour; `/_nuxt/builds/latest.json` is not retained. Error documents and authentication pages are not given public caching. Old hashed assets must remain available during release transitions.
+
+## Reproducing measurements
+
+Use Node 24.22.1 and the same lockfile for both revisions. Save the baseline `.output` before rebuilding the candidate. From the repository root run:
+
+```sh
+PERF_HTTP2=1 PERF_LIGHTHOUSE=1 node client/scripts/measure-landing-performance.mjs before /absolute/path/to/baseline-output
+PERF_HTTP2=1 PERF_LIGHTHOUSE=1 node client/scripts/measure-landing-performance.mjs after client/.output
+```
+
+With `PERF_HTTP2=1`, both revisions use the same temporary loopback HTTP/2 TLS proxy with gzip compression, including HTML. Its self-signed certificate stays in the ignored artifact directory. `PERF_LIGHTHOUSE=1` additionally runs Lighthouse 13.5.0 with mobile simulation. Omit these flags to measure direct Nitro without the proxy or Lighthouse.
+
+The script starts a temporary loopback API with fictional data and a production Nitro server, uses clean Chrome contexts with disabled HTTP cache, a 412 × 823 viewport and CPU slowdown ×4, and compares anonymous and cookie-bearing visits. External requests are blocked; vendor network costs and real customer/API latency are outside this comparison. `PERF_CHROME_BIN` selects Chrome; otherwise it uses local Google Chrome on macOS or Playwright Chromium.
+
+Results and screenshots stay in the ignored `.e2e/performance` directory. Memory samples use a loopback-only Node inspector and explicit garbage collection before and after the workload. RSS includes process allocator high-water marks and is not a leak measurement on its own. These local results are not production Lighthouse scores.
+
+## Investigation and transferred patterns
+
+The read-only production investigation found a frontend close to its 1 GiB container limit, seven restarts and a V8 heap-out-of-memory failure. Its 1024 MiB old-space setting left no allowance for the rest of the process. Completed SSR query caches were retained for ten minutes, and public SSR reads shared the ordinary anonymous API quota, producing HTTP 429 responses. These findings explain concrete failure modes; they do not establish that every slow request has the same cause.
+
+[Raydocs #308](https://github.com/JhumanJ/raydocs/pull/308) supplied applicable patterns: mount optional tools on visibility or intent, defer private identity reads on public routes, and ignore stale authentication failures after a new login. Those patterns are adapted to OpnForm's existing query and authentication contracts.
+
+## Before and after
+
+Baseline: `3a0178856c3bb12d214de86a452b84f979ca7a98`. Measured application source: `cef9a64cd9aa3e3950f7d4849390695145084820` (later report-only commits do not change the build). Both builds use the same installed dependencies, production Nitro, HTTP/2 and compression. Browser runs and Lighthouse runs are sequential, without concurrent builds or test suites. Values below are the final local runs, with decimal MB. Lighthouse is a single simulated mobile run per revision; its timings and score vary between runs.
+
+| Metric | Before | After |
+| --- | ---: | ---: |
+| Anonymous initial JS responses | 209 | 56 |
+| Anonymous JS responses after viewing demo | 209 | 64 |
+| Anonymous initial first-party resource transfer | 8.27 MB | 0.51 MB |
+| Synthetic signed-in initial JS responses | 215 | 68 |
+| Synthetic signed-in JS responses after viewing demo | 215 | 83 |
+| Synthetic signed-in initial first-party resource transfer | 7.92 MB | 0.54 MB |
+| Lighthouse performance score | 66 | 88 |
+| Lighthouse LCP | 6.27 s | 3.25 s |
+| Lighthouse TBT | 353.00 ms | 72.50 ms |
+| Lighthouse CLS | 0.040 | 0.040 |
+| V8 live heap before workload | 72.9 MB | 63.7 MB |
+| V8 live heap after 1,000 SSR form renders | 707.3 MB | 69.9 MB |
+
+Initial transfer includes scripts, styles, fonts and images loaded before scrolling, excluding the HTML document and blocked external vendors. It does not count every image eventually loaded down the page. Both browser scenarios rendered successfully without JavaScript exceptions; the demo and its cover were checked after scrolling. The synthetic signed-in scenario exercises deferred loading with fictional API data; real authentication is covered separately by browser tests against the isolated Laravel stack.
+
+The static landing import graph is 357.1 KiB gzip across 47 files. It differs from the browser's 56 script responses because runtime imports also load. CI now rejects a landing graph above 375 KiB gzip or 50 static files. Existing public-form budgets remain unchanged: classic 418.4 KiB and focused 409.0 KiB, below 425 KiB each.
+
+## Validation and review
+
+- Frontend: 111 files / 1,214 tests passed; full ESLint and production build passed. Built-server checks verify Brotli, immutable hashed assets, mutable-asset revalidation, uncached errors and private login responses.
+- Backend: 2,567 tests / 20,343 assertions passed, with two skips and two existing deprecation notices. Full Pint passed. The changed provider passes scoped PHPStan.
+- Full PHPStan reports three existing relation diagnostics in `WorkspaceController`, `FormListStatsLoader` and `McpFormManagementService`. The unmodified baseline was analyzed separately and reports the same three diagnostics; this PR introduces none.
+- Deployment: 15 controller contract tests and 21 disposable runtime scenarios passed against the actual PHP 8.3 application image. These cover runtime cache generation and permissions, PostgreSQL, Redis, real synthetic HTTP login/submission/upload, workers, expiry and shutdown. Disposable containers and networks were removed.
+- Production-build browser tests against the isolated seeded stack passed login, logout/protected redirects, classic/focused creation, public field rendering and a mixed-field submission. All 25 SSR initialization/draft/conditional-visibility browser tests also passed (31 browser cases total), including classic/focused hydration, numeric controls, computed values, restored drafts, delayed synchronization, URL prefills and auto-submission.
+- Review covered query dehydration and cleanup, private-route bootstrap, stale authentication responses, first-use/remount/error handling for feedback, lazy dialogs and demo, image dimensions/font character coverage, cache headers and runtime allocation. Concrete findings were corrected and the diff was reviewed again.
+
+No production deployment, DNS change, production data mutation or merge was performed. Runtime headroom and higher SSR quota take effect only through a future authorized release. Real production traffic, external vendors and API latency still require verification after that release; the local score must not be represented as a production score.
+
+## Independent review loop
+
+The JhumanJ Code Review skill was run in a read-only subagent. Round one found three issues: the renderer quota was registered on the external rather than internal middleware path, a new login could still be expired during an authentication-module import, and a first changelog click did not load the vendor SDK. All three were corrected with regression tests. Round two found no remaining concrete findings.
+
+The quota regressions instantiate the production HTTP Kernel and call the real public routes, checking bounded renderer reads, forged credentials, the shared ordinary 100/minute bucket and the independent external 60/minute limiter. Existing signed-download and export regressions also exercise the new middleware name. Authentication tests suspend the module import while the session changes. Mounted navigation/vendor tests exercise changelog-first intent, delayed vendor mount/user data and download retries.
+
+These review fixes follow the benchmark source snapshot identified above. Full frontend/backend suites, lint and bundle guards were rerun for the updated application; the earlier measured timings remain a snapshot of their explicitly identified revision.
+
+## Lossless product-image refinement
+
+This refinement changes only the six product-image WebP files and this report. Decoded full-size RGBA buffers were compared byte-for-byte to the original PNGs. Responsive variants were compared byte-for-byte to their resized source references; dimensions, alpha and any embedded color profile were preserved. The footer file was verified unchanged by SHA-256.
+
+Chromium decoded all six rebuilt assets successfully. Canvas comparison found identical opaque content and at most one 8-bit level of difference at semi-transparent edges when composited on white; this is separate from the exact RGBA equality of the encoded source images. Lint, production build, unchanged JavaScript budgets and the independent image review passed.
+
+The earlier benchmark table identifies its own application revision and predates this quality refinement. Its Lighthouse timings remain tied to that earlier revision; the fresh network check below validates the lossless assets separately. The four full-size files add 115,928 bytes compared with the earlier lossy WebPs; actual transfer depends on the responsive variant selected and which lazy images are loaded.
+
+A fresh HTTP/2 mobile network check with the rebuilt lossless assets measured **511,423 bytes / 56 initial script responses** anonymously and **537,182 bytes / 68 initial script responses** with the synthetic session. After viewing the demo, script counts were 64 and 75, respectively. Both browser scenarios completed without JavaScript exceptions. Initial transfer still rounds to 0.51 MB and 0.54 MB; larger image payloads are deferred. No new Lighthouse score is claimed for this asset-only refinement. Reproduce with `PERF_HTTP2=1 node client/scripts/measure-landing-performance.mjs after-lossless client/.output`.
diff --git a/tests/Deployment/coolify-model-fixture.php b/tests/Deployment/coolify-model-fixture.php
index 5a31a9eef..2f4a5f11c 100644
--- a/tests/Deployment/coolify-model-fixture.php
+++ b/tests/Deployment/coolify-model-fixture.php
@@ -4,6 +4,7 @@
namespace App\Models {
class Service
{
+ public static $frontend = null;
public $server_id = 5;
public $uuid = 'ssssssssssssssssssssssss';
public $server;
@@ -17,6 +18,11 @@ namespace App\Models {
$this->docker_compose_raw = json_encode(['services' => array_fill_keys(
['api', 'frontend', 'jobs', 'scheduler', 'migrate'], ['image' => 'previous-image']
)]);
+ if (self::$frontend !== null) {
+ $raw = json_decode($this->docker_compose_raw, true);
+ $raw['services']['frontend'] = self::$frontend;
+ $this->docker_compose_raw = json_encode($raw);
+ }
}
public static function where(...$arguments) { return new self; }
diff --git a/tests/Deployment/test-runtime.py b/tests/Deployment/test-runtime.py
index 118e0105f..9fb296275 100644
--- a/tests/Deployment/test-runtime.py
+++ b/tests/Deployment/test-runtime.py
@@ -192,6 +192,13 @@ add rule inet {firewall_table} forward_guard iifname "{bridge}" oifname != "{bri
settings = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();echo json_encode([config('database.redis.default.host'),config('database.redis.cache.host'),config('queue.connections.redis.retry_after'),$a->environment(),$a->configurationIsCached()]);"
assert json.loads(docker('exec', api, 'php', '-r', settings).stdout) == [queue, cache, 3700, 'production', True]
record('queue/cache/auth/state share one endpoint with separate logical DBs and 3700s reservation')
+ for role in (api, migration):
+ cached = json.loads(docker('exec', role, 'php', '-r',
+ "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();echo json_encode([$a->configurationIsCached(),$a->routesAreCached(),$a->eventsAreCached()]);").stdout)
+ assert cached == [True, True, True], cached
+ assert docker('exec', api, 'stat', '-c', '%a', '/app/bootstrap/cache/config.php').stdout.strip() == '600'
+ record('runtime configuration routes events and views are compiled; cached secrets remain private')
+
smoke = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$f=App\\Models\\Forms\\Form::where('title','Product feedback')->firstOrFail();if(App\\Models\\Forms\\FormSubmission::count()!==6)exit(1);$t=auth('api')->attempt(['email'=>'[email protected]','password'=>'Abcd@1234']);if(!$t)exit(2);echo $f->slug;"
slug = docker('exec', api, 'php', '-r', smoke).stdout.strip()
assert slug
diff --git a/tests/Deployment/test_service_release.py b/tests/Deployment/test_service_release.py
index 363f77ef7..240bbfebd 100644
--- a/tests/Deployment/test_service_release.py
+++ b/tests/Deployment/test_service_release.py
@@ -1,3 +1,4 @@
+import base64
import copy
import importlib.util
import json
@@ -97,7 +98,7 @@ class ServiceReleaseTests(unittest.TestCase):
self.assertEqual(execute.call_args.args[0], ['docker', 'exec', '-i', 'coolify', 'php'])
ssh.assert_not_called()
- def run_controller_fixture(self, directory, candidate, **options):
+ def run_controller_fixture(self, directory, candidate, frontend=None, **options):
target = {'controller_local': True, 'service_uuid': 's' * 24,
'server_id': 5, 'project_id': 4, 'team_id': 0, 'native_address': '100.65.151.96'}
with patch.object(self.release, 'execute', return_value='{}') as execute:
@@ -107,9 +108,30 @@ class ServiceReleaseTests(unittest.TestCase):
program = '$x=json_decode' + execute.call_args.kwargs['input'].split('$x=json_decode', 1)[1]
program = program.replace('/var/www/html/storage/app/opnform-release-history', directory)
fixture = Path(__file__).with_name('coolify-model-fixture.php').read_text()
+ saved = str(Path(directory) / 'saved-compose.json')
+ fixture = fixture.replace('public function save() {}', 'public function save() { file_put_contents(' + json.dumps(saved) + ', $this->docker_compose_raw); }')
+ if frontend is not None:
+ encoded = base64.b64encode(json.dumps(frontend).encode()).decode()
+ program = "App\\Models\\Service::$frontend=json_decode(base64_decode('" + encoded + "'),true);\n" + program
return subprocess.run(['php'], input=fixture + '\nnamespace {\n' + program + '\n}\n',
capture_output=True, text=True, timeout=10)
+ def test_frontend_heap_has_headroom_and_preserves_other_runtime_flags(self):
+ for environment in ({'KEEP': 'yes', 'NODE_OPTIONS': '--enable-source-maps --max-old-space-size=1024'},
+ ['KEEP=yes', 'NODE_OPTIONS=--enable-source-maps --max-old-space-size=1024']):
+ with self.subTest(environment=environment), tempfile.TemporaryDirectory() as directory:
+ frontend = {'image': 'old', 'mem_limit': '1g', 'environment': environment,
+ 'deploy': {'resources': {'limits': {'memory': '1g'}}}}
+ applied = self.run_controller_fixture(directory, self.candidate, frontend=frontend, apply=True)
+ self.assertEqual(applied.returncode, 0, applied.stderr)
+ saved = json.loads((Path(directory) / 'saved-compose.json').read_text())['services']['frontend']
+ self.assertEqual(saved['mem_limit'], '2g')
+ self.assertEqual(saved['deploy']['resources']['limits']['memory'], '2g')
+ env = saved['environment']
+ if isinstance(env, list): env = dict(v.split('=', 1) for v in env)
+ self.assertEqual(env['KEEP'], 'yes')
+ self.assertEqual(env['NODE_OPTIONS'], '--enable-source-maps --max-old-space-size=1536')
+
@unittest.skipUnless(shutil.which('php'), 'PHP is required for the generated controller fixture')
def test_successful_same_sha_reruns_have_independent_history_and_release_their_lease(self):
with tempfile.TemporaryDirectory() as directory: