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/**.

Works in Claude, ChatGPT, Codex and more
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.

Request we tested it on“Add a POST /api/projects route that accepts a projectRef, verifies authentication, and forwards the request to an upstream API.”
View on GitHub ↗
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 from next/*. Inside shared components under components/**, use useParams() from 'common' (do not mix useParams() and Route.useParams() in the same file).
  • Route files export only Route. Shared components live in components/**; 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.tsx wraps routes/project/$ref/database/**); layouts like routes/_app.tsx and section shells read route metadata via staticData.
  • In layout shells, always pass select to useMatches({ select }) — calling useMatches() without select returns 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. (For InlineLink, DynamicLink, SupportLink, and external DOCS_URL links, see studio-ui-patterns.)
  • Prefer TanStack Router location APIs over window.location (Router strips BASE_PATH automatically). Avoid ?error= and mixing useParams (see apps/studio/AGENTS.md).
  • Validate untrusted search/route params at entry with Zod, encode dynamic segments with encodeURIComponent when interpolating into URLs (always validate path identifiers with an explicit allowlist regex too — encodeURIComponent leaves . 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 both apps/studio/vercel.ts and apps/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 guards HEAD on GET-only routes) to return 405 + Allow, preventing unregistered methods from falling through to the SSR HTML shell.
  • Converts InvalidJsonError (thrown by parseJsonBody from @/lib/api/apiHelpers) into 400.
  • Captures unexpected exceptions in Sentry and returns 500.
  • Verifies the platform JWT when { withAuth: true } and attaches claims to ApiHandlerContext.
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. Read claims from ApiHandlerContext instead of re-calling authenticateRequest / getUserClaims.
  • Standardized errors & upstream status: Return errors as { error: { message } } (extracting upstream error messages via getErrorMessage from @/lib/get-error-message). Always check response.ok, handle empty/bodyless success responses before parsing JSON, and propagate upstream HTTP status codes (falling back to 500 on errors).
  • Boundary validation & env guards: Parse JSON bodies with parseJsonBody(request) + Zod and query strings with getSearchParamsRecord(url.searchParams) + Zod, using allowlist patterns for URL path identifiers. Guard required process.env.* variables explicitly rather than using !.
  • `IS_PLATFORM` & lazy server clients: withAuth is 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 — use selfHostedSupabaseAdmin from @/lib/api/self-hosted-admin or construct lazily inside the handler. (ESLint only catches direct top-level createClient(...) calls in routes/**, not new SupabaseClient(...), aliases, helper factories, or imported lib/** 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).