Files
Alaister YoungandAlaister Young b6c391a058 [FE-5114] (part 1) – refactor(studio): add native API helpers & routes (#54028)
## 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>
2026-12-01 20:53:57 +08:00

112 lines
3.6 KiB
TypeScript

import { createFileRoute } from '@tanstack/react-router'
import { IS_PLATFORM } from 'common'
import { parseJsonBody } from '@/lib/api/apiHelpers'
import { createApiHandlers, type ApiHandlerContext } from '@/lib/api/apiWrapper'
import { getEdgeFunctionTestUrl } from '@/lib/api/edgeFunctions'
import { DEFAULT_SUPABASE_PUBLIC_URL } from '@/lib/constants/api'
interface EdgeFunctionTestBody {
url: string
method: string
body?: unknown
headers?: Record<string, string | null | undefined>
}
async function handlePost({ request }: ApiHandlerContext) {
const parsedBody = await parseJsonBody<EdgeFunctionTestBody>(request)
try {
const { url: requestUrl, method, body: requestBody, headers: customHeaders } = parsedBody
const url = getEdgeFunctionTestUrl(requestUrl, {
isPlatform: IS_PLATFORM,
nimbusProjectsUrl: process.env.NIMBUS_PROD_PROJECTS_URL,
supabaseUrl: process.env.SUPABASE_URL,
supabasePublicUrl: process.env.SUPABASE_PUBLIC_URL || DEFAULT_SUPABASE_PUBLIC_URL,
})
if (url === undefined) {
return Response.json(
{
status: 400,
error: { message: 'Provided URL is not a valid Supabase edge function URL' },
},
{ status: 400 }
)
}
// Forward the supplied headers as given, dropping empty values. Header names are case
// insensitive, so they are merged on their lowercased name: a supplied `content-type` replaces
// the default rather than sitting beside it and being comma joined by `fetch`.
const suppliedHeaders = new Map<string, { name: string; value: string }>([
['content-type', { name: 'Content-Type', value: 'application/json' }],
])
Object.entries(customHeaders || {}).forEach(([key, value]) => {
const name = key.trim()
if (name.length === 0 || value === undefined || value === null || value === '') return
suppliedHeaders.set(name.toLowerCase(), { name, value })
})
const requestHeaders: Record<string, string> = Object.fromEntries(
[...suppliedHeaders.values()].map(({ name, value }) => [name, value])
)
// Prepare the request body based on method and Content-Type
let finalBody: BodyInit | undefined = undefined
if (method !== 'GET' && method !== 'HEAD') {
if (suppliedHeaders.get('content-type')?.value === 'application/json') {
finalBody = typeof requestBody === 'string' ? requestBody : JSON.stringify(requestBody)
} else {
finalBody = requestBody as BodyInit | undefined
}
}
const response = await fetch(url, {
method,
headers: requestHeaders,
body: finalBody,
redirect: 'manual', // don't follow the redirect and return response as is
})
const responseBody = await response.text()
const responseHeaders: Record<string, string | string[]> = {}
response.headers.forEach((value, key) => {
const existing = responseHeaders[key]
if (existing === undefined) {
responseHeaders[key] = value
} else if (Array.isArray(existing)) {
existing.push(value)
} else {
responseHeaders[key] = [existing, value]
}
})
return Response.json({
status: response.status,
headers: responseHeaders,
body: responseBody,
})
} catch (error) {
const message = error instanceof Error ? error.message : ''
return Response.json(
{
status: 500,
error: {
message: message || 'Failed to test edge function',
},
},
{ status: 500 }
)
}
}
export const Route = createFileRoute('/api/edge-functions/test')({
server: {
handlers: createApiHandlers({
POST: handlePost,
}),
},
})