Commit Graph
16 Commits
Author SHA1 Message Date
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
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
Alaister YoungandAlaister Young bbb0af65cb [FE-3106] (part 14) – refactor(studio): drop the dual-runtime shims and aliases (#53223)
Drops the remaining Next-era shims and aliases that only existed for the
dual runtime (FE-3106). Part 14 of the stack.

**Depends on:** #53222

**Changed:**
- ~45 files – import Sentry from `@sentry/react` directly instead of the
aliased `@sentry/nextjs`
- `hooks/ui/usePreventNavigationOnUnsavedChanges.ts` – is now the
TanStack `useBlocker` implementation (previously swapped in by a Vite
alias)
- `components/interfaces/App/RouteValidationWrapper.tsx` – `next/router`
→ `useNavigate` + the leaf route's `fullPath` (`/project/$ref/sql/$id`)
for the exempt-route and last-visited checks
- `hooks/misc/withAuth.tsx` – no `getLayout` forwarding
- `TemplateEditor.test.tsx` – renders inside a router for the
unsaved-changes blocker

**Removed:**
- `compat/sentry-nextjs.ts` and its Vite alias, the
`usePreventNavigationOnUnsavedChanges` alias and Next hook,
`types/next.ts` (`NextPageWithLayout`), the `@sentry/nextjs` dependency

The `compat/next/*` shims for `link`, `router`, `head`, `image`,
`navigation`, `dynamic` and `script` stay: about 300 components outside
`routes/**` still import them.

Addresses
[FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages).

## To test

- Trigger an error (e.g. a failing query) – it reaches Sentry as before
- Edit an email template or edge function and navigate away – the
unsaved-changes prompt appears
- Open an org you don't belong to – toast and redirect home; open a SQL
snippet, leave and come back – last snippet is restored

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-17 17:49:20 +09:00
Charis b3dd6612d7 feat(studio): classify errors with fault, reason, and per-tag Sentry sampling (#52730)
Follows #52707 (rename `ResponseError` to `StudioError`).

Resolves FE-4772.

## What

Introduces the error core for Studio error classification.

- **Tagged errors.** `lib/errors/studio-errors.ts` defines
`Data.TaggedError` classes (`RequestAborted`, `NetworkUnreachable`,
`MalformedResponse`, `PlatformError`, `UnclassifiedApiError`,
`DbConnectionTimeout`, `UnexpectedError`). Each carries `fault`,
`reason`, `classifiedBy` (`rule` or `default`), `retryable`, and
`service`. `StudioError` is the union type; use `isStudioError` instead
of `instanceof`.
- **Two classifiers** in `data/error-classification.ts`:
- `classifyResponseError` is only for errors from an API response: known
message patterns first, then defaults by status (5xx `PlatformError`,
4xx `UnclassifiedApiError`, no status `UnexpectedError`).
- `classifyError` is for everything else: aborts, browser fetch failures
(matched by message, so ordinary `TypeError` bugs stay
`UnexpectedError`), and unexpected errors.
- `handleError` picks between them, reports, and rethrows the same
instance so React Query receives the classified error.
- **Routing and sampling.** `lib/errors/error-routing.ts` maps every tag
to a Sentry sample rate (`SAMPLE_NEVER`, `SAMPLE_OTHER`, `SAMPLE_OWNED`,
`SAMPLE_ALWAYS`). `reportStudioError` tags events with `sample_rate`,
and `beforeSend` applies it. `alwaysCapture` reports at rate 1. The
global Sentry error `sampleRate` stays unset so the rates don't
multiply.
- **Network failures.** A fetch failure is a `user` fault with reason
`offline` when the browser reports being offline, and a `platform` fault
otherwise.
- **Hand-built errors.** Call sites that wrapped caught exceptions or
made up status codes now use `classifyError` or a specific class instead
of `classifyResponseError`.

## Behavior changes

- Errors that previously went unreported, including unexpected errors
with a message, are now reported to Sentry at their routed sample rate.
- `handleError` no longer logs the stack with `console.error`.
- `MalformedResponse` is defined but not produced yet; a follow-up adds
the empty-body check.

## Testing

- Unit tests for classification, routing, reporting, and the
`beforeSend` sampling helper.
- `pnpm vitest run data lib components/interfaces/ErrorHandling`,
typecheck, lint ratchet, and knip pass locally.
2026-11-04 13:19:01 -05:00
Charis df742bdb3b refactor(studio): rename ResponseError to StudioError (#52707)
## What

Moves the `ResponseError` class (`types/base.ts`) and the classified
error classes (`types/api-errors.ts`) into
`lib/errors/studio-errors.ts`, and renames `ResponseError` to
`StudioError`.

## Why

Studio's error classification is being expanded to cover errors that
don't come from API responses (thrown network failures, aborted
requests, unexpected client errors). The API-specific name and location
no longer fit. Landing the rename on its own keeps the follow-up PR,
which introduces the classified error model, small and reviewable.

## Notes for reviewers

- Mechanical change, no behavior change. Most of the diff is a one-line
import change per file plus import re-sorting by Prettier.
- Files that only use the type now use `import type { StudioError }`.
- `ResponseError` is no longer re-exported from `@/types`; there are no
compatibility shims at the old paths.
- Unrelated identifiers like `QueryResponseError` and
`parseResponseErrors` are unchanged.
2026-11-03 11:09:30 -05:00
Joshen Lim dc23320e43 Add sentry capture exception to apiWrapper (#47804)
## Context

As per PR title - also adjusts the imports for files consuming
`apiWrapper` to remove the default export for `apiWrapper`

Have tested locally by throwing an error in one of the API routes -
verified that the event shows up on Sentry

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* API errors are now captured in Sentry before returning server error
responses, improving production visibility while keeping endpoint
behavior the same.
* **Tests**
* Added coverage to confirm rejected handler executions are reported to
Sentry and return the expected HTTP 500 JSON payload.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-10 16:28:42 +08:00
Charis 205cbe7d26 chore(studio}: enforce import order, remove bare import specifiers (#44585) 2026-04-07 20:34:10 -04:00
Ivan Vasilov c5b6695380 fix: Remove auth from /incident-status and /incident-banner endpoints (#43751) 2026-03-13 15:29:54 +01:00
Charis befc817f94 feat: version who-knows-what of incident banner (#43726)
Feature

## What is the current behavior?

Incident banner logic depends on StatusPage and Supabase project for
metadata.

## What is the new behavior?

New incident banner logic that depends only on incident.io. Displays in
non-production environments for now because I haven't wired up the rest
of the workflow. This is just to allow a total end-to-end
testing/playground for test incidents <-> Slack <-> preview dashboard
for people to try out the UX.

## Additional context

You can test using my [test
incident](https://app.incident.io/supabase/incidents/405). This has
severity minor, so the preview site should have a banner. Toggle to
informative, hard refresh dashboard with cache off, and banner should
disappear. Toggle back to minor, hard refresh without cache again, and
banner should reappear. Same thing if you edit the "Banner shown" field
from 1 to -1 and back.
2026-03-12 16:55:53 -04:00
Matt Rossman e8ab92408f feat(assistant): enable Braintrust tracing for non-sensitive chats (#42963)
Enables Braintrust tracing for AI Assistant chats to support debugging
and future online evals.

**Code Changes**

- Wraps `generateAssistantResponse` in a Braintrust `traced()` span,
logging the user's latest message as input along with metadata
(`chatId`, `chatName`, `projectRef`, `userId`, `orgId`, `planId`, etc.)
- Threads JWT claims from `apiWrapper` → handler to log `userId` in
Braintrust without an extra API call (+ expanded `apiWrapper` tests)
- Threads `orgId` and `planId` from `getOrgAIDetails` to log in
Braintrust

**Infrastructure Changes**

- Created a "Vercel" service account in Braintrust
- Added `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_ID` env vars to the
studio-staging project in Vercel using a service token for the above
service account
- Added an "Overview" view to the Logs tab in the Braintrust Assistant
project to surface the new metadata

**Precautions**

- HIPAA sensitive projects are excluded from logging (see
https://github.com/supabase/supabase/pull/42787 for the detection logic)
- Production is temporarily excluded from logging until we're confident
in the setup

**Testing steps**

- Chat with the AI Assistant in the [studio-staging preview
build](https://github.com/supabase/supabase/pull/42963#issuecomment-3917178023)
below
- Visit the [Logs tab in the Braintrust Assistant
project](https://www.braintrust.dev/app/supabase.io/p/Assistant/logs)
and inspect the trace

<img width="4680" height="962" alt="CleanShot 2026-02-18 at 17 43 55@2x"
src="https://github.com/user-attachments/assets/c3a11b21-4e7f-4e90-bdab-a25ab8ee0d1f"
/>

<img width="2632" height="1288" alt="CleanShot 2026-02-18 at 17 45
04@2x"
src="https://github.com/user-attachments/assets/6c7b6ebc-5090-4ede-8f71-859ff7e386aa"
/>

**References**
- https://www.braintrust.dev/docs/integrations/sdk-integrations/vercel
- https://www.braintrust.dev/docs/instrument/custom-tracing

Closes AI-438
2026-02-19 11:43:47 -05:00
Kevin Grüneberg f0436716f9 perf: use getClaims for API endpoint auth (#39311)
Use getClaims instead of getUser which avoids a network call to GoTrue to validate the user in case of asymmetric keys - this shaves off a good amount of latency for every API call.
2025-10-08 09:59:27 +08:00
Charis 283b125369 fix: failing type errors in build (#38761)
* fix(www): types for awaited params

* fix(docs): no extraneous exports from route page

* fix(studio): api handler types, no non-handlers allowed in pages
2025-09-17 15:55:38 +10:00
Joshen LimandAlaister Young dbb413beeb Chore/deprecate lib common fetch 03 (#36529)
* Deprecate use of getWithTimeout, refactor BuildingState and RestoringState to use RQ

* Refactor profile-create-mutation to use data/fetchers, and edge-function-status-query to use fetch

* Shift post from lib/common/fetch, refactor bucket-object-download-mutation

* Address feedback

* Minor fix

* Refactor post calls from lib/common/fetch in auth pages to data/fetchers

* Add missing POST users endpoint + small fix when deleting user via context menu

* Remove all use of any imports from lib/common/fetch

* Clean up remaining usage of lib/common/fetch

* Fix fetchHeadWithTimeout

* simplify handleFetchError

* allow handleFetchError to accept unknown

* non-breaking change

* small fixes

* fix query path

---------

Co-authored-by: Alaister Young <a@alaisteryoung.com>
2025-07-21 16:59:17 +08:00
Ivan Vasilov 92955d5555 chore: Bump sentry to v8+ (#29896)
* Bump sentry to v8.

* Fix all obsolete APIs.

* Fix the sentry configs.

* Add pages for testing sentry.

* Add missing imports to sentry.config file.

* Add base path to the api path.

* Remove extra files.
2024-10-17 11:39:06 +02:00
Kevin Grüneberg f9a55935f5 chore: use type imports for types/interfaces (#21738) 2024-03-04 20:48:22 +08:00
Ivan Vasilov 436bdb10ae chore: Move the studio app to apps/studio (#18915)
* 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.
2023-11-15 12:38:55 +01:00