Studio Routes studio-routes
TanStack Start routing and server API handler conventions for Supabase Studio.
Use it when adding or modifying file routes under apps/studio/routes/**, layout shells, permanent redirects in redirects.shared.ts, URL params or search state, or server API endpoints under apps/studio/routes/api/**.
- Our test
- 9/10✓ Verified
- tested Dec 6, 2026
- GitHub stars
- 116k
- supabase/supabase
- Added by
- 0
- members
- Updated
- Dec 6
- commit 9140cc7
- Content
- 1 file
- no scripts · 7 KB
- License
- Apache 2.0
- free to use
What our test found
Le skill fournit des conventions concrètes et un modèle utile, avec de bons garde-fous de validation, d’authentification et de gestion des erreurs.
name: studio-routes description: TanStack Start routing and server API handler conventions for Supabase Studio. Use when adding or modifying file routes under apps/studio/routes/**, layout shells, permanent redirects in redirects.shared.ts, URL params or search state, or server API endpoints under apps/studio/routes/api/**.
Studio Routes & Server API Handlers
Routes live under apps/studio/routes/** using TanStack Start file-based routing. apps/studio/routeTree.gen.ts is generated by the Vite plugin — never hand-edit it.
File Routes & Layouts (routes/**)
- Use native TanStack Router APIs (
createFileRoute,Link,useNavigate,Route.useParams()inside route files,useSearch) — never import fromnext/*. Inside shared components undercomponents/**, useuseParams()from'common'(do not mixuseParams()andRoute.useParams()in the same file). - Route files export only
Route. Shared components live incomponents/**; avoid trivial pass-through wrappers (function FooPage() { return <FooContent /> }). - Layouts are pathless (
routes/_app.tsx,routes/_auth.tsx) or sibling-file shells (routes/project/$ref/database.tsxwrapsroutes/project/$ref/database/**); layouts likeroutes/_app.tsxand section shells read route metadata viastaticData. - In layout shells, always pass
selecttouseMatches({ select })— callinguseMatches()withoutselectreturns a fresh array on every router tick and re-renders the entire shell subtree.
Navigation, Params & Redirects
- Use typed
<Link to="..." params={...} search={...}>for known internal routes, and render navigation triggers as<Button asChild><Link ...>rather than<button onClick={() => navigate(...)}>so⌘/middle-click works. (ForInlineLink,DynamicLink,SupportLink, and externalDOCS_URLlinks, seestudio-ui-patterns.) - Prefer TanStack Router location APIs over
window.location(Router stripsBASE_PATHautomatically). Avoid?error=and mixinguseParams(seeapps/studio/AGENTS.md). - Validate untrusted search/route params at entry with Zod, encode dynamic segments with
encodeURIComponentwhen interpolating into URLs (always validate path identifiers with an explicit allowlist regex too —encodeURIComponentleaves.and..intact, allowing dot-segment traversal), and avoid leaking unrelated contextual search params across routes. - Register permanent route moves directly to their final destination in
apps/studio/redirects.shared.ts(avoid multi-hop chains; consumed by bothapps/studio/vercel.tsandapps/studio/routes/__root.tsx) and delete replaced route files.
Server API Routes (routes/api/**)
Wrap every server route handler with createApiHandlers(handlers, { withAuth }) from @/lib/api/apiWrapper:
- Registers
ANY(and guardsHEADonGET-only routes) to return405+Allow, preventing unregistered methods from falling through to the SSR HTML shell. - Converts
InvalidJsonError(thrown byparseJsonBodyfrom@/lib/api/apiHelpers) into400. - Captures unexpected exceptions in Sentry and returns
500. - Verifies the platform JWT when
{ withAuth: true }and attachesclaimstoApiHandlerContext.
Canonical template
import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { parseJsonBody } from '@/lib/api/apiHelpers'
import { createApiHandlers, type ApiHandlerContext } from '@/lib/api/apiWrapper'
import { IS_PLATFORM } from '@/lib/constants'
import { getErrorMessage } from '@/lib/get-error-message'
const RequestSchema = z.object({
// Allowlist rejects dot-segment traversal
projectRef: z.string().regex(/^[a-z0-9-]+$/i),
})
async function handlePost({ request, claims }: ApiHandlerContext) {
if (!IS_PLATFORM) {
return Response.json({ error: { message: 'Platform only' } }, { status: 404 })
}
const upstreamUrl = process.env.UPSTREAM_API_URL
if (!upstreamUrl) {
return Response.json({ error: { message: 'Missing UPSTREAM_API_URL' } }, { status: 500 })
}
const parsed = RequestSchema.safeParse(await parseJsonBody(request))
if (!parsed.success) {
return Response.json({ error: { message: 'Invalid request body' } }, { status: 400 })
}
const response = await fetch(
`${upstreamUrl}/projects/${encodeURIComponent(parsed.data.projectRef)}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: claims?.sub }),
}
)
if (!response.ok) {
const body = await response.json().catch(() => null)
const fallback = response.statusText || 'Upstream request failed'
const message = getErrorMessage(body?.error) ?? getErrorMessage(body, fallback)
return Response.json({ error: { message } }, { status: response.status || 500 })
}
const text = await response.text()
if (!text) return new Response(null, { status: response.status })
return Response.json(JSON.parse(text), { status: response.status })
}
export const Route = createFileRoute('/api/example')({
server: {
handlers: createApiHandlers({ POST: handlePost }, { withAuth: true }),
},
})Server handler rules
- Auth by default: Pass
{ withAuth: true }on auth, sensitive, external-proxy, and non-trivial mutating routes. ReadclaimsfromApiHandlerContextinstead of re-callingauthenticateRequest/getUserClaims. - Standardized errors & upstream status: Return errors as
{ error: { message } }(extracting upstream error messages viagetErrorMessagefrom@/lib/get-error-message). Always checkresponse.ok, handle empty/bodyless success responses before parsing JSON, and propagate upstream HTTP status codes (falling back to500on errors). - Boundary validation & env guards: Parse JSON bodies with
parseJsonBody(request)+ Zod and query strings withgetSearchParamsRecord(url.searchParams)+ Zod, using allowlist patterns for URL path identifiers. Guard requiredprocess.env.*variables explicitly rather than using!. - `IS_PLATFORM` & lazy server clients:
withAuthis a no-op when!IS_PLATFORM. Gate platform-only vs self-hosted handlers explicitly. The TanStack Start server eagerly evaluates every route module at boot, so never construct a Supabase client at module scope — useselfHostedSupabaseAdminfrom@/lib/api/self-hosted-adminor construct lazily inside the handler. (ESLint only catches direct top-levelcreateClient(...)calls inroutes/**, notnew SupabaseClient(...), aliases, helper factories, or importedlib/**modules.)
Knip Entry Points
routes/**/*.{ts,tsx} is already registered under workspaces["apps/studio"].entry in knip.jsonc. If you add another framework-convention file that nothing imports directly, register it under entry — not ignore (an ignored file's imports are not traced, causing its dependencies to fail Knip as unused).