Files
supabase/apps/studio/scripts/vercel-spa-routes.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

153 lines
6.4 KiB
TypeScript

import { readdir, readFile, writeFile } from 'node:fs/promises'
import { basename, resolve } from 'node:path'
import type { NitroModule } from 'nitro/types'
// Nitro module that makes the Vercel Build Output a static-first SPA: documents
// are served from the prerendered shell on the CDN and only server functions
// and API routes invoke the function. Nitro's own config sends every
// non-static path to the function.
//
// A module rather than config because `nitro({ hooks: { compiled } })`
// REPLACES the vercel preset's `compiled` hook (config.json is never written),
// and `vercel.config.routes` is defu-merged: user routes land above Nitro's
// `handle: filesystem` while its function catch-all is still appended last.
//
// Runs before TanStack Start writes `_shell.html`.
/** Must match `spa.prerender.outputPath` in tanstackStart() (default `/_shell`). */
export const SHELL_PATH = '/_shell.html'
/** Must match `serverFns.base` in tanstackStart() (default `/_serverFn`). */
export const SERVER_FN_BASE = '/_serverFn'
/** Directory under `routes/` that holds the server routes. */
export const API_PREFIX = '/api'
type Route = Record<string, unknown> & {
src?: string
dest?: string
handle?: string
}
/** A top-level entry of the static output directory. */
export type StaticEntry = { name: string; isDirectory: boolean }
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
/**
* Matches `${basePath}/<static file>` and captures the root-relative path.
* Limited to the actual top-level static entries so page deep links whose last
* segment contains a dot (e.g. a `my.bucket` storage bucket) still fall
* through to the shell. Directories only match with a trailing path, so a
* page that shares a directory's name is unaffected.
*/
export function buildStaticFileSrc(basePath: string, entries: StaticEntry[]): string | undefined {
const dirs = entries.filter((e) => e.isDirectory).map((e) => escapeRegExp(e.name))
const files = entries.filter((e) => !e.isDirectory).map((e) => escapeRegExp(e.name))
const alternatives = [
...(dirs.length ? [`(?:${dirs.join('|')})/.+`] : []),
...(files.length ? [`(?:${files.join('|')})`] : []),
]
if (!alternatives.length) return undefined
return `^${escapeRegExp(basePath)}/(${alternatives.join('|')})$`
}
/**
* After `handle: filesystem`: only `/_serverFn/*` and `/api/*` reach the
* function, a missing hashed chunk 404s instead of becoming the HTML shell,
* prerendered pages are served from their own HTML, and everything else is
* the shell.
*
* @param assetsPrefix `/assets`, or `/_vercel/immutable/<salt>/nitro` with
* `vercel.immutableStaticFiles`.
* @param basePath `NEXT_PUBLIC_BASE_PATH` (e.g. `/dashboard`). Pages, API
* routes, server functions and browser asset URLs live under it while the
* static files and immutable store stay at the root. Prefixed rules come
* first and requests for `staticEntries` under the prefix are rewritten to
* the root. A rewrite ends routing, so a prefixed request for a missing
* hashed chunk 404s at its root destination rather than reaching the shell.
* @param staticEntries Top-level entries of the static output directory.
* @param prerenderedRoutes Page paths (without `basePath`) that TanStack Start
* prerenders to `<path>/index.html` at the root of the static output.
*/
export function buildSpaRoutes(
generated: Route[],
functionDest: string,
assetsPrefix: string,
basePath = '',
staticEntries: StaticEntry[] = [],
prerenderedRoutes: string[] = []
): Route[] {
const fsIndex = generated.findIndex((r) => r.handle === 'filesystem')
if (fsIndex === -1) {
throw new Error('[vercel-spa-routes] generated config has no { handle: "filesystem" }')
}
const before = generated.slice(0, fsIndex)
const after = generated.slice(fsIndex + 1)
const isFunctionCatchAll = (r: Route) => r.src === '/(.*)' && r.dest === functionDest
if (!after.some(isFunctionCatchAll)) {
throw new Error(
`[vercel-spa-routes] expected Nitro catch-all { src: "/(.*)", dest: "${functionDest}" } was not found`
)
}
const kept = after.filter((r) => !isFunctionCatchAll(r) && r.handle !== 'filesystem')
const prefixes = basePath ? [basePath, ''] : ['']
const staticFileSrc = basePath ? buildStaticFileSrc(basePath, staticEntries) : undefined
return [
...before,
{ handle: 'filesystem' },
...kept,
...prefixes.flatMap((prefix) => [
{ src: `${prefix}${SERVER_FN_BASE}/(.*)`, dest: functionDest },
{ src: `${prefix}${API_PREFIX}/(.*)`, dest: functionDest },
]),
{ src: `${assetsPrefix}/(.*)`, status: 404 },
...(staticFileSrc ? [{ src: staticFileSrc, dest: '/$1' }] : []),
...prerenderedRoutes.flatMap((route) =>
prefixes.map((prefix) => ({
src: `${escapeRegExp(`${prefix}${route}`)}/?`,
dest: `${route}/index.html`,
// `isPrerenderedRoute()` is case-sensitive, so other casings must get the shell.
caseSensitive: true,
}))
),
{ src: '/(.*)', dest: SHELL_PATH },
]
}
export function vercelSpaRoutes({
basePath = '',
prerenderedRoutes = [],
}: { basePath?: string; prerenderedRoutes?: string[] } = {}): NitroModule {
return {
name: 'vercel-spa-routes',
setup(nitro) {
if (nitro.options.preset !== 'vercel') return
nitro.hooks.hook('compiled', async () => {
const configPath = resolve(nitro.options.output.dir, 'config.json')
const functionDest = `/${basename(nitro.options.output.serverDir).replace(/\.func$/, '')}`
const assetsPrefix =
'/' + (nitro.options.buildAssetsDir || 'assets').replace(/^\/|\/$/g, '')
// Includes the immutable asset store (`_vercel`); `_shell.html` is
// written later but is never requested under the prefix.
const staticEntries = (
await readdir(nitro.options.output.publicDir, { withFileTypes: true })
).map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }))
const config = JSON.parse(await readFile(configPath, 'utf8'))
config.routes = buildSpaRoutes(
config.routes,
functionDest,
assetsPrefix,
basePath,
staticEntries,
prerenderedRoutes
)
await writeFile(configPath, JSON.stringify(config, null, 2))
nitro.logger.success(
`[vercel-spa-routes] documents -> ${SHELL_PATH}, ${basePath}${SERVER_FN_BASE}/* and ${basePath}${API_PREFIX}/* -> ${functionDest}, missing ${assetsPrefix}/* -> 404`
)
})
},
}
}