Skip to content

Beautiful Open-Source Form Builder

Fix transient public form failures being shown as 404s (#1289)

Julien Nahumec96750973dc
diff --git a/client/composables/query/forms/useForms.js b/client/composables/query/forms/useForms.js
index 047ba8322..08067f706 100644
--- a/client/composables/query/forms/useForms.js
+++ b/client/composables/query/forms/useForms.js
@@ -5,6 +5,7 @@ import { useIsAuthenticated } from '~/composables/useAuthFlow'
import { useFormsListCache } from './useFormsList'
export function useForms() {
+ const nuxtApp = useNuxtApp()
const queryClient = useQueryClient()
const { isAuthenticated } = useIsAuthenticated()
const formsListCache = useFormsListCache()
@@ -17,17 +18,17 @@ export function useForms() {
})
const detail = (slug, options = {}) => {
- const { usePrivate = false, enabled = true, ...queryOptions } = options
+ const { usePrivate = false, enabled = true, requestOptions = {}, ...queryOptions } = options
const scope = scopeFor(usePrivate)
return useQuery({
queryKey: detailKey(scope, slug),
- queryFn: () => {
+ queryFn: () => nuxtApp.runWithContext(() => {
if (usePrivate) {
- return formsApi.get(slug, queryOptions)
+ return formsApi.get(slug, requestOptions)
}
- return formsApi.publicGet(slug, queryOptions)
- },
+ return formsApi.publicGet(slug, requestOptions)
+ }),
enabled: isQueryEnabled(slug, enabled, usePrivate),
onSuccess: (form) => {
if (form) {
diff --git a/client/lib/forms/public-form-loading.js b/client/lib/forms/public-form-loading.js
new file mode 100644
index 000000000..da85a3637
--- /dev/null
+++ b/client/lib/forms/public-form-loading.js
@@ -0,0 +1,30 @@
+const TRANSIENT_RESPONSE_STATUSES = new Set([408, 425, 429])
+
+function getErrorStatus (error) {
+ const rawStatus = error?.statusCode ?? error?.status ?? error?.response?.status
+ const status = Number(rawStatus)
+
+ return Number.isInteger(status) && status > 0 ? status : null
+}
+
+export function isPublicFormNotFoundError (error) {
+ return getErrorStatus(error) === 404
+}
+
+export function shouldRetryPublicFormRequest (failureCount, error) {
+ if (failureCount >= 2) {
+ return false
+ }
+
+ const status = getErrorStatus(error)
+
+ return status === null || TRANSIENT_RESPONSE_STATUSES.has(status) || status >= 500
+}
+
+export function publicFormRetryDelay (attemptIndex) {
+ return Math.min(250 * (2 ** attemptIndex), 1_000)
+}
+
+export function getPublicFormResponseStatus (error) {
+ return isPublicFormNotFoundError(error) ? 404 : 503
+}
diff --git a/client/pages/forms/[slug]/index.vue b/client/pages/forms/[slug]/index.vue
index d4e74fff9..fafa04c6c 100644
--- a/client/pages/forms/[slug]/index.vue
+++ b/client/pages/forms/[slug]/index.vue
@@ -5,7 +5,27 @@
class="flex flex-col min-h-screen"
>
<div class="w-full mx-auto flex flex-col grow h-full">
- <div v-if="!formLoading && !form">
+ <div
+ v-if="formUnavailable"
+ class="flex grow items-center justify-center p-6"
+ >
+ <div class="max-w-md text-center">
+ <h1 class="text-2xl font-semibold text-neutral-900">
+ This form is temporarily unavailable
+ </h1>
+ <p class="mt-3 text-neutral-500">
+ We couldn't load the form right now. Please check your connection and try again.
+ </p>
+ <button
+ type="button"
+ class="mt-6 rounded-lg bg-blue-500 px-4 py-2 font-medium text-white hover:bg-blue-600"
+ @click="retryForm"
+ >
+ Try again
+ </button>
+ </div>
+ </div>
+ <div v-else-if="formNotFound || (!formLoading && !form)">
<NotFoundForm />
</div>
<div v-else-if="formLoading">
@@ -48,6 +68,12 @@ import {
import { FormMode } from "~/lib/forms/FormModeStrategy.js"
import { formsApi } from '~/api'
import { customDomainUsed } from '~/lib/utils.js'
+import {
+ getPublicFormResponseStatus,
+ isPublicFormNotFoundError,
+ publicFormRetryDelay,
+ shouldRetryPublicFormRequest,
+} from '~/lib/forms/public-form-loading.js'
const crisp = useCrisp()
const appStore = useAppStore()
@@ -58,10 +84,39 @@ const { t } = useI18n()
const { performRedirect } = useSubdomainRedirect()
// Use TanStack Query to load the form
-const { data: form, isLoading: formLoading, error: formError, refetch: refetchForm, suspense } = useForms().detail(slug, {
- retry: false, // Don't auto-retry for 404s
+const {
+ data: form,
+ isLoading: formLoading,
+ error: formError,
+ refetch: refetchForm,
+ suspense,
+} = useForms().detail(slug, {
+ retry: shouldRetryPublicFormRequest,
+ retryDelay: publicFormRetryDelay,
refetchOnWindowFocus: false,
+ requestOptions: {
+ retry: false,
+ },
+})
+
+const retainedFormErrorStatus = useState(`public-form-error-status:${slug}`, () => null)
+const formErrorStatus = computed(() => {
+ return formError.value
+ ? getPublicFormResponseStatus(formError.value)
+ : retainedFormErrorStatus.value
})
+const formNotFound = computed(() => formErrorStatus.value === 404)
+const formUnavailable = computed(() => formErrorStatus.value === 503)
+const retryingForm = ref(false)
+
+const retryForm = () => {
+ if (retryingForm.value) return
+
+ retryingForm.value = true
+ refetchForm().finally(() => {
+ retryingForm.value = false
+ })
+}
if (import.meta.server) {
await suspense()
@@ -104,19 +159,28 @@ const passwordEntered = function (password) {
})
}
-// Handle 404 errors during SSR
+// Preserve real 404s while exposing transient upstream failures as retryable 503s.
if (import.meta.server && formError.value) {
const event = useRequestEvent()
+ const responseStatus = getPublicFormResponseStatus(formError.value)
+ retainedFormErrorStatus.value = responseStatus
console.error(`Error loading form [${slug}]:`, formError.value)
-
- // Check if we should redirect on 404 (subdomain redirect feature)
- await performRedirect({ skipIfIframe: true })
- setResponseStatus(event, 404, 'Page Not Found')
+
+ if (responseStatus === 404) {
+ await performRedirect({ skipIfIframe: true })
+ }
+
+ setResponseStatus(
+ event,
+ responseStatus,
+ responseStatus === 404 ? 'Page Not Found' : 'Service Unavailable',
+ )
}
// Adapt page to form: colors, custom code etc when form is loaded
watch(form, (newForm) => {
if (newForm) {
+ retainedFormErrorStatus.value = null
handleDarkMode(newForm?.dark_mode)
handleTransparentMode(newForm?.transparent_background)
@@ -129,9 +193,15 @@ watch(form, (newForm) => {
}
}, { immediate: true })
+watch(formError, (error) => {
+ if (error) {
+ retainedFormErrorStatus.value = getPublicFormResponseStatus(error)
+ }
+})
+
// Handle client-side 404 redirects for forms (subdomain redirect feature)
watch([formLoading, formError], async ([loading, error]) => {
- if (import.meta.client && !loading && (error || !form.value)) {
+ if (import.meta.client && !loading && isPublicFormNotFoundError(error)) {
await performRedirect({ skipIfIframe: true })
}
})
diff --git a/client/test/e2e/opnform-flows.spec.ts b/client/test/e2e/opnform-flows.spec.ts
index 60c3db823..6cda780df 100644
--- a/client/test/e2e/opnform-flows.spec.ts
+++ b/client/test/e2e/opnform-flows.spec.ts
@@ -219,15 +219,21 @@ async function openRegister(page: Page) {
}
async function selectHearAboutUs(page: Page) {
- await page.getByRole("button", { name: "Select option", exact: true }).click()
- await page.getByText("Friend or Colleague", { exact: true }).click()
+ const select = page.getByRole("button", { name: "How did you hear about us?", exact: true })
+
+ await expect(async () => {
+ await select.click()
+ await expect(select).toHaveAttribute("aria-expanded", "true")
+ }).toPass({ timeout: 15_000 })
+
+ await page.getByRole("option", { name: "Friend or Colleague", exact: true }).click()
}
async function registerUi(page: Page, email: string) {
await openRegister(page)
+ await selectHearAboutUs(page)
await page.locator('input[name="name"]').fill("Playwright User")
await page.locator('input[name="email"]').fill(email)
- await selectHearAboutUs(page)
await page.locator('input[name="password"]').fill("Abcd@1234")
await page.locator('input[name="password_confirmation"]').fill("Abcd@1234")
await page.locator('input[name="agree_terms"]').check({ force: true })
diff --git a/client/test/unit/public-form-loading.test.ts b/client/test/unit/public-form-loading.test.ts
new file mode 100644
index 000000000..0295c2e2b
--- /dev/null
+++ b/client/test/unit/public-form-loading.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import {
+ getPublicFormResponseStatus,
+ isPublicFormNotFoundError,
+ publicFormRetryDelay,
+ shouldRetryPublicFormRequest,
+} from '../../lib/forms/public-form-loading.js'
+
+describe('public form loading policy', () => {
+ it.each([
+ { statusCode: 404 },
+ { status: 404 },
+ { response: { status: 404 } },
+ ])('recognizes a 404 across supported fetch error shapes', (error) => {
+ expect(isPublicFormNotFoundError(error)).toBe(true)
+ expect(getPublicFormResponseStatus(error)).toBe(404)
+ expect(shouldRetryPublicFormRequest(0, error)).toBe(false)
+ })
+
+ it.each([
+ [{ statusCode: 408 }, true],
+ [{ statusCode: 425 }, true],
+ [{ statusCode: 429 }, true],
+ [{ statusCode: 500 }, true],
+ [{ statusCode: 502 }, true],
+ [{ statusCode: 503 }, true],
+ [{ statusCode: 504 }, true],
+ [new TypeError('fetch failed'), true],
+ [{ statusCode: 400 }, false],
+ [{ statusCode: 401 }, false],
+ [{ statusCode: 403 }, false],
+ [{ statusCode: 422 }, false],
+ ])('retries only transient failures', (error, expected) => {
+ expect(shouldRetryPublicFormRequest(0, error)).toBe(expected)
+ })
+
+ it('stops after two retries', () => {
+ const error = { statusCode: 503 }
+
+ expect(shouldRetryPublicFormRequest(0, error)).toBe(true)
+ expect(shouldRetryPublicFormRequest(1, error)).toBe(true)
+ expect(shouldRetryPublicFormRequest(2, error)).toBe(false)
+ })
+
+ it('maps every non-404 failure to service unavailable', () => {
+ expect(getPublicFormResponseStatus({ statusCode: 500 })).toBe(503)
+ expect(getPublicFormResponseStatus(new TypeError('fetch failed'))).toBe(503)
+ })
+
+ it('uses short bounded exponential delays', () => {
+ expect(publicFormRetryDelay(0)).toBe(250)
+ expect(publicFormRetryDelay(1)).toBe(500)
+ expect(publicFormRetryDelay(10)).toBe(1_000)
+ })
+})
diff --git a/client/test/unit/useForms-detail-options.test.ts b/client/test/unit/useForms-detail-options.test.ts
new file mode 100644
index 000000000..87ceeeb8f
--- /dev/null
+++ b/client/test/unit/useForms-detail-options.test.ts
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ publicGet: vi.fn(),
+ get: vi.fn(),
+ runWithContext: vi.fn(callback => callback()),
+ useQuery: vi.fn(config => config),
+}))
+
+vi.stubGlobal('useNuxtApp', () => ({
+ runWithContext: mocks.runWithContext,
+}))
+
+vi.mock('@tanstack/vue-query', () => ({
+ useMutation: vi.fn(),
+ useQuery: mocks.useQuery,
+ useQueryClient: () => ({
+ getQueryData: vi.fn(),
+ setQueryData: vi.fn(),
+ }),
+}))
+
+vi.mock('~/api/forms', () => ({
+ formsApi: {
+ get: mocks.get,
+ publicGet: mocks.publicGet,
+ },
+}))
+
+vi.mock('~/composables/useAuthFlow', () => ({
+ useIsAuthenticated: () => ({ isAuthenticated: { value: true } }),
+}))
+
+vi.mock('~/composables/query/forms/useFormsListCache', () => ({
+ useFormsListCache: () => ({
+ add: vi.fn(),
+ remove: vi.fn(),
+ update: vi.fn(),
+ }),
+}))
+
+import { useForms } from '../../composables/query/forms/useForms.js'
+
+describe('useForms detail options', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('keeps query retry options out of the underlying HTTP request', async () => {
+ const retry = vi.fn()
+ const retryDelay = vi.fn()
+ const requestOptions = {
+ headers: { 'x-test': 'value' },
+ retry: false,
+ }
+
+ const query = useForms().detail('contact', {
+ refetchOnWindowFocus: false,
+ requestOptions,
+ retry,
+ retryDelay,
+ })
+
+ expect(query.retry).toBe(retry)
+ expect(query.retryDelay).toBe(retryDelay)
+ expect(query.refetchOnWindowFocus).toBe(false)
+
+ await query.queryFn()
+
+ expect(mocks.runWithContext).toHaveBeenCalledTimes(1)
+ expect(mocks.publicGet).toHaveBeenCalledWith('contact', requestOptions)
+ })
+
+ it('preserves private form requests with their explicit HTTP options', async () => {
+ const requestOptions = {
+ headers: { authorization: 'Bearer test-token' },
+ }
+
+ const query = useForms().detail('contact', {
+ usePrivate: true,
+ requestOptions,
+ })
+
+ await query.queryFn()
+
+ expect(mocks.runWithContext).toHaveBeenCalledTimes(1)
+ expect(mocks.get).toHaveBeenCalledWith('contact', requestOptions)
+ expect(mocks.publicGet).not.toHaveBeenCalled()
+ })
+})