Files
supabase/apps/studio/lib/api/apiWrapper.ts
T
Alaister YoungandAlaister Young 0252fd8cad [FE-5114] (part 7) – refactor(studio): remove Next API adapter (#54034)
## 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>
2026-12-01 23:01:47 +08:00

95 lines
3.1 KiB
TypeScript

import * as Sentry from '@sentry/react'
import type { JwtPayload } from '@supabase/supabase-js'
import { IS_PLATFORM } from '../constants'
import { authenticateRequest } from './apiAuthenticate'
import { InvalidJsonError } from './apiHelpers'
import { isStudioError } from '@/lib/errors/studio-errors'
import type { ResponseFailure } from '@/types'
type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'
export interface ApiHandlerContext {
request: Request
params: Record<string, string>
claims?: JwtPayload
}
export type ApiHandler = (ctx: ApiHandlerContext) => Response | Promise<Response>
type ServerRouteHandler = (ctx: {
request: Request
params?: Record<string, string>
}) => Promise<Response>
export function isResponseOk<T>(response: T | ResponseFailure | undefined): response is T {
if (response === undefined || response === null) {
return false
}
if (isStudioError(response)) {
return false
}
if (typeof response === 'object' && 'error' in response && Boolean(response.error)) {
return false
}
return true
}
/**
* Wrap native TanStack Start API route handlers with optional platform JWT authentication,
* malformed-JSON 400 handling, Sentry error reporting, and 405 Method Not Allowed (with an
* `Allow` header derived from the registered methods) for any other method, via `ANY` and
* for a HEAD request dispatched to a GET-only handler.
*/
export function createApiHandlers<M extends ApiMethod>(
handlers: Record<M, ApiHandler>,
options?: { withAuth?: boolean }
): Record<M | 'ANY', ServerRouteHandler> {
const allowedMethods = Object.keys(handlers) as M[]
const wrapped = {} as Record<M | 'ANY', ServerRouteHandler>
const methodNotAllowed = (request: Request) =>
Response.json(
{ data: null, error: { message: `Method ${request.method} Not Allowed` } },
{ status: 405, headers: { Allow: allowedMethods.join(', ') } }
)
for (const method of allowedMethods) {
const handler = handlers[method]
wrapped[method] = async ({ request, params = {} }) => {
// TanStack Start dispatches HEAD to GET when no HEAD handler is registered.
if (request.method !== method) return methodNotAllowed(request)
try {
let claims: JwtPayload | undefined
if (IS_PLATFORM && options?.withAuth) {
const authResult = await authenticateRequest(request)
if (!isResponseOk(authResult)) {
return Response.json(
{ error: { message: `Unauthorized: ${authResult.error.message}` } },
{ status: 401 }
)
}
claims = authResult
}
return await handler({ request, params, claims })
} catch (error) {
if (error instanceof InvalidJsonError) {
return Response.json({ error: { message: 'Invalid JSON' } }, { status: 400 })
}
Sentry.captureException(error)
return Response.json({ error: { message: 'Internal Server Error' } }, { status: 500 })
}
}
}
wrapped.ANY = async ({ request }) => methodNotAllowed(request)
return wrapped
}