## Problem
With all Studio API routes migrated to native TanStack Start handlers
(or removed when unused) in parts 1–6, the Next Pages Router API adapter
and legacy `NextApiRequest`/`NextApiResponse` wrappers are no longer
used. Part 7 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
tears them down.
## Solution
**Removed:**
- `compat/next/api.ts` and `compat/next/api.test.ts` (`toWebHandler`)
- Legacy `apiWrapper`, `apiAuthenticate`, and `fetchUserClaims`
(`NextApiRequest`/`NextApiResponse`) functions and their legacy tests in
`lib/api/apiWrapper.ts`, `lib/api/apiAuthenticate.ts`,
`lib/api/apiWrappers.test.ts`, and `lib/api/apiAuthenticate.test.ts`
- The now-unused `fromNodeHeaders` helper (and its `node:http` import)
and its tests in `lib/api/apiHelpers.ts` / `lib/api/apiHelpers.test.ts`
**Changed:**
- Updated comment in `lib/server/configcat.ts` from `apiAuthenticate` to
`authenticateRequest`
## Review instructions
1. Confirm `git grep -E
"NextApiRequest|NextApiResponse|compat/next/api|toWebHandler|fromNodeHeaders|from
'next'" apps/studio/` returns no matches.
2. Run `pnpm --filter studio run typecheck`, `pnpm knip --workspace
apps/studio`, and `pnpm --filter studio exec vitest run lib/api/
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.
## 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: Alaister Young <10985857+alaister@users.noreply.github.com>
## Problem
Studio's `routes/api/platform/projects/**` routes still run legacy Next
Pages Router handlers through `compat/next/api.ts`, and
`projects/$ref/config/index.ts` and `projects/$ref/billing/addons.ts`
are unused in self-hosted mode. Part 5 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
migrates the 19 active project routes to native TanStack Start handlers
and removes the 2 unused routes.
## Solution
**Changed:**
- Migrated 19 project routes — analytics (`endpoints/$name`,
`log-drains`, `log-drains/$uuid`), API proxies (`api/graphql`,
`api/rest`), content snippets & folders (`content/**`), and
config/settings/databases/lints/keys/monitoring routes — to
`createApiHandlers`
- Preserved FE-5124 fixes on `log-drains/$uuid` (empty-body `204` on
`DELETE`, `try`/`catch` + `!response.ok` → `500`); its `Allow: GET, PUT,
DELETE` and the previously stale `Allow` on `log-drains` (`GET, POST`)
now come from `createApiHandlers`
- Forwarded upstream error status and JSON body (falling back to `500` /
`{ error: { message } }`) in `api/graphql` and `api/rest`
- Parsed the JSON body once in `content/index.ts` `PUT` so the `not
found` create fallback does not attempt to re-read the request stream
- `content/index.ts` and `content/folders/index.ts` read query params
through `getSearchParamsRecord`, so repeated `ids` (and repeated GET
params on `content/index`) return `400` as they did with Next's query
parsing
- `run-lints` forwards headers via
`constructHeaders(Object.fromEntries(request.headers))`
**Added:**
- `getSearchParamsRecord` in `lib/api/apiHelpers.ts`: collects URL
search params into a record, mapping repeated keys to arrays so zod
string schemas reject them
- `folderQueryParamsSchema` and `listFolderContents(request, folderId?)`
in `lib/api/snippets.utils.ts`, shared by `content/folders/index` and
`content/folders/$id`
- `getLogflareConfig()` in `lib/api/self-hosted/logflare.ts`: reads the
Logflare env vars at call time (same `500` naming the missing vars) and
builds the request URLs and headers for `analytics/log-drains` and
`analytics/log-drains/$uuid`
- Unit tests for `getSearchParamsRecord`, `analytics/endpoints/$name`,
`analytics/log-drains/$uuid`, `content/index`, `content/folders`, and
`api/rest` (`HEAD` and upstream error forwarding)
**Removed:**
- Removed 2 unused routes
(`routes/api/platform/projects/$ref/config/index.ts` and
`routes/api/platform/projects/$ref/billing/addons.ts`) and regenerated
`routeTree.gen.ts`
**Behavior changes vs master:**
- `analytics/endpoints/$name` GET strips `name` and `ref` from the
forwarded query (parity with master, where they arrived as route params
in `req.query`)
- `content/folders` and `content/folders/$id` GET validate query params
and return `400` for invalid or repeated values
- `api/graphql` and `api/rest` forward upstream non-OK status codes and
error bodies instead of always returning `500`
- Unused `projects/$ref/config/index` and `projects/$ref/billing/addons`
routes have been removed
## Review instructions
1. Run `pnpm --filter studio exec vitest run lib/api/apiHelpers.test.ts
tests/routes/api/platform/projects/`.
2. On self-hosted Studio, create/update/delete a log drain,
create/save/delete a SQL snippet and folder, and verify REST/GraphQL API
docs load.
## 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: Alaister Young <10985857+alaister@users.noreply.github.com>
## Problem
Studio's `routes/api/platform/pg-meta/**` and `routes/api/v1/**` routes
still run legacy Next Pages Router handlers through
`compat/next/api.ts`, and 10 legacy `pg-meta` GET proxy routes are no
longer called anywhere in the repo. Part 3 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
migrates the 9 active routes to native TanStack Start handlers and
deletes the 10 unused proxy routes.
## Solution
**Changed:**
- Migrated `platform/pg-meta/$ref/query/index.ts` and all 8 `v1` routes
(`api-keys`, `api-keys/$id`, `config/auth/signing-keys/{index,legacy}`,
`database/migrations`, `functions/{index,$slug/index}`,
`types/typescript`) to `createApiHandlers`; `query` and
`database/migrations` share `pgMetaErrorResponse`
- Enabled `{ withAuth: true }` on `api-keys`, `api-keys/$id`, and
`config/auth/signing-keys/{index,legacy}` for consistency with the other
`v1` routes
- Updated `api-keys` route tests to use `callRoute`
**Added:**
- `pgMetaErrorResponse(error)` in `lib/api/self-hosted/pg-meta.ts`
(keeps a `PgMetaDatabaseError`'s status and `{ message, formattedError
}` payload expected by `data/error-classification.ts`, otherwise `500`)
- Unit test for `pg-meta/$ref/query`
(`tests/routes/api/platform/pg-meta/$ref/query/index.test.ts`)
**Removed:**
- Removed all 10 unused `pg-meta` GET proxy routes (`column-privileges`,
`extensions`, `foreign-tables`, `materialized-views`, `policies`,
`publications`, `tables`, `triggers`, `types`, `views`), removed their
`FETCH_TYPE_BYPASS_EXCEPTIONS` entries from `eslint.config.cjs`, and
regenerated `routeTree.gen.ts`
- Removed `getPgMetaRedirectUrl` (`lib/api/apiHelpers.ts`) and
`parseRevealQuery` (`lib/api/self-hosted/api-keys.ts`)
**Behavior changes vs master:**
- Routes forward only `cookie` and `x-connection-encrypted` to pg-meta
via `constructHeaders(Object.fromEntries(request.headers))`, matching
what master's adapter forwarded
- `database/migrations` GET now forwards headers to
`listMigrationVersions` (master passed them as the wrong argument)
- `v1/projects/$ref/api-keys*` and `config/auth/signing-keys*` now pass
`{ withAuth: true }` (no-op in self-hosted mode; consistent with the
other `v1` routes)
- The 10 unused `pg-meta` GET proxy routes have been removed
(`pg-meta/$ref/query` and `v1/projects/$ref/types/typescript` remain)
## Review instructions
1. Run `pnpm --filter studio exec vitest run tests/routes/api/v1/
tests/routes/api/platform/pg-meta/`.
2. On self-hosted Studio, load tables/views/policies/extensions, run a
query in the SQL Editor, check API keys, and generate TypeScript types.
## 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: Alaister Young <10985857+alaister@users.noreply.github.com>
## Problem
Studio's `routes/api/**` server routes still run legacy Next Pages
Router handlers through the `toWebHandler` shim in `compat/next/api.ts`.
Part 1 of 7 for
[FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the)
adds native TanStack Start (`Request` → `Response`) helpers and migrates
the top-level utility routes so we can remove the adapter at the end of
the stack.
## Solution
**Added:**
- `createApiHandlers` in `lib/api/apiWrapper.ts`: wraps native TanStack
Start route handlers with optional platform JWT auth, JSON `400` (`{
error: { message: 'Invalid JSON' } }`) on `InvalidJsonError`, Sentry
capture + generic `500` on unexpected throws, and an `ANY` handler that
returns `405` with an `Allow` header derived from the registered
methods. Exports `ApiHandler` / `ApiHandlerContext` (`params` is
`Record<string, string>`)
- `authenticateRequest` in `lib/api/apiAuthenticate.ts` (Web `Request`
counterpart of `apiAuthenticate`, same error messages)
- `InvalidJsonError` and `parseJsonBody` in `lib/api/apiHelpers.ts`
- `callRoute(route, request, params)` test helper in
`tests/lib/server-route.ts`
- Unit tests for `createApiHandlers` (exercising real
`authenticateRequest` through MSW in
`lib/api/createApiHandlers.test.ts`), `authenticateRequest`,
`parseJsonBody`, `/api/generate-attachment-url`, and
`/api/integrations/stripe-sync`
**Changed:**
- Updated `getRouteHandler` in `tests/lib/server-route.ts` to mirror
TanStack Start's `HEAD` → `GET` → `ANY` dispatch order
- Migrated 11 top-level API routes (`check-cname`,
`cli-release-version`, `content/graphql`, `edge-functions/test`,
`enabled-features-overrides`, `generate-attachment-url`,
`get-deployment-commit`, `get-ip-address`, `get-s3-keys`,
`get-utc-time`, `integrations/stripe-sync`) to native handlers
- Added `withAuth: true` to `check-cname`, `content/graphql`, and
`integrations/stripe-sync`, and updated `check-cname-mutation.ts` and
`data/graphql/execute.ts` to attach `constructHeaders()`
- Reused `withAuth` `claims` in `generate-attachment-url` to avoid a
duplicate GoTrue lookup in platform mode
- Converted `tests/routes/api/get-deployment-commit.test.ts` to
`callRoute`
**Removed:**
- Removed 2 unused routes (`routes/api/connect/index.ts` and
`routes/api/parse-query.ts`), dropped `/parse-query` from
`lib/hosted-api-allowlist.ts`, removed Nitro's `traceDeps:
['libpg-query*']` in `vite.config.ts` (no server runtime route imports
`libpg-query` anymore), and regenerated `routeTree.gen.ts`
**Behavior changes vs master:**
- Methods a route doesn't register now get a JSON `405` with an `Allow`
header (previously they fell through to the SSR app). `HEAD` requests
that TanStack Start dispatches to a `GET` handler also get `405`,
matching master's method switches
- `InvalidJsonError` returns JSON `{ error: { message: 'Invalid JSON' }
}` (`400`) instead of plain text
- `check-cname`, `content/graphql`, and `integrations/stripe-sync` now
verify the platform JWT via `withAuth: true`
- Unexpected throws return a generic `500` with `{ error: { message:
'Internal Server Error' } }`
- Unused `/api/connect` and `/api/parse-query` routes have been removed
## Review instructions
1. Run `pnpm --filter studio exec vitest run
lib/api/apiAuthenticate.test.ts lib/api/apiHelpers.test.ts
lib/api/apiWrappers.test.ts lib/api/createApiHandlers.test.ts
tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`.
2. Smoke-test `/api/get-deployment-commit`, `/api/check-cname`,
`/api/content/graphql`, `/api/generate-attachment-url`, and
`/api/edge-functions/test` in Studio and confirm unsupported HTTP
methods return `405` with an `Allow` header.
## 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: Alaister Young <10985857+alaister@users.noreply.github.com>
Moves every `pages/api/**` handler into its TanStack server route under
`routes/api/**` and deletes `pages/api/**`, part of the final pass of
the TanStack Start migration (FE-3106). Handlers move verbatim and still
run through `toWebHandler`, so auth (`apiWrapper`), response shapes and
headers are unchanged. Part 2 of the stack.
**Depends on:** #53199
**Changed:**
- `routes/api/**` – each route now holds its handler (formerly the
`pages/api` default export) as a local `nextHandler`/named function.
Next-only `config`/`maxDuration` exports are dropped: `vite.config.ts`
already sets the function `maxDuration`, and `toWebHandler` parses
bodies itself
- `routes/api/ai/docs.ts` – Web-native handler inlined, `NextRequest` →
`Request`
- `lib/api/apiHelpers.ts` – `getPgMetaRedirectUrl` moved here from the
old `tables` handler, which the other pg-meta routes imported it from
- `eslint.config.cjs`, `.github/CODEOWNERS` – `pages/api` paths →
`routes/api`
- `tests/routes/api/**`, `lib/api/{generate-v4,rate}.test.ts`,
`scripts/__tests__/server-source-maps.test.ts` – call the route's
registered handler with a Web `Request` (`tests/lib/server-route.ts`);
the MCP query-validation cases now run against the native route
**Removed:**
- `pages/api/**` (102 files), including the Next twins of the
already-native `routes/api/mcp/index.ts` and `functions/$slug/body.ts`
- unused `ProjectSettings` types and the `node-mocks-http` dev
dependency
Parity: every route registers the same methods its handler serves. The
exceptions are `check-cname`, `get-ip-address`, `get-utc-time`,
`get-s3-keys`, `get-deployment-commit`, `cli-release-version` and
`connect`: in Next they answered any method, and their routes register
`GET` only, as before this PR.
Addresses
[FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages).
## To test
- Load the table editor, SQL editor and Auth users on a self-hosted
build – `/api/platform/**` and `/api/v1/**` respond as before
- Use the Assistant and the docs search – `/api/ai/**` streams as before
- `GET /api/get-deployment-commit` – same JSON and `Cache-Control`
Ran typecheck, ESLint, lint ratchet, knip, Prettier, the TanStack build
and the full Studio vitest suite: all pass except
`lib/server/configcat.test.ts`, which also fails on `master` in an
environment with ConfigCat env vars set. Self-hosted E2E is CI-only.
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
`getBearerToken` in the Stripe Sync API handler parsed the
`Authorization` header with `/^Bearer\s+(.+)$/i`. Both `\s+` and `(.+)`
can match whitespace, so a header made of `Bearer` and a long run of
whitespace backtracks in quadratic time (CodeQL `js/polynomial-redos`).
The token is now parsed with `slice`, a case-insensitive scheme check
and `trim`.
**Changed:**
- `apps/studio/lib/api/apiHelpers.ts` – new shared
`getBearerToken(authorization)` that parses in linear time. It returns
`null` for a missing, array-valued, non-Bearer or empty/whitespace-only
header. Previously a whitespace-only token returned `''` instead of
`null`, which still got a 401.
- `apps/studio/pages/api/integrations/stripe-sync.ts` – drops the local
regex helper and uses the shared one.
`apps/studio/routes/api/integrations/stripe-sync.ts` re-exports this
handler on `master`, so both routes get the fix.
**Added:**
- `apps/studio/lib/api/apiHelpers.test.ts` – `getBearerToken` cases: a
valid token, lowercase `bearer`, extra whitespace,
missing/array/wrong-scheme/empty headers, and a 100k-whitespace header
that has to return in under 100 ms (the old regex takes about 4 s).
No other API handlers in `apps/studio` or `packages/` use this regex.
The remaining `Authorization` parsing in `lib/api/apiAuthenticate.ts`
and `lib/gotrue.ts` uses `replace(/bearer /i, '')`, which runs in linear
time.
## To test
- [ ] On a project, install the Stripe Sync integration from Studio
(Integrations → Stripe Sync). Installation starts and finishes.
- [ ] Uninstall it again. Uninstallation starts and finishes.
- [ ] `curl -i -X POST <studio-url>/api/integrations/stripe-sync -H
'Authorization: Basic abc' -H 'Content-Type: application/json' -d '{}'`
returns 401. Do the same with `Authorization: Bearer` followed only by
spaces, and with no `Authorization` header: both return 401.
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
Incident status banners/alerts should be automatically determined from
the status page, rather than being manually configured.
Adds a new endpoint, /api/incident-status, to return information about
active incidents. This information is fetched from the StatusPage API.
The endpoint is cached to reduce number of third-party API requests.
Co-authored-by: Ali Waseem <waseema393@gmail.com>
* Add layoutheader to self-hosted to allow showing assistant
* Fix layout
* Remove debug checks
* Check for key
* Dont load tables
* Fix assistant error handling
* Yeet
* Update turbo.json
* Another one
* god
* Fix
* Add fallback
* last attempt to fix
* Clean up
* take the wheel
* Tiny fix
* Skip enrich query for local, to match prod
---------
Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
* Move all studio files from /studio to /apps/studio.
* Move studio specific prettier ignores.
* Fix the ui references from studio.
* Fix the css imports.
* Fix all package.json issues.
* Fix the prettier setup for the studio app.
* Add .turbo folder to prettierignore.
* Fix the github workflows.