Files
supabase/apps/studio/scripts/__tests__/vercel-spa-routes.test.ts
c5cdb59c47 feat(studio): prerender signed-out auth pages in the TanStack build (#52690)
## Problem

The TanStack Start build serves every document from the prerendered SPA
shell (`_shell.html`). For signed-out pages such as `/sign-in` and
`/sign-up`, the first HTML response holds only the loading fallback and
the generic `<title>Supabase</title>`. The page content and route
`head()` tags only appear after the JS bundle hydrates.

## Solution

On platform builds, prerender `/sign-in`, `/sign-up`, `/sign-in-sso` and
`/forgot-password` to static HTML next to the shell.

- `lib/prerendered-routes.ts`: the list of prerendered paths, shared by
the build config, the Vercel routes and the root route.
- `vite.config.ts`: passes the paths to `tanstackStart({ pages })` with
link crawling off, so only these pages are prerendered. Self-hosted
builds prerender nothing (self-hosted sign-in redirects straight to the
default project).
- `scripts/vercel-spa-routes.ts`: serves `<path>/index.html` for each
prerendered path (with and without the base path, optional trailing
slash, case-sensitive), ahead of the shell catch-all.
- `routes/__root.tsx`: renders `<Outlet />` once hydrated, or before
hydration when the path is prerendered; otherwise `<ShellFallback />`.
The Outlet stays at the same position in the tree, so navigating away
from a prerendered page doesn't remount it.

One prerendered file serves every visitor and every query string, so the
first render of these pages can't depend on per-visitor state:

- Search-param reads that affect render return empty until
`useHydrated()`, then update. `useInboundBranding` checks this directly,
and the "Sign up", "Sign in" and "Continue with SSO" link hrefs read
from `useHydratedQuery`.
- The "Sign in" links on `/sign-up` and `/forgot-password` now carry the
query params. The `/sign-up` link drops `returnTo=/new`, the default the
"Sign up" link sets, so existing users don't land in the new-org flow.
- Form controls sit in a `DisabledUntilHydrated` fieldset, so input
typed before hydration isn't lost and Enter can't natively POST the
form.
- The sign-in/forgot-password logo switches light/dark via CSS (`dark:`
classes) instead of `resolvedTheme` after mount, so dark-theme users
don't see the light logo first.
- `SignInLayout`'s session redirect effect skips the redirect after
unmount.

Also adds page titles for `/sign-in-sso` and `/forgot-password`.

## Review instructions

1. View source (not the inspector) of `/dashboard/sign-in`,
`/dashboard/sign-up`, `/dashboard/sign-in-sso` and
`/dashboard/forgot-password` on the preview: the HTML holds the form and
the page title, not the loading fallback. `/dashboard/organizations`
still returns the shell.
2. Load `/dashboard/sign-in?returnTo=%2Fproject%2F<ref>`: no hydration
errors in the console, and the "Sign up" link (hover / open in new tab)
carries the same `returnTo`. The "Sign in" links on `/dashboard/sign-up`
and `/dashboard/forgot-password` carry the query params too.
3. Sign in from that URL: you land on the project, with no second
redirect to `/organizations`.
4. Load `/dashboard/sign-in?destination=cli`: the CLI-branded heading
renders without a hydration error.
5. Links between the four pages navigate client-side, and dark mode
shows the dark logo straight away.

## Checks

- Platform `vite build` (`NEXT_PUBLIC_IS_PLATFORM=true
NEXT_PUBLIC_BASE_PATH=/dashboard`): prerenders the four pages plus the
shell; each file has its title, inputs and a disabled fieldset.
Self-hosted build prerenders only the shell.
- Served the build locally with Vercel-equivalent routing and checked in
a browser: no hydration errors for plain, `?returnTo=…`,
`?destination=cli` (with and without `method`),
`/sign-up?destination=cli` and `/Sign-In`; hrefs carry `returnTo` after
hydration; navigating from `/sign-in` to other routes doesn't remount
the sign-in form or flash the shell loader; with JS blocked, inputs and
submit are disabled.
- Unit tests for `isPrerenderedRoute` and the prerendered Vercel routes;
`tsc --noEmit`, ESLint on changed files, Prettier, knip and the lint
ratchet pass.
- Not covered locally: the signed-in `returnTo` redirect end to end
(review step 3).

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
Co-authored-by: Kody Jackson <kody.jackson@supabase.io>
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-05 10:31:28 -06:00

159 lines
6.1 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { buildSpaRoutes, buildStaticFileSrc, type StaticEntry } from '../vercel-spa-routes'
const IMMUTABLE = '/_vercel/immutable/initial/nitro'
const cacheRule = {
headers: { 'cache-control': 'public, max-age=31536000, immutable' },
src: `${IMMUTABLE}/(.*)`,
}
const skewCookieRule = {
src: '/.*',
has: [{ type: 'header', key: 'Sec-Fetch-Dest', value: 'document' }],
headers: { 'Set-Cookie': '__vdpl=dpl_123; Path=/; SameSite=Lax; Secure; HttpOnly' },
continue: true,
}
const filesystem = { handle: 'filesystem' }
const functionCatchAll = { src: '/(.*)', dest: '/__server' }
const staticEntries: StaticEntry[] = [
{ name: '_vercel', isDirectory: true },
{ name: 'img', isDirectory: true },
{ name: 'monaco-editor', isDirectory: true },
{ name: 'supabase-logo.svg', isDirectory: false },
]
const STATIC_FILE_SRC = '^/dashboard/((?:_vercel|img|monaco-editor)/.+|(?:supabase-logo\\.svg))$'
describe('buildSpaRoutes', () => {
it('keeps the rules ahead of the filesystem handler and replaces the function catch-all', () => {
const routes = buildSpaRoutes(
[cacheRule, skewCookieRule, filesystem, functionCatchAll],
'/__server',
IMMUTABLE
)
expect(routes).toEqual([
cacheRule,
skewCookieRule,
filesystem,
{ src: '/_serverFn/(.*)', dest: '/__server' },
{ src: '/api/(.*)', dest: '/__server' },
{ src: `${IMMUTABLE}/(.*)`, status: 404 },
{ src: '/(.*)', dest: '/_shell.html' },
])
})
it('adds prefixed rules and a public-file rewrite under a base path', () => {
const routes = buildSpaRoutes(
[cacheRule, filesystem, functionCatchAll],
'/__server',
IMMUTABLE,
'/dashboard',
staticEntries
)
expect(routes.slice(2)).toEqual([
{ src: '/dashboard/_serverFn/(.*)', dest: '/__server' },
{ src: '/dashboard/api/(.*)', dest: '/__server' },
{ src: '/_serverFn/(.*)', dest: '/__server' },
{ src: '/api/(.*)', dest: '/__server' },
{ src: `${IMMUTABLE}/(.*)`, status: 404 },
{ src: STATIC_FILE_SRC, dest: '/$1' },
{ src: '/(.*)', dest: '/_shell.html' },
])
})
it('serves prerendered pages from their own HTML ahead of the shell', () => {
const routes = buildSpaRoutes(
[filesystem, functionCatchAll],
'/__server',
IMMUTABLE,
'/dashboard',
[],
['/sign-in']
)
expect(routes.slice(-3)).toEqual([
{ src: '/dashboard/sign-in/?', dest: '/sign-in/index.html', caseSensitive: true },
{ src: '/sign-in/?', dest: '/sign-in/index.html', caseSensitive: true },
{ src: '/(.*)', dest: '/_shell.html' },
])
const signIn = new RegExp(`^${routes.at(-3)!.src}$`)
expect(signIn.test('/dashboard/sign-in')).toBe(true)
expect(signIn.test('/dashboard/sign-in/')).toBe(true)
expect(signIn.test('/dashboard/sign-in-mfa')).toBe(false)
})
it('fails loudly when Nitro output changes shape', () => {
expect(() => buildSpaRoutes([functionCatchAll], '/__server', '/assets')).toThrow(
/no \{ handle: "filesystem" \}/
)
expect(() => buildSpaRoutes([filesystem], '/__server', '/assets')).toThrow(
/catch-all .* was not found/
)
})
it('omits the public-file rewrite without a base path or static entries', () => {
expect(
buildSpaRoutes([filesystem, functionCatchAll], '/__server', IMMUTABLE, '', staticEntries)
).not.toContainEqual(expect.objectContaining({ dest: '/$1' }))
expect(
buildSpaRoutes([filesystem, functionCatchAll], '/__server', IMMUTABLE, '/dashboard')
).not.toContainEqual(expect.objectContaining({ dest: '/$1' }))
expect(buildStaticFileSrc('/dashboard', [])).toBeUndefined()
})
// Files present in the static output, resolved after a rewrite.
const existingFiles = new Set([
`${IMMUTABLE}/chunk.js`,
`${IMMUTABLE}/editor.worker.js`,
`${IMMUTABLE}/styles.css`,
'/img/logo.svg',
'/supabase-logo.svg',
])
// Models routing after `handle: filesystem` missed: the first matching rule
// wins, and a rewrite ends routing, so its destination must exist.
function resolveAfterFilesystemMiss(pathname: string) {
const routes = buildSpaRoutes(
[filesystem, functionCatchAll],
'/__server',
IMMUTABLE,
'/dashboard',
staticEntries
)
const after = routes.slice(routes.findIndex((r) => r.handle === 'filesystem') + 1)
const rule = after.find(({ src }) => src && new RegExp(`^${src}$`).test(pathname))
if (!rule) return undefined
if (rule.status) return rule.status
const destination = pathname.replace(new RegExp(`^${rule.src}$`), rule.dest!)
if (destination === '/__server' || destination === '/_shell.html') return destination
return existingFiles.has(destination) ? destination : 404
}
it.each([
[`/dashboard${IMMUTABLE}/chunk.js`, `${IMMUTABLE}/chunk.js`],
[`/dashboard${IMMUTABLE}/editor.worker.js`, `${IMMUTABLE}/editor.worker.js`],
[`/dashboard${IMMUTABLE}/styles.css`, `${IMMUTABLE}/styles.css`],
['/dashboard/img/logo.svg', '/img/logo.svg'],
['/dashboard/supabase-logo.svg', '/supabase-logo.svg'],
// Missing hashed chunks 404 rather than becoming the shell
[`/dashboard${IMMUTABLE}/old-chunk.js`, 404],
[`${IMMUTABLE}/old-chunk.js`, 404],
['/dashboard/api/export.json', '/__server'],
['/dashboard/_serverFn/function-id', '/__server'],
['/dashboard/project/example/editor', '/_shell.html'],
// Deep links whose last segment contains a dot are pages, not files
['/dashboard/project/example/storage/files/buckets/my.bucket', '/_shell.html'],
['/dashboard/project/example/functions/hello.world', '/_shell.html'],
['/dashboard/img', '/_shell.html'],
['/dashboard/img/', '/_shell.html'],
['/dashboard/img.png', '/_shell.html'],
// Unprefixed paths are unchanged
['/api/export.json', '/__server'],
['/_serverFn/function-id', '/__server'],
['/project/example/storage/files/buckets/my.bucket', '/_shell.html'],
])('routes %s to %s after the filesystem misses', (pathname, destination) => {
expect(resolveAfterFilesystemMiss(pathname)).toBe(destination)
})
})