From 408c61cb031b3c6877884fbd30982a38aa390ad0 Mon Sep 17 00:00:00 2001 From: Jeremias Menichelli Date: Tue, 17 Nov 2026 19:13:41 +0100 Subject: [PATCH] chore: a PoC for new reference pages and schema --- .prettierignore | 3 +- docs/reference-beta/definition.schema.json | 288 +++++++++++++++++ .../adapters-elysia-supabase-error.md | 38 +++ .../adapters-elysia-with-supabase.md | 64 ++++ .../definitions/adapters-h3-with-supabase.md | 60 ++++ .../adapters-hono-with-supabase.md | 54 ++++ .../definitions/core-create-admin-client.md | 66 ++++ .../definitions/core-create-context-client.md | 75 +++++ .../definitions/core-extract-credentials.md | 40 +++ .../definitions/core-resolve-env.md | 39 +++ .../definitions/core-verify-auth-options.md | 51 +++ .../definitions/core-verify-auth.md | 89 ++++++ .../core-verify-credentials-options.md | 51 +++ .../definitions/core-verify-credentials.md | 110 +++++++ ...lient-with-supabase-admin-client-config.md | 16 + ...admin-client-with-supabase-admin-client.md | 48 +++ .../middleware-claims-with-claims-config.md | 61 ++++ .../middleware-claims-with-claims.md | 111 +++++++ ...ware-client-with-supabase-client-config.md | 17 + .../middleware-client-with-supabase-client.md | 48 +++ ...admin-with-postgres-admin-client-config.md | 78 +++++ ...stgres-admin-with-postgres-admin-client.md | 123 ++++++++ .../definitions/middleware-postgres-ident.md | 49 +++ .../middleware-postgres-postgres-api.md | 30 ++ ...ddleware-postgres-postgres-pool-options.md | 43 +++ .../middleware-postgres-request-claims.md | 25 ++ ...re-postgres-with-postgres-client-config.md | 78 +++++ ...iddleware-postgres-with-postgres-client.md | 136 ++++++++ ...ired-claims-with-required-claims-config.md | 61 ++++ ...re-required-claims-with-required-claims.md | 120 +++++++ .../definitions/server-allow-with-key.md | 15 + .../definitions/server-allow.md | 15 + .../definitions/server-api-key-format.md | 15 + .../definitions/server-auth-config.md | 34 ++ .../definitions/server-auth-error.md | 119 +++++++ .../server-auth-failure-context.md | 76 +++++ .../definitions/server-auth-generic-error.md | 13 + .../definitions/server-auth-mode-with-key.md | 31 ++ .../definitions/server-auth-mode.md | 35 +++ .../definitions/server-auth-result.md | 43 +++ .../definitions/server-client-auth.md | 24 ++ .../server-create-admin-client-options.md | 29 ++ .../server-create-context-client-options.md | 40 +++ .../server-create-supabase-client-error.md | 13 + .../server-create-supabase-context.md | 138 ++++++++ .../server-credentialed-auth-mode.md | 15 + .../definitions/server-credentials.md | 27 ++ .../definitions/server-env-error.md | 109 +++++++ .../definitions/server-env-generic-error.md | 13 + .../definitions/server-error-code-header.md | 15 + .../definitions/server-error-payload.md | 46 +++ .../server-error-response-config.md | 45 +++ .../definitions/server-error-source.md | 19 ++ .../definitions/server-errors.md | 123 ++++++++ .../definitions/server-from-supabase-url.md | 43 +++ .../server-invalid-api-key-error.md | 15 + .../server-invalid-credentials-error.md | 20 ++ .../definitions/server-invalid-jwt-error.md | 17 + .../server-jwks-fetch-failed-error.md | 15 + .../server-jwks-not-configured-error.md | 16 + .../definitions/server-jwtclaims.md | 62 ++++ .../server-minimal-error-payload.md | 17 + ...rver-missing-authorization-server-error.md | 13 + .../server-missing-connection-string-error.md | 15 + .../server-missing-credentials-error.md | 15 + ...r-missing-default-publishable-key-error.md | 13 + ...server-missing-default-secret-key-error.md | 13 + .../server-missing-publishable-key-error.md | 13 + .../server-missing-resource-server-error.md | 13 + .../server-missing-secret-key-error.md | 13 + .../server-missing-supabase-urlerror.md | 13 + .../server-no-keys-configured-error.md | 16 + .../server-oauth-protected-resource-config.md | 68 ++++ .../server-postgres-connect-paused-error.md | 16 + .../server-postgres-pool-busy-error.md | 16 + .../definitions/server-postgres-pool-error.md | 120 +++++++ .../server-received-credentials.md | 32 ++ .../server-resource-metadata-options.md | 24 ++ .../server-resource-metadata-response.md | 43 +++ .../server-short-circuit-config.md | 42 +++ .../definitions/server-supabase-context.md | 50 +++ .../definitions/server-supabase-env.md | 57 ++++ .../server-supabase-server-error-options.md | 36 +++ .../server-supabase-server-error.md | 110 +++++++ .../server-unauthorized-response-options.md | 19 ++ .../server-unauthorized-response.md | 38 +++ .../server-unsupported-role-error.md | 17 + .../server-unusable-credential-error.md | 22 ++ .../definitions/server-url-option.md | 13 + .../definitions/server-user-claims.md | 44 +++ .../server-with-oauth-protected-resource.md | 145 +++++++++ .../server-with-supabase-config.md | 126 ++++++++ .../definitions/server-with-supabase.md | 159 ++++++++++ package.json | 6 +- pnpm-lock.yaml | 18 +- scripts/check-reference-beta.mjs | 68 ++++ scripts/generate-reference-beta.mjs | 297 ++++++++++++++++++ 97 files changed, 5039 insertions(+), 13 deletions(-) create mode 100644 docs/reference-beta/definition.schema.json create mode 100644 docs/reference-beta/definitions/adapters-elysia-supabase-error.md create mode 100644 docs/reference-beta/definitions/adapters-elysia-with-supabase.md create mode 100644 docs/reference-beta/definitions/adapters-h3-with-supabase.md create mode 100644 docs/reference-beta/definitions/adapters-hono-with-supabase.md create mode 100644 docs/reference-beta/definitions/core-create-admin-client.md create mode 100644 docs/reference-beta/definitions/core-create-context-client.md create mode 100644 docs/reference-beta/definitions/core-extract-credentials.md create mode 100644 docs/reference-beta/definitions/core-resolve-env.md create mode 100644 docs/reference-beta/definitions/core-verify-auth-options.md create mode 100644 docs/reference-beta/definitions/core-verify-auth.md create mode 100644 docs/reference-beta/definitions/core-verify-credentials-options.md create mode 100644 docs/reference-beta/definitions/core-verify-credentials.md create mode 100644 docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client-config.md create mode 100644 docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client.md create mode 100644 docs/reference-beta/definitions/middleware-claims-with-claims-config.md create mode 100644 docs/reference-beta/definitions/middleware-claims-with-claims.md create mode 100644 docs/reference-beta/definitions/middleware-client-with-supabase-client-config.md create mode 100644 docs/reference-beta/definitions/middleware-client-with-supabase-client.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client-config.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-ident.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-postgres-api.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-postgres-pool-options.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-request-claims.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-with-postgres-client-config.md create mode 100644 docs/reference-beta/definitions/middleware-postgres-with-postgres-client.md create mode 100644 docs/reference-beta/definitions/middleware-required-claims-with-required-claims-config.md create mode 100644 docs/reference-beta/definitions/middleware-required-claims-with-required-claims.md create mode 100644 docs/reference-beta/definitions/server-allow-with-key.md create mode 100644 docs/reference-beta/definitions/server-allow.md create mode 100644 docs/reference-beta/definitions/server-api-key-format.md create mode 100644 docs/reference-beta/definitions/server-auth-config.md create mode 100644 docs/reference-beta/definitions/server-auth-error.md create mode 100644 docs/reference-beta/definitions/server-auth-failure-context.md create mode 100644 docs/reference-beta/definitions/server-auth-generic-error.md create mode 100644 docs/reference-beta/definitions/server-auth-mode-with-key.md create mode 100644 docs/reference-beta/definitions/server-auth-mode.md create mode 100644 docs/reference-beta/definitions/server-auth-result.md create mode 100644 docs/reference-beta/definitions/server-client-auth.md create mode 100644 docs/reference-beta/definitions/server-create-admin-client-options.md create mode 100644 docs/reference-beta/definitions/server-create-context-client-options.md create mode 100644 docs/reference-beta/definitions/server-create-supabase-client-error.md create mode 100644 docs/reference-beta/definitions/server-create-supabase-context.md create mode 100644 docs/reference-beta/definitions/server-credentialed-auth-mode.md create mode 100644 docs/reference-beta/definitions/server-credentials.md create mode 100644 docs/reference-beta/definitions/server-env-error.md create mode 100644 docs/reference-beta/definitions/server-env-generic-error.md create mode 100644 docs/reference-beta/definitions/server-error-code-header.md create mode 100644 docs/reference-beta/definitions/server-error-payload.md create mode 100644 docs/reference-beta/definitions/server-error-response-config.md create mode 100644 docs/reference-beta/definitions/server-error-source.md create mode 100644 docs/reference-beta/definitions/server-errors.md create mode 100644 docs/reference-beta/definitions/server-from-supabase-url.md create mode 100644 docs/reference-beta/definitions/server-invalid-api-key-error.md create mode 100644 docs/reference-beta/definitions/server-invalid-credentials-error.md create mode 100644 docs/reference-beta/definitions/server-invalid-jwt-error.md create mode 100644 docs/reference-beta/definitions/server-jwks-fetch-failed-error.md create mode 100644 docs/reference-beta/definitions/server-jwks-not-configured-error.md create mode 100644 docs/reference-beta/definitions/server-jwtclaims.md create mode 100644 docs/reference-beta/definitions/server-minimal-error-payload.md create mode 100644 docs/reference-beta/definitions/server-missing-authorization-server-error.md create mode 100644 docs/reference-beta/definitions/server-missing-connection-string-error.md create mode 100644 docs/reference-beta/definitions/server-missing-credentials-error.md create mode 100644 docs/reference-beta/definitions/server-missing-default-publishable-key-error.md create mode 100644 docs/reference-beta/definitions/server-missing-default-secret-key-error.md create mode 100644 docs/reference-beta/definitions/server-missing-publishable-key-error.md create mode 100644 docs/reference-beta/definitions/server-missing-resource-server-error.md create mode 100644 docs/reference-beta/definitions/server-missing-secret-key-error.md create mode 100644 docs/reference-beta/definitions/server-missing-supabase-urlerror.md create mode 100644 docs/reference-beta/definitions/server-no-keys-configured-error.md create mode 100644 docs/reference-beta/definitions/server-oauth-protected-resource-config.md create mode 100644 docs/reference-beta/definitions/server-postgres-connect-paused-error.md create mode 100644 docs/reference-beta/definitions/server-postgres-pool-busy-error.md create mode 100644 docs/reference-beta/definitions/server-postgres-pool-error.md create mode 100644 docs/reference-beta/definitions/server-received-credentials.md create mode 100644 docs/reference-beta/definitions/server-resource-metadata-options.md create mode 100644 docs/reference-beta/definitions/server-resource-metadata-response.md create mode 100644 docs/reference-beta/definitions/server-short-circuit-config.md create mode 100644 docs/reference-beta/definitions/server-supabase-context.md create mode 100644 docs/reference-beta/definitions/server-supabase-env.md create mode 100644 docs/reference-beta/definitions/server-supabase-server-error-options.md create mode 100644 docs/reference-beta/definitions/server-supabase-server-error.md create mode 100644 docs/reference-beta/definitions/server-unauthorized-response-options.md create mode 100644 docs/reference-beta/definitions/server-unauthorized-response.md create mode 100644 docs/reference-beta/definitions/server-unsupported-role-error.md create mode 100644 docs/reference-beta/definitions/server-unusable-credential-error.md create mode 100644 docs/reference-beta/definitions/server-url-option.md create mode 100644 docs/reference-beta/definitions/server-user-claims.md create mode 100644 docs/reference-beta/definitions/server-with-oauth-protected-resource.md create mode 100644 docs/reference-beta/definitions/server-with-supabase-config.md create mode 100644 docs/reference-beta/definitions/server-with-supabase.md create mode 100644 scripts/check-reference-beta.mjs create mode 100644 scripts/generate-reference-beta.mjs diff --git a/.prettierignore b/.prettierignore index 0474c62..87b41ea 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,4 +3,5 @@ dist pnpm-lock.yaml # generated by release-please; prettier restyles its bullets, causing churn CHANGELOG.md -jsr.json \ No newline at end of file +jsr.json +docs/reference-beta/definitions diff --git a/docs/reference-beta/definition.schema.json b/docs/reference-beta/definition.schema.json new file mode 100644 index 0000000..229a014 --- /dev/null +++ b/docs/reference-beta/definition.schema.json @@ -0,0 +1,288 @@ +{ + "title": "Reference definition frontmatter", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "id": { + "description": "Stable, shared across languages. Must match the file name.", + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "kind": { + "type": "string", + "enum": ["method", "command", "endpoint", "class", "type", "constant"] + }, + "category": { + "description": "Groups definitions on the library index page.", + "default": "general", + "type": "string" + }, + "title": { + "type": "string" + }, + "symbol": { + "description": "Fully qualified name, e.g. `supabase.auth.signUp`.", + "type": "string" + }, + "summary": { + "description": "One line, used in lists.", + "type": "string" + }, + "description": { + "description": "Markdown.", + "type": "string" + }, + "signature": { + "description": "Methods, classes, types and constants.", + "type": "string" + }, + "usage": { + "description": "Commands only.", + "type": "string" + }, + "http": { + "description": "Endpoints only.", + "type": "object", + "properties": { + "method": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": ["method", "path"], + "additionalProperties": false + }, + "type_params": { + "type": "array", + "items": { + "type": "string" + } + }, + "stability": { + "default": "stable", + "type": "string", + "enum": ["stable", "beta", "experimental"] + }, + "deprecated": { + "default": false, + "type": "boolean" + }, + "since": { + "type": "string" + }, + "requires": { + "type": "array", + "items": { + "type": "string" + } + }, + "inherits_flags": { + "description": "Commands that also accept a shared flag group.", + "type": "string" + }, + "auth": { + "description": "Endpoints only.", + "type": "object", + "properties": { + "scopes": { + "default": [], + "type": "array", + "items": { + "type": "string" + } + }, + "permissions": { + "default": [], + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "parameters": { + "description": "Arguments of methods, commands and endpoints; constructor arguments of classes.", + "default": [], + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + "properties": { + "description": "Members of classes and types. Same shape as parameters, `location: property`.", + "default": [], + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + "returns": { + "description": "Methods.", + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": ["type"], + "additionalProperties": false + }, + "responses": { + "description": "Endpoints only.", + "type": "array", + "items": { + "type": "object", + "properties": { + "status": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "description": { + "type": "string" + }, + "schema": {} + }, + "required": ["status"], + "additionalProperties": false + } + }, + "throws": { + "default": [], + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "description": "Error type. Omitted when only a description is given.", + "type": "string" + }, + "description": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "examples": { + "default": [], + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "description": "Stable within the definition.", + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "description": "Markdown.", + "type": "string" + }, + "lang": { + "description": "Code fence language, e.g. `js`, `sh`.", + "default": "plaintext", + "type": "string" + }, + "code": { + "type": "string" + }, + "response": { + "description": "Sample output.", + "type": "string" + } + }, + "required": ["id", "title", "code"], + "additionalProperties": false + } + } + }, + "required": ["id", "kind", "title", "summary"], + "additionalProperties": false, + "$defs": { + "__schema0": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "location": { + "description": "Where the parameter is passed.", + "type": "string", + "enum": [ + "argument", + "positional", + "flag", + "path", + "query", + "header", + "body", + "property" + ] + }, + "type": { + "type": "string" + }, + "required": { + "default": false, + "type": "boolean" + }, + "description": { + "description": "Markdown.", + "type": "string" + }, + "default": {}, + "allowed_values": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ] + } + }, + "short": { + "description": "Short flag, e.g. `-i`. Commands only.", + "type": "string" + }, + "env": { + "description": "Environment variable that sets this parameter.", + "type": "string" + }, + "variadic": { + "type": "boolean" + }, + "deprecated": { + "type": "boolean" + }, + "replaced_by": { + "type": "string" + }, + "children": { + "description": "Nested fields, same shape.", + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": ["name"], + "additionalProperties": false + } + } +} diff --git a/docs/reference-beta/definitions/adapters-elysia-supabase-error.md b/docs/reference-beta/definitions/adapters-elysia-supabase-error.md new file mode 100644 index 0000000..ea74020 --- /dev/null +++ b/docs/reference-beta/definitions/adapters-elysia-supabase-error.md @@ -0,0 +1,38 @@ +--- +id: adapters-elysia-supabase-error +kind: class +category: Adapters +title: SupabaseError +symbol: "@supabase/server/adapters/elysia.SupabaseError" +summary: Wraps an `AuthError` as an Elysia-compatible error. +description: |- + Wraps an `AuthError` as an Elysia-compatible error. + + Discriminate in `onError` via `code === 'SupabaseError'`. The original + `AuthError` is available as the typed `.cause`. +signature: class SupabaseError extends Error +stability: stable +deprecated: true +parameters: + - name: inner + location: argument + type: AuthError + required: true + description: "" +properties: + - name: status + location: property + type: number + required: true + description: "" + - name: cause + location: property + type: AuthError + required: true + description: "" +examples: [] +--- + +> **Deprecated:** Removed with the Elysia adapter on December 1, 2026. The Elysia + bridge from the framework integration guide answers auth failures with + a `Response` instead: https://supabase.com/docs/reference/server/frameworks diff --git a/docs/reference-beta/definitions/adapters-elysia-with-supabase.md b/docs/reference-beta/definitions/adapters-elysia-with-supabase.md new file mode 100644 index 0000000..172aea5 --- /dev/null +++ b/docs/reference-beta/definitions/adapters-elysia-with-supabase.md @@ -0,0 +1,64 @@ +--- +id: adapters-elysia-with-supabase +kind: method +category: Adapters +title: withSupabase +symbol: "@supabase/server/adapters/elysia.withSupabase" +summary: Elysia plugin that creates a `SupabaseContext` and makes it available in route handlers. +description: |- + Elysia plugin that creates a `SupabaseContext` and makes it available in route handlers. + + Skips if a previous plugin already set the context, enabling route-level overrides. + Throws a `SupabaseError` on auth failure. `.status` is on the error directly; the original + `AuthError` is available as the typed `.cause`. Discriminate in `onError` via `code === 'SupabaseError'`. +signature: 'withSupabase(config?: Omit): Elysia<"", { decorator: {}; store: {}; derive: {}; resolve: {} }, { typebox: {}; error: { SupabaseError: SupabaseError } }, { schema: {}; standaloneSchema: {}; macro: {}; macroFn: {}; parser: {}; response: {} }, {}, { derive: {}; resolve: { supabaseContext: SupabaseContext }; schema: {}; standaloneSchema: {}; response: ExtractErrorFromHandle<{ supabaseContext: SupabaseContext }> }, { derive: {}; resolve: {}; schema: {}; standaloneSchema: {}; response: {} }>' +stability: stable +deprecated: true +parameters: + - name: config + location: argument + type: Omit + required: false + description: Auth modes and optional environment overrides. CORS is excluded — use Elysia's CORS utilities. +returns: + type: 'Elysia<"", { decorator: {}; store: {}; derive: {}; resolve: {} }, { typebox: {}; error: { SupabaseError: SupabaseError } }, { schema: {}; standaloneSchema: {}; macro: {}; macroFn: {}; parser: {}; response: {} }, {}, { derive: {}; resolve: { supabaseContext: SupabaseContext }; schema: {}; standaloneSchema: {}; response: ExtractErrorFromHandle<{ supabaseContext: SupabaseContext }> }, { derive: {}; resolve: {}; schema: {}; standaloneSchema: {}; response: {} }>' + description: An Elysia plugin that exposes `supabaseContext`. +throws: [] +examples: + - id: app-wide-auth-via-use + title: App-wide auth via .use() + lang: ts + code: | + import { Elysia } from 'elysia' + import { withSupabase } from '@supabase/server/adapters/elysia' + + const app = new Elysia() + .use(withSupabase({ auth: 'user' })) + .get('/games', async ({ supabaseContext }) => { + const { data } = await supabaseContext.supabase.from('favorite_games').select() + return data + }) + + app.listen(3000) + - id: per-route-auth-via-scoped-use + title: Per-route auth via scoped .use() + lang: ts + code: | + import { Elysia } from 'elysia' + import { withSupabase } from '@supabase/server/adapters/elysia' + + const app = new Elysia() + .get('/health', () => ({ status: 'ok' })) + .group('/api', (app) => + app + .use(withSupabase({ auth: 'user' })) + .get('/profile', async ({ supabaseContext }) => { + return supabaseContext.userClaims + }) + ) + + app.listen(3000) +--- + +> **Deprecated:** Removed on December 1, 2026. Use the Elysia bridge from the + framework integration guide instead: https://supabase.com/docs/reference/server/frameworks diff --git a/docs/reference-beta/definitions/adapters-h3-with-supabase.md b/docs/reference-beta/definitions/adapters-h3-with-supabase.md new file mode 100644 index 0000000..74ae1d9 --- /dev/null +++ b/docs/reference-beta/definitions/adapters-h3-with-supabase.md @@ -0,0 +1,60 @@ +--- +id: adapters-h3-with-supabase +kind: method +category: Adapters +title: withSupabase +symbol: "@supabase/server/adapters/h3.withSupabase" +summary: H3 middleware that creates a `SupabaseContext` and stores it in `event.context.supabaseContext`. +description: |- + H3 middleware that creates a `SupabaseContext` and stores it in `event.context.supabaseContext`. + + Skips if a previous middleware already set the context, enabling chained middleware via `app.use()`. + Throws an `HTTPError` on auth failure. +signature: 'withSupabase(config?: Omit): Middleware' +stability: stable +deprecated: true +parameters: + - name: config + location: argument + type: Omit + required: false + description: Auth modes and optional environment overrides. CORS is excluded — use H3's CORS utilities. +returns: + type: Middleware + description: An H3 middleware. +throws: [] +examples: + - id: app-wide-auth-via-app-use + title: App-wide auth via app.use() + lang: ts + code: | + import { H3 } from 'h3' + import { withSupabase } from '@supabase/server/adapters/h3' + + const app = new H3() + app.use(withSupabase({ auth: 'user' })) + + app.get('/games', async (event) => { + const { supabase } = event.context.supabaseContext + return supabase.from('favorite_games').select() + }) + + export default { fetch: app.fetch } + - id: per-route-auth-via-define-handler + title: Per-route auth via defineHandler + lang: ts + code: | + import { defineHandler } from 'h3' + import { withSupabase } from '@supabase/server/adapters/h3' + + export default defineHandler({ + middleware: [withSupabase({ auth: 'user' })], + handler: async (event) => { + const { supabase } = event.context.supabaseContext + return supabase.from('favorite_games').select() + }, + }) +--- + +> **Deprecated:** Removed on December 1, 2026. Use the H3 bridge from the + framework integration guide instead: https://supabase.com/docs/reference/server/frameworks diff --git a/docs/reference-beta/definitions/adapters-hono-with-supabase.md b/docs/reference-beta/definitions/adapters-hono-with-supabase.md new file mode 100644 index 0000000..43c3122 --- /dev/null +++ b/docs/reference-beta/definitions/adapters-hono-with-supabase.md @@ -0,0 +1,54 @@ +--- +id: adapters-hono-with-supabase +kind: method +category: Adapters +title: withSupabase +symbol: "@supabase/server/adapters/hono.withSupabase" +summary: Hono middleware that creates a `SupabaseContext` and stores it in `c.var.supabaseContext`. +description: |- + Hono middleware that creates a `SupabaseContext` and stores it in `c.var.supabaseContext`. + + Skips if a previous middleware already set the context, enabling route-level overrides. + Throws a Hono `HTTPException` on auth failure. +signature: 'withSupabase(config?: Omit): MiddlewareHandler<{ Variables: { supabaseContext: SupabaseContext } }>' +stability: stable +deprecated: true +parameters: + - name: config + location: argument + type: Omit + required: false + description: Auth modes and optional environment overrides. CORS is excluded — use Hono's `cors()`. +returns: + type: "MiddlewareHandler<{ Variables: { supabaseContext: SupabaseContext } }>" + description: A Hono middleware that sets `c.var.supabaseContext`. +throws: [] +examples: + - id: app-wide-auth-via-app-use + title: App-wide auth via app.use() + lang: ts + code: | + import { Hono } from 'hono' + import { withSupabase } from '@supabase/server/adapters/hono' + import type { SupabaseContext } from '@supabase/server' + + type Env = { + Variables: { + supabaseContext: SupabaseContext + } + } + + const app = new Hono() + app.use('*', withSupabase({ auth: 'user' })) + + app.get('/profile', async (c) => { + const { supabase } = c.var.supabaseContext + const { data } = await supabase.rpc('get_profile') + return c.json(data) + }) + + export default { fetch: app.fetch } +--- + +> **Deprecated:** Removed on December 1, 2026. Use the Hono bridge from the + framework integration guide instead: https://supabase.com/docs/reference/server/frameworks diff --git a/docs/reference-beta/definitions/core-create-admin-client.md b/docs/reference-beta/definitions/core-create-admin-client.md new file mode 100644 index 0000000..161fb56 --- /dev/null +++ b/docs/reference-beta/definitions/core-create-admin-client.md @@ -0,0 +1,66 @@ +--- +id: core-create-admin-client +kind: method +category: Primitives +title: createAdminClient +symbol: "@supabase/server/core.createAdminClient" +summary: Creates an admin Supabase client that bypasses Row-Level Security. +description: |- + Creates an admin Supabase client that bypasses Row-Level Security. + + Uses a secret key for authentication, giving full access to all data. + Stateless — one client per request. + + ## Which key is used + + With `auth.keyName` set, that named key from `SUPABASE_SECRET_KEYS` is used — + and it throws if the key doesn't exist. With `keyName` omitted, the `default` + key is used, falling back to the first key in the set when no `default` exists. + + Note this differs from the `"secret"` auth mode, which matches the `default` + key only and never falls back — see `AuthModeWithKey`. +signature: "createAdminClient(options?: CreateAdminClientOptions): SupabaseClient" +stability: stable +deprecated: false +parameters: + - name: options + location: argument + type: CreateAdminClientOptions + required: false + description: "" + children: + - name: auth + location: argument + type: Pick + required: false + description: Auth identity — key name from the verified request. + - name: env + location: argument + type: Partial + required: false + description: Override auto-detected environment variables. + - name: supabaseOptions + location: argument + type: SupabaseClientOptions + required: false + description: Options forwarded to `createClient()`. `accessToken` is stripped; auth settings are force-overwritten. +returns: + type: SupabaseClient + description: "" +throws: + - type: EnvError + description: If `SUPABASE_URL` is missing or the specified secret key is not found. +examples: + - id: basic-usage + title: Basic usage + lang: ts + code: | + // Uses the `default` secret key (or the first key if no `default` exists) + const supabaseAdmin = createAdminClient() + const { data } = await supabaseAdmin.from('audit_log').insert({ action: 'user_login' }) + - id: specific-named-key + title: Specific named key + lang: ts + code: | + const supabaseAdmin = createAdminClient({ auth: { keyName: 'internal' } }) +--- diff --git a/docs/reference-beta/definitions/core-create-context-client.md b/docs/reference-beta/definitions/core-create-context-client.md new file mode 100644 index 0000000..c8caf6f --- /dev/null +++ b/docs/reference-beta/definitions/core-create-context-client.md @@ -0,0 +1,75 @@ +--- +id: core-create-context-client +kind: method +category: Primitives +title: createContextClient +symbol: "@supabase/server/core.createContextClient" +summary: Creates a Supabase client scoped to the caller's context. +description: |- + Creates a Supabase client scoped to the caller's context. + + Configured with a publishable key and (optionally) the caller's JWT, + so Row-Level Security policies apply. Stateless — one client per request. + + ## Which key is used + + With `auth.keyName` set, that named key from `SUPABASE_PUBLISHABLE_KEYS` is + used — and it throws if the key doesn't exist. With `keyName` omitted, the + `default` key is used, falling back to the first key in the set when no + `default` exists. + + Note this differs from the `"publishable"` auth mode, which matches the + `default` key only and never falls back — see `AuthModeWithKey`. +signature: "createContextClient(options?: CreateContextClientOptions): SupabaseClient" +stability: stable +deprecated: false +parameters: + - name: options + location: argument + type: CreateContextClientOptions + required: false + description: "" + children: + - name: auth + location: argument + type: ClientAuth + required: false + description: Auth identity — token and key name from the verified request. + children: + - name: token + location: argument + type: string | null + required: false + description: The caller's JWT, or `null` for anonymous access. + - name: keyName + location: argument + type: string | null + required: false + description: Name of the API key to use. Falls back to `"default"`, then first available. + - name: env + location: argument + type: Partial + required: false + description: Override auto-detected environment variables. + - name: supabaseOptions + location: argument + type: SupabaseClientOptions + required: false + description: Options forwarded to `createClient()`. `accessToken` is stripped; auth settings are force-overwritten. +returns: + type: SupabaseClient + description: "" +throws: + - type: EnvError + description: If `SUPABASE_URL` is missing or the specified publishable key is not found. +examples: + - id: with-verified-auth + title: With verified auth + lang: ts + code: | + const { data: auth } = await verifyAuth(request, { auth: 'user' }) + const supabase = createContextClient({ + auth: { token: auth.token, keyName: auth.keyName }, + }) + const { data } = await supabase.rpc('get_my_items') +--- diff --git a/docs/reference-beta/definitions/core-extract-credentials.md b/docs/reference-beta/definitions/core-extract-credentials.md new file mode 100644 index 0000000..0649484 --- /dev/null +++ b/docs/reference-beta/definitions/core-extract-credentials.md @@ -0,0 +1,40 @@ +--- +id: core-extract-credentials +kind: method +category: Primitives +title: extractCredentials +symbol: "@supabase/server/core.extractCredentials" +summary: Extracts authentication credentials from an incoming HTTP request. +description: |- + Extracts authentication credentials from an incoming HTTP request. + + Reads two headers: + - `Authorization: Bearer ` → extracted as `token` + - `apikey: ` → extracted as `apikey` + + This is a pure extraction step — no validation or verification is performed. + Pass the result to `verifyCredentials` to validate against allowed auth modes. +signature: "extractCredentials(request: Request): Credentials" +stability: stable +deprecated: false +parameters: + - name: request + location: argument + type: Request + required: true + description: The incoming HTTP request. +returns: + type: Credentials + description: The extracted `Credentials`. Fields are `null` when the corresponding header is absent. +throws: [] +examples: + - id: basic-usage + title: Basic usage + lang: ts + code: | + import { extractCredentials } from '@supabase/server/core' + + const creds = extractCredentials(request) + console.log(creds.token) // "eyJhbGci..." or null + console.log(creds.apikey) // "sb-abc123-publishable-..." or null +--- diff --git a/docs/reference-beta/definitions/core-resolve-env.md b/docs/reference-beta/definitions/core-resolve-env.md new file mode 100644 index 0000000..7b2b300 --- /dev/null +++ b/docs/reference-beta/definitions/core-resolve-env.md @@ -0,0 +1,39 @@ +--- +id: core-resolve-env +kind: method +category: Primitives +title: resolveEnv +symbol: "@supabase/server/core.resolveEnv" +summary: Resolves Supabase environment configuration from runtime environment variables. +description: |- + Resolves Supabase environment configuration from runtime environment variables. + + Reads `SUPABASE_URL`, keys (`SUPABASE_PUBLISHABLE_KEYS` / `SUPABASE_SECRET_KEYS`), + and the JWKS source (`SUPABASE_JWKS` for inline keys, `SUPABASE_JWKS_URL` + for a remote endpoint, or the well-known endpoint derived from + `SUPABASE_PUBLIC_URL` / the resolved `url`). Works across Deno, Node.js, + and Bun. For Cloudflare Workers, use `overrides` or enable node-compat. +signature: "resolveEnv(overrides?: Partial): { data: SupabaseEnv; error: null } | { data: null; error: EnvError }" +stability: stable +deprecated: false +parameters: + - name: overrides + location: argument + type: Partial + required: false + description: Partial values that take precedence over env vars. +returns: + type: "{ data: SupabaseEnv; error: null } | { data: null; error: EnvError }" + description: "`{ data: SupabaseEnv, error: null }` on success, `{ data: null, error: EnvError }` on failure." +throws: [] +examples: + - id: reading-and-overriding-env-vars + title: Reading and overriding env vars + lang: ts + code: | + const { data: env, error } = resolveEnv() + if (error) throw error + + // Override for tests + const { data: env } = resolveEnv({ url: 'http://localhost:54321' }) +--- diff --git a/docs/reference-beta/definitions/core-verify-auth-options.md b/docs/reference-beta/definitions/core-verify-auth-options.md new file mode 100644 index 0000000..3c17c5b --- /dev/null +++ b/docs/reference-beta/definitions/core-verify-auth-options.md @@ -0,0 +1,51 @@ +--- +id: core-verify-auth-options +kind: type +category: Primitives +title: VerifyAuthOptions +symbol: "@supabase/server/core.VerifyAuthOptions" +summary: Options for `verifyAuth`. +description: Options for `verifyAuth`. +signature: interface VerifyAuthOptions +stability: stable +deprecated: false +properties: + - name: auth + location: property + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Auth mode(s) to try. Modes are attempted in order — the first match wins. + + Default: `"user"` + - name: allow + location: property + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. Kept for backward + compatibility; will be removed in a future major release. When both are + provided, `auth` wins. + - name: audience + location: property + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: property + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: property + type: Partial + required: false + description: Optional environment overrides (passed through to `resolveEnv`). +examples: [] +--- diff --git a/docs/reference-beta/definitions/core-verify-auth.md b/docs/reference-beta/definitions/core-verify-auth.md new file mode 100644 index 0000000..7563d87 --- /dev/null +++ b/docs/reference-beta/definitions/core-verify-auth.md @@ -0,0 +1,89 @@ +--- +id: core-verify-auth +kind: method +category: Primitives +title: verifyAuth +symbol: "@supabase/server/core.verifyAuth" +summary: Extracts credentials from a request and verifies them in a single step. +description: |- + Extracts credentials from a request and verifies them in a single step. + + This is a convenience function that combines `extractCredentials` and + `verifyCredentials`. Use it when you want the full auth flow without + needing to inspect the raw credentials. +signature: "verifyAuth(request: Request, options: VerifyAuthOptions): Promise<{ data: AuthResult; error: null } | { data: null; error: AuthError }>" +stability: stable +deprecated: false +parameters: + - name: request + location: argument + type: Request + required: true + description: The incoming HTTP request. + - name: options + location: argument + type: VerifyAuthOptions + required: true + description: Auth modes to accept and optional environment overrides. + children: + - name: auth + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Auth mode(s) to try. Modes are attempted in order — the first match wins. + + Default: `"user"` + - name: allow + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. Kept for backward + compatibility; will be removed in a future major release. When both are + provided, `auth` wins. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: argument + type: Partial + required: false + description: Optional environment overrides (passed through to `resolveEnv`). +returns: + type: "Promise<{ data: AuthResult; error: null } | { data: null; error: AuthError }>" + description: |- + A result tuple: `{ data, error }`. + - On success: `{ data: AuthResult, error: null }` + - On failure: `{ data: null, error: AuthError }` +throws: [] +examples: + - id: user-auth + title: User auth + lang: ts + code: | + import { verifyAuth } from '@supabase/server/core' + + const { data: auth, error } = await verifyAuth(request, { + auth: 'user', + }) + + if (error) { + return Response.json({ message: error.message }, { status: error.status }) + } + + console.log(auth.userClaims!.id) // "d0f1a2b3-..." +--- diff --git a/docs/reference-beta/definitions/core-verify-credentials-options.md b/docs/reference-beta/definitions/core-verify-credentials-options.md new file mode 100644 index 0000000..03e56db --- /dev/null +++ b/docs/reference-beta/definitions/core-verify-credentials-options.md @@ -0,0 +1,51 @@ +--- +id: core-verify-credentials-options +kind: type +category: Primitives +title: VerifyCredentialsOptions +symbol: "@supabase/server/core.VerifyCredentialsOptions" +summary: Options for `verifyCredentials`. +description: Options for `verifyCredentials`. +signature: interface VerifyCredentialsOptions +stability: stable +deprecated: false +properties: + - name: auth + location: property + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Auth mode(s) to try. Modes are attempted in order — the first match wins. + + Default: `"user"` + - name: allow + location: property + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. Kept for + backward compatibility; will be removed in a future major release. When + both are provided, `auth` wins. + - name: audience + location: property + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: property + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: property + type: Partial + required: false + description: Optional environment overrides (passed through to `resolveEnv`). +examples: [] +--- diff --git a/docs/reference-beta/definitions/core-verify-credentials.md b/docs/reference-beta/definitions/core-verify-credentials.md new file mode 100644 index 0000000..3d2724e --- /dev/null +++ b/docs/reference-beta/definitions/core-verify-credentials.md @@ -0,0 +1,110 @@ +--- +id: core-verify-credentials +kind: method +category: Primitives +title: verifyCredentials +symbol: "@supabase/server/core.verifyCredentials" +summary: Verifies pre-extracted credentials against one or more allowed auth modes. +description: |- + Verifies pre-extracted credentials against one or more allowed auth modes. + + Tries each mode in order — first match wins. A mode is only tried when its + credential is present; a JWT that is present but fails verification + short-circuits the chain with `InvalidJwtError` instead of falling + through to the next mode. Use `verifyAuth` to extract and verify in a + single call. + + When every mode falls through, the returned error names the actual cause + rather than a generic failure — `MissingCredentialsError` when the + request carried nothing, `InvalidApiKeyError` when an `apikey` matched + no configured key, or a `500` (`JwksNotConfiguredError`, + `NoKeysConfiguredError`) when the server is configured such that no + request could ever have succeeded. Every error carries `hint`, `docs`, and + non-sensitive `details`. + + A misconfiguration `500` is only reported once nothing has matched, so an + allowed mode that does match the request's credentials still wins — e.g. + `['user', 'secret']` with no JWKS but a valid apikey authenticates as + `secret`. `sb_*` values in the Authorization slot are API keys, not user + tokens, and stay a caller error. +signature: "verifyCredentials(credentials: Credentials, options: VerifyCredentialsOptions): Promise<{ data: AuthResult; error: null } | { data: null; error: AuthError }>" +stability: stable +deprecated: false +parameters: + - name: credentials + location: argument + type: Credentials + required: true + description: The credentials to verify (from `extractCredentials`). + children: + - name: token + location: argument + type: string | null + required: true + description: "Bearer token from the `Authorization: Bearer ` header, or `null` if absent." + - name: apikey + location: argument + type: string | null + required: true + description: API key from the `apikey` header, or `null` if absent. + - name: options + location: argument + type: VerifyCredentialsOptions + required: true + description: Allowed auth modes and optional env overrides. + children: + - name: auth + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Auth mode(s) to try. Modes are attempted in order — the first match wins. + + Default: `"user"` + - name: allow + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. Kept for + backward compatibility; will be removed in a future major release. When + both are provided, `auth` wins. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: argument + type: Partial + required: false + description: Optional environment overrides (passed through to `resolveEnv`). +returns: + type: "Promise<{ data: AuthResult; error: null } | { data: null; error: AuthError }>" + description: "`{ data: AuthResult, error: null }` on success, `{ data: null, error: AuthError }` on failure." +throws: [] +examples: + - id: multiple-auth-modes + title: Multiple auth modes + lang: ts + code: | + const credentials = extractCredentials(request) + const { data: auth, error } = await verifyCredentials(credentials, { + auth: ['user', 'publishable'], + }) + if (error) { + console.error(error.code, error.message, error.hint) + return Response.json(error.toJSON(), { status: error.status }) + } +--- diff --git a/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client-config.md b/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client-config.md new file mode 100644 index 0000000..136bad4 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client-config.md @@ -0,0 +1,16 @@ +--- +id: middleware-admin-client-with-supabase-admin-client-config +kind: type +category: Middleware +title: WithSupabaseAdminClientConfig +symbol: "@supabase/server/middleware/admin-client.WithSupabaseAdminClientConfig" +summary: Configuration for `withSupabaseAdminClient` — the same environment and client options `createAdminClient` accepts, minus the per-request auth identity (which is read from the upstream context). +description: |- + Configuration for `withSupabaseAdminClient` — the same + environment and client options `createAdminClient` accepts, minus the + per-request auth identity (which is read from the upstream context). +signature: type WithSupabaseAdminClientConfig = Omit +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client.md b/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client.md new file mode 100644 index 0000000..9693594 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-admin-client-with-supabase-admin-client.md @@ -0,0 +1,48 @@ +--- +id: middleware-admin-client-with-supabase-admin-client +kind: method +category: Middleware +title: withSupabaseAdminClient +symbol: "@supabase/server/middleware/admin-client.withSupabaseAdminClient" +summary: Contributes `ctx.supabaseAdmin` — an admin Supabase client that bypasses Row-Level Security, authenticated with a secret key. This is the same middleware `withSupabase` composes internally to build its context. +description: |- + Contributes `ctx.supabaseAdmin` — an admin Supabase client that + bypasses Row-Level Security, authenticated with a secret key. This is the + same middleware `withSupabase` composes internally to build its context. + + The client is constructed on the first property access of + `ctx.supabaseAdmin` and memoized for the request. A handler that never + accesses it requires no secret key. +signature: "withSupabaseAdminClient(config?: WithSupabaseAdminClientConfig): Entry<{ supabaseAdmin: SupabaseClient }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithSupabaseAdminClientConfig + required: false + description: "" +returns: + type: "Entry<{ supabaseAdmin: SupabaseClient }>" + description: "" +throws: + - type: EnvError + description: |- + When `SUPABASE_URL` or the secret key is + missing — thrown at the first `ctx.supabaseAdmin` property access, inside + the handler or downstream middleware that performs it. +examples: + - id: standalone-pipeline + title: Standalone pipeline + lang: ts + code: | + import { pipeline } from '@supabase/middleware' + import { withSupabaseAdminClient } from '@supabase/server/middleware/admin-client' + + export default { + fetch: pipeline([withSupabaseAdminClient()], async (req, ctx) => { + await ctx.supabaseAdmin.from('audit_log').insert({ action: 'ping' }) + return Response.json({ ok: true }) + }), + } +--- diff --git a/docs/reference-beta/definitions/middleware-claims-with-claims-config.md b/docs/reference-beta/definitions/middleware-claims-with-claims-config.md new file mode 100644 index 0000000..8b318bd --- /dev/null +++ b/docs/reference-beta/definitions/middleware-claims-with-claims-config.md @@ -0,0 +1,61 @@ +--- +id: middleware-claims-with-claims-config +kind: type +category: Middleware +title: WithClaimsConfig +symbol: "@supabase/server/middleware/claims.WithClaimsConfig" +summary: Configuration for `withClaims`. +description: Configuration for `withClaims`. +signature: interface WithClaimsConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: jwks + location: property + type: JSONWebKeySet | URL + required: false + description: |- + JWKS source used to verify tokens: an inline key set or a remote JWKS + URL. Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` + (https endpoint) from the environment. + - name: audience + location: property + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s). When set, a token without `aud` is rejected, + and a token whose `aud` is an array passes when any entry is accepted. + - name: issuer + location: property + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s). When set, a token without `iss` is rejected. + Supabase Auth issues `https://.supabase.co/auth/v1`, which + `fromSupabaseUrl(url)` builds from a project URL. + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-claims-with-claims.md b/docs/reference-beta/definitions/middleware-claims-with-claims.md new file mode 100644 index 0000000..bf7e01f --- /dev/null +++ b/docs/reference-beta/definitions/middleware-claims-with-claims.md @@ -0,0 +1,111 @@ +--- +id: middleware-claims-with-claims +kind: method +category: Middleware +title: withClaims +symbol: "@supabase/server/middleware/claims.withClaims" +summary: Contributes `ctx.jwtClaims` by verifying the caller's Bearer token against the project JWKS — the same verification core `withSupabase` uses for its `user` auth mode. +description: |- + Contributes `ctx.jwtClaims` by verifying the caller's Bearer + token against the project JWKS — the same verification core `withSupabase` + uses for its `user` auth mode. + + Use this when composing a standalone `pipeline([...], handler)` that is + **not** wrapped by `withSupabase` — for example a Supabase-agnostic Edge + Function that still wants the caller's verified claims available to a + downstream middleware such as `withPostgresClient`. Inside `withSupabase`, the + context already carries `jwtClaims`, so `withClaims` is unnecessary. + + Behavior: + - No `Authorization: Bearer` token (or an `sb_*` API key in that position) + → contributes `null`; the request proceeds as anonymous. + - Token present but invalid → short-circuits with a 401 JSON response + (`{ message, code }`, matching `withSupabase`'s error shape). + - Token present but no JWKS configured → short-circuits with a 500 — + verification is not optional; there is no decode-only mode. + + `withClaims` is not an auth gate. It never rejects a request that has no + token. A pipeline like `[withClaims(), withSupabaseClient()]` accepts + anonymous callers and is not the composable form of + `withSupabase({ auth: 'user' })`, which rejects token-less requests with + a 401. To require an authenticated caller, compose `withRequiredClaims` + from `@supabase/server/middleware/required-claims` instead. The two entries + share the `jwtClaims` key, so a pipeline picks "claims if present" or + "claims required"; composing both is a compile-time conflict. +signature: "withClaims(config?: WithClaimsConfig): Entry<{ jwtClaims: JWTClaims | null }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithClaimsConfig + required: false + description: "" + children: + - name: jwks + location: argument + type: JSONWebKeySet | URL + required: false + description: |- + JWKS source used to verify tokens: an inline key set or a remote JWKS + URL. Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` + (https endpoint) from the environment. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s). When set, a token without `aud` is rejected, + and a token whose `aud` is an array passes when any entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s). When set, a token without `iss` is rejected. + Supabase Auth issues `https://.supabase.co/auth/v1`, which + `fromSupabaseUrl(url)` builds from a project URL. + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Entry<{ jwtClaims: JWTClaims | null }>" + description: "" +throws: [] +examples: + - id: standalone-pipeline + title: Standalone pipeline + lang: ts + code: | + import { pipeline } from '@supabase/middleware' + import { withClaims } from '@supabase/server/middleware/claims' + import { withPostgresClient } from '@supabase/server/middleware/postgres' + + export default { + fetch: pipeline([withClaims(), withPostgresClient()], async (req, ctx) => { + const rows = await ctx.postgres.query`select id, title from posts` + return Response.json({ rows, caller: ctx.jwtClaims?.sub ?? 'anon' }) + }), + } +--- diff --git a/docs/reference-beta/definitions/middleware-client-with-supabase-client-config.md b/docs/reference-beta/definitions/middleware-client-with-supabase-client-config.md new file mode 100644 index 0000000..50ec812 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-client-with-supabase-client-config.md @@ -0,0 +1,17 @@ +--- +id: middleware-client-with-supabase-client-config +kind: type +category: Middleware +title: WithSupabaseClientConfig +symbol: "@supabase/server/middleware/client.WithSupabaseClientConfig" +summary: Configuration for `withSupabaseClient` — the same environment and client options `createContextClient` accepts, minus the per-request auth identity (which is read from the request and the upstream context). +description: |- + Configuration for `withSupabaseClient` — the same + environment and client options `createContextClient` accepts, minus the + per-request auth identity (which is read from the request and the upstream + context). +signature: type WithSupabaseClientConfig = Omit +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-client-with-supabase-client.md b/docs/reference-beta/definitions/middleware-client-with-supabase-client.md new file mode 100644 index 0000000..9cbb37f --- /dev/null +++ b/docs/reference-beta/definitions/middleware-client-with-supabase-client.md @@ -0,0 +1,48 @@ +--- +id: middleware-client-with-supabase-client +kind: method +category: Middleware +title: withSupabaseClient +symbol: "@supabase/server/middleware/client.withSupabaseClient" +summary: Contributes `ctx.supabase` — a Supabase client scoped to the caller's identity, so Row-Level Security policies apply. This is the same middleware `withSupabase` composes internally to build its context. +description: |- + Contributes `ctx.supabase` — a Supabase client scoped to the + caller's identity, so Row-Level Security policies apply. This is the same + middleware `withSupabase` composes internally to build its context. + + Standalone, the caller's Bearer token (when present) is attached unverified — + PostgREST verifies it on every query. Compose `withClaims` + upstream when the pipeline itself needs verified claims. +signature: "withSupabaseClient(config?: WithSupabaseClientConfig): Entry<{ supabase: SupabaseClient }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithSupabaseClientConfig + required: false + description: "" +returns: + type: "Entry<{ supabase: SupabaseClient }>" + description: "" +throws: + - type: EnvError + description: |- + When `SUPABASE_URL` or the publishable key is + missing — composing wrappers (like `withSupabase`) map this to a 500 + response; standalone pipelines see it as a thrown error. +examples: + - id: standalone-pipeline + title: Standalone pipeline + lang: ts + code: | + import { pipeline } from '@supabase/middleware' + import { withSupabaseClient } from '@supabase/server/middleware/client' + + export default { + fetch: pipeline([withSupabaseClient()], async (req, ctx) => { + const { data } = await ctx.supabase.from('posts').select('id, title') + return Response.json(data) + }), + } +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client-config.md b/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client-config.md new file mode 100644 index 0000000..54bc43b --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client-config.md @@ -0,0 +1,78 @@ +--- +id: middleware-postgres-admin-with-postgres-admin-client-config +kind: type +category: Middleware +title: WithPostgresAdminClientConfig +symbol: "@supabase/server/middleware/postgres-admin.WithPostgresAdminClientConfig" +summary: Configuration for `withPostgresAdminClient`. +description: Configuration for `withPostgresAdminClient`. +signature: interface WithPostgresAdminClientConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: connectionString + location: property + type: string + required: false + description: Defaults to `getEnv('SUPABASE_DB_URL')` (from `@supabase/middleware`). + - name: pool + location: property + type: PostgresPoolOptions + required: false + description: |- + Pool size and checkout timeout for this connection string. Checked when + the middleware is built; an invalid value throws a `RangeError` then. + Entries whose options resolve to the same values share one pool. + children: + - name: max + location: property + type: number + required: false + description: |- + Connections this process opens at most on this connection string. A + positive integer. The pooler team recommends one to four for serverless + deployments. + + Default: ```ts + 4 + ``` + - name: checkoutTimeoutMs + location: property + type: number + required: false + description: |- + Milliseconds a query waits for a free connection before failing with + `POSTGRES_POOL_BUSY`, and how long a new connection may take to come up. + A positive number. Keep it well under the pooler's own 60 second checkout + timeout so the failure surfaces here, with a message that says what + happened. + + Default: ```ts + 10000 + ``` + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client.md b/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client.md new file mode 100644 index 0000000..156f877 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-admin-with-postgres-admin-client.md @@ -0,0 +1,123 @@ +--- +id: middleware-postgres-admin-with-postgres-admin-client +kind: method +category: Middleware +title: withPostgresAdminClient +symbol: "@supabase/server/middleware/postgres-admin.withPostgresAdminClient" +summary: Contributes `ctx.postgresAdmin` — a `pg` client that **bypasses RLS**, for full-table access. The direct-connection counterpart to `withSupabaseAdminClient`, and the deliberate opt-out from the guardrails `withPostgresClient` (`@supabase/server/middleware/postgres`) enforces. +description: |- + Contributes `ctx.postgresAdmin` — a `pg` client that **bypasses + RLS**, for full-table access. The direct-connection counterpart to + `withSupabaseAdminClient`, and the deliberate opt-out from the guardrails + `withPostgresClient` (`@supabase/server/middleware/postgres`) enforces. + + Queries run as-is, as the role in the connection string: no claim injection, + no role switching, no wrapping transaction. Whatever that role may read, the + caller may read. + + Unlike `withPostgresClient` this declares **no upstream prerequisite** — it + never looks at `ctx.jwtClaims`, so it composes in any auth mode, including + `auth: 'secret'` and `auth: 'none'`: + + ```ts + import { pipeline } from '@supabase/middleware' + import { withSupabase } from '@supabase/server' + import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin' + + pipeline([withSupabase({ auth: 'secret' }), withPostgresAdminClient()], handler) + ``` + + Compose both halves when a handler needs each in turn — they share one pool, + and `ctx.postgres` stays RLS-scoped regardless: + + ```ts + pipeline([withSupabase({ auth: 'user' }), withPostgresClient(), withPostgresAdminClient()], handler) + ``` + + > **Authorization is yours now.** RLS is not consulted, so any per-user + > scoping has to be a `where` clause you write. Reach for + > `withPostgresClient` unless you specifically need to cross user + > boundaries. + + > **Runtime note.** `pg` needs raw TCP, so this runs on Node/Deno (including + > the Supabase Edge runtime), **not** on Workers-style isolates. +signature: "withPostgresAdminClient(config?: WithPostgresAdminClientConfig): Entry<{ postgresAdmin: PostgresApi }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithPostgresAdminClientConfig + required: false + description: "" + children: + - name: connectionString + location: argument + type: string + required: false + description: Defaults to `getEnv('SUPABASE_DB_URL')` (from `@supabase/middleware`). + - name: pool + location: argument + type: PostgresPoolOptions + required: false + description: |- + Pool size and checkout timeout for this connection string. Checked when + the middleware is built; an invalid value throws a `RangeError` then. + Entries whose options resolve to the same values share one pool. + children: + - name: max + location: argument + type: number + required: false + description: |- + Connections this process opens at most on this connection string. A + positive integer. The pooler team recommends one to four for serverless + deployments. + + Default: ```ts + 4 + ``` + - name: checkoutTimeoutMs + location: argument + type: number + required: false + description: |- + Milliseconds a query waits for a free connection before failing with + `POSTGRES_POOL_BUSY`, and how long a new connection may take to come up. + A positive number. Keep it well under the pooler's own 60 second checkout + timeout so the failure surfaces here, with a message that says what + happened. + + Default: ```ts + 10000 + ``` + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Entry<{ postgresAdmin: PostgresApi }>" + description: "" +throws: [] +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-ident.md b/docs/reference-beta/definitions/middleware-postgres-ident.md new file mode 100644 index 0000000..d60d535 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-ident.md @@ -0,0 +1,49 @@ +--- +id: middleware-postgres-ident +kind: method +category: Middleware +title: ident +symbol: "@supabase/server/middleware/postgres.ident" +summary: Quote a Postgres identifier — a table, column, or role name — for safe interpolation into SQL text. +description: |- + Quote a Postgres identifier — a table, column, or role name — for safe + interpolation into SQL text. + + Bind parameters cover *values* and nothing else: `order by $1` sorts every + row by the constant string `$1`, and `select $1 from t` selects a literal, + not a column. Identifiers therefore have to reach the server as SQL text, + which is the one place string-building is unavoidable. This makes that step + safe by quoting the name and doubling any embedded quote, so the result is + always exactly one identifier no matter what it contains. + + **It is not an allowlist.** Quoting a caller-supplied name yields a valid + identifier, not a permitted one — `ident(req.query.sort)` cannot inject SQL + but can still read a column the caller was never meant to see. Check the + name against a fixed set you control first, then quote it. +signature: "ident(name: string): string" +stability: stable +deprecated: false +parameters: + - name: name + location: argument + type: string + required: true + description: The identifier to quote. +returns: + type: string + description: The name wrapped in double quotes, with embedded quotes doubled. +throws: + - description: |- + If `name` is empty or contains a NUL byte — neither can survive the + round trip, and Postgres reports both with errors that do not name the cause. +examples: + - id: example-1 + title: Example 1 + lang: ts + code: | + const SORTABLE = new Set(['created_at', 'title']) + if (!SORTABLE.has(column)) throw new Error('unsupported sort column') + const rows = await ctx.postgres.queryRaw( + `select id, title from posts order by ${ident(column)} desc`, + ) +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-postgres-api.md b/docs/reference-beta/definitions/middleware-postgres-postgres-api.md new file mode 100644 index 0000000..ced0b56 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-postgres-api.md @@ -0,0 +1,30 @@ +--- +id: middleware-postgres-postgres-api +kind: type +category: Middleware +title: PostgresApi +symbol: "@supabase/server/middleware/postgres.PostgresApi" +summary: The shape of `ctx.postgres` and `ctx.postgresAdmin`. +description: |- + The shape of `ctx.postgres` and `ctx.postgresAdmin`. + + Both halves expose the same surface — they differ in what runs around the + query, not in how you call it. `withPostgresClient` wraps every query in a + transaction that injects the caller's claims and drops to their role; + `withPostgresAdminClient` runs it as-is, as the connection-string role. +signature: interface PostgresApi +stability: stable +deprecated: false +properties: + - name: query + location: property + type: "(strings: TemplateStringsArray, ...values: unknown[]) => Promise" + required: true + description: "" + - name: queryRaw + location: property + type: "(text: string, params?: unknown[]) => Promise" + required: true + description: "" +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-postgres-pool-options.md b/docs/reference-beta/definitions/middleware-postgres-postgres-pool-options.md new file mode 100644 index 0000000..fb5694b --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-postgres-pool-options.md @@ -0,0 +1,43 @@ +--- +id: middleware-postgres-postgres-pool-options +kind: type +category: Middleware +title: PostgresPoolOptions +symbol: "@supabase/server/middleware/postgres.PostgresPoolOptions" +summary: Pool sizing for `withPostgresClient` and `withPostgresAdminClient`. Two entries on the same connection string share a pool only when their options resolve to the same values. +description: |- + Pool sizing for `withPostgresClient` and + `withPostgresAdminClient`. Two entries on the same connection string share + a pool only when their options resolve to the same values. +signature: interface PostgresPoolOptions +stability: stable +deprecated: false +properties: + - name: max + location: property + type: number + required: false + description: |- + Connections this process opens at most on this connection string. A + positive integer. The pooler team recommends one to four for serverless + deployments. + + Default: ```ts + 4 + ``` + - name: checkoutTimeoutMs + location: property + type: number + required: false + description: |- + Milliseconds a query waits for a free connection before failing with + `POSTGRES_POOL_BUSY`, and how long a new connection may take to come up. + A positive number. Keep it well under the pooler's own 60 second checkout + timeout so the failure surfaces here, with a message that says what + happened. + + Default: ```ts + 10000 + ``` +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-request-claims.md b/docs/reference-beta/definitions/middleware-postgres-request-claims.md new file mode 100644 index 0000000..1acae7e --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-request-claims.md @@ -0,0 +1,25 @@ +--- +id: middleware-postgres-request-claims +kind: type +category: Middleware +title: RequestClaims +symbol: "@supabase/server/middleware/postgres.RequestClaims" +summary: Minimal claims shape `withPostgresClient` needs on the upstream context. +description: |- + Minimal claims shape `withPostgresClient` needs on the + upstream context. + + Satisfied both by `withSupabase`'s JWKS-verified `ctx.jwtClaims` and by the + standalone `withClaims` middleware — `withPostgresClient` only reads `role` + and serializes the whole object into `request.jwt.claims`. +signature: interface RequestClaims +stability: stable +deprecated: false +properties: + - name: role + location: property + type: string + required: false + description: "" +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-with-postgres-client-config.md b/docs/reference-beta/definitions/middleware-postgres-with-postgres-client-config.md new file mode 100644 index 0000000..76ad2d6 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-with-postgres-client-config.md @@ -0,0 +1,78 @@ +--- +id: middleware-postgres-with-postgres-client-config +kind: type +category: Middleware +title: WithPostgresClientConfig +symbol: "@supabase/server/middleware/postgres.WithPostgresClientConfig" +summary: Configuration for `withPostgresClient`. +description: Configuration for `withPostgresClient`. +signature: interface WithPostgresClientConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: connectionString + location: property + type: string + required: false + description: Defaults to `getEnv('SUPABASE_DB_URL')` (from `@supabase/middleware`). + - name: pool + location: property + type: PostgresPoolOptions + required: false + description: |- + Pool size and checkout timeout for this connection string. Checked when + the middleware is built; an invalid value throws a `RangeError` then. + Entries whose options resolve to the same values share one pool. + children: + - name: max + location: property + type: number + required: false + description: |- + Connections this process opens at most on this connection string. A + positive integer. The pooler team recommends one to four for serverless + deployments. + + Default: ```ts + 4 + ``` + - name: checkoutTimeoutMs + location: property + type: number + required: false + description: |- + Milliseconds a query waits for a free connection before failing with + `POSTGRES_POOL_BUSY`, and how long a new connection may take to come up. + A positive number. Keep it well under the pooler's own 60 second checkout + timeout so the failure surfaces here, with a message that says what + happened. + + Default: ```ts + 10000 + ``` + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-postgres-with-postgres-client.md b/docs/reference-beta/definitions/middleware-postgres-with-postgres-client.md new file mode 100644 index 0000000..8c2dfe6 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-postgres-with-postgres-client.md @@ -0,0 +1,136 @@ +--- +id: middleware-postgres-with-postgres-client +kind: method +category: Middleware +title: withPostgresClient +symbol: "@supabase/server/middleware/postgres.withPostgresClient" +summary: Contributes `ctx.postgres` — an RLS-scoped `pg` client, the safe version of "authenticate, then query as the user". This is the direct-connection counterpart to `withSupabaseClient`, and its service-role companion is `withPostgresAdminClient` (`@supabase/server/middleware/postgres-admin`). +description: |- + Contributes `ctx.postgres` — an RLS-scoped `pg` client, the safe + version of "authenticate, then query as the user". This is the + direct-connection counterpart to `withSupabaseClient`, and its service-role + companion is `withPostgresAdminClient` + (`@supabase/server/middleware/postgres-admin`). + + Every query runs in its own short transaction that injects the caller's + claims and drops to their role, exactly like PostgREST: + + ```sql + begin; + select set_config('request.jwt.claims', $claims, true); -- auth.uid() resolves + set local role "authenticated"; -- RLS now enforces + + commit; + ``` + + Everything is transaction-local, so nothing leaks onto the pooled connection. + + Only `authenticated` and `anon` are assumed. A token naming any other role — + including `service_role` — is **refused** with a 500 and + `code: 'UNSUPPORTED_ROLE'`, never silently downgraded to `anon`: running the + query as the wrong identity would return zero rows and leave nothing to + debug. Bypassing RLS is a separate, explicit opt-in: compose + `withPostgresAdminClient`. + + > **Custom roles.** Supabase supports custom Postgres roles via the `role` + > claim, and RLS still applies to them. They are not supported here yet, so + > such a token is refused rather than downgraded. + + Reads the caller's claims from `ctx.jwtClaims`, which `withSupabase` + populates (JWKS-verified) — so after `withSupabase` in a pipeline it composes + directly: + + ```ts + pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], handler) + ``` + + Standalone (no `withSupabase`), pair it with `withClaims` so `ctx.jwtClaims` + is present before it runs. + + > **Table grants.** Queries run as `authenticated` or `anon`, so those + > roles need explicit table privileges (e.g. `grant select, insert on + > to authenticated`) in addition to RLS policies. A missing grant + > fails with `permission denied` (SQLSTATE 42501) before RLS is consulted. + + > **Runtime note.** `pg` needs raw TCP, so this runs on Node/Deno (including + > the Supabase Edge runtime), **not** on Workers-style isolates. +signature: "withPostgresClient(config?: WithPostgresClientConfig): Entry<{ postgres: PostgresApi }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithPostgresClientConfig + required: false + description: "" + children: + - name: connectionString + location: argument + type: string + required: false + description: Defaults to `getEnv('SUPABASE_DB_URL')` (from `@supabase/middleware`). + - name: pool + location: argument + type: PostgresPoolOptions + required: false + description: |- + Pool size and checkout timeout for this connection string. Checked when + the middleware is built; an invalid value throws a `RangeError` then. + Entries whose options resolve to the same values share one pool. + children: + - name: max + location: argument + type: number + required: false + description: |- + Connections this process opens at most on this connection string. A + positive integer. The pooler team recommends one to four for serverless + deployments. + + Default: ```ts + 4 + ``` + - name: checkoutTimeoutMs + location: argument + type: number + required: false + description: |- + Milliseconds a query waits for a free connection before failing with + `POSTGRES_POOL_BUSY`, and how long a new connection may take to come up. + A positive number. Keep it well under the pooler's own 60 second checkout + timeout so the failure surfaces here, with a message that says what + happened. + + Default: ```ts + 10000 + ``` + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Entry<{ postgres: PostgresApi }>" + description: "" +throws: [] +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-required-claims-with-required-claims-config.md b/docs/reference-beta/definitions/middleware-required-claims-with-required-claims-config.md new file mode 100644 index 0000000..cdfddfc --- /dev/null +++ b/docs/reference-beta/definitions/middleware-required-claims-with-required-claims-config.md @@ -0,0 +1,61 @@ +--- +id: middleware-required-claims-with-required-claims-config +kind: type +category: Middleware +title: WithRequiredClaimsConfig +symbol: "@supabase/server/middleware/required-claims.WithRequiredClaimsConfig" +summary: Configuration for `withRequiredClaims`. +description: Configuration for `withRequiredClaims`. +signature: interface WithRequiredClaimsConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: jwks + location: property + type: JSONWebKeySet | URL + required: false + description: |- + JWKS source used to verify tokens: an inline key set or a remote JWKS + URL. Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` + (https endpoint) from the environment. + - name: audience + location: property + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s). When set, a token without `aud` is rejected, + and a token whose `aud` is an array passes when any entry is accepted. + - name: issuer + location: property + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s). When set, a token without `iss` is rejected. + Supabase Auth issues `https://.supabase.co/auth/v1`, which + `fromSupabaseUrl(url)` builds from a project URL. + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/middleware-required-claims-with-required-claims.md b/docs/reference-beta/definitions/middleware-required-claims-with-required-claims.md new file mode 100644 index 0000000..e9f5ea5 --- /dev/null +++ b/docs/reference-beta/definitions/middleware-required-claims-with-required-claims.md @@ -0,0 +1,120 @@ +--- +id: middleware-required-claims-with-required-claims +kind: method +category: Middleware +title: withRequiredClaims +symbol: "@supabase/server/middleware/required-claims.withRequiredClaims" +summary: "The user-mode auth gate: requires a valid user JWT and contributes **non-null** `ctx.jwtClaims`. Verification runs against the project JWKS, the same core `withSupabase` uses for its `user` auth mode." +description: |- + The user-mode auth gate: requires a valid user JWT and + contributes **non-null** `ctx.jwtClaims`. Verification runs against the + project JWKS, the same core `withSupabase` uses for its `user` auth mode. + + This is the required-caller counterpart to `withClaims`, which contributes + claims when a token is present and lets token-less requests proceed as + anonymous. A pipeline picks one or the other, "claims required" or "claims + if present"; composing both is a compile-time conflict on the `jwtClaims` + key. + + Behavior — every short-circuit uses the standard error payload, with the same + code `withSupabase({ auth: 'user' })` returns for an identical request: + - No `Authorization: Bearer` token → 401 `MISSING_CREDENTIALS`. The handler + never runs. + - An `sb_*` API key in that position → 401 `UNUSABLE_CREDENTIAL`: a + credential arrived, just not a user JWT. + - Token present but invalid → 401 `INVALID_JWT`, naming the specific reason. + - Token present but no JWKS configured → 500 `JWKS_NOT_CONFIGURED`; + verification is not optional and there is no decode-only mode. + + Because the contribution is non-null, gated handlers read `ctx.jwtClaims` + directly, with no `?.sub ?? 'anon'` fallbacks. Downstream entries declaring + a `jwtClaims` prerequisite, such as `withPostgresClient`, compose with no + further verification. + + The 401 and 500 short-circuits carry no CORS headers, and a bare pipeline + answers no `OPTIONS` preflight. For browser callers, compose `withCors` + (`@supabase/middleware/cors`) ahead of the gate: it answers preflight before + the gate runs and stamps `Access-Control-*` headers on the short-circuit + responses. + + After `withSupabase` in a pipeline the context already carries verified + `jwtClaims`, so this gate is unnecessary there and placing it after + `withSupabase` is a compile-time conflict. Use `withSupabase({ auth: 'user' })` + to gate that path. +signature: "withRequiredClaims(config?: WithRequiredClaimsConfig): Entry<{ jwtClaims: JWTClaims }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithRequiredClaimsConfig + required: false + description: "" + children: + - name: jwks + location: argument + type: JSONWebKeySet | URL + required: false + description: |- + JWKS source used to verify tokens: an inline key set or a remote JWKS + URL. Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` + (https endpoint) from the environment. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s). When set, a token without `aud` is rejected, + and a token whose `aud` is an array passes when any entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s). When set, a token without `iss` is rejected. + Supabase Auth issues `https://.supabase.co/auth/v1`, which + `fromSupabaseUrl(url)` builds from a project URL. + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Entry<{ jwtClaims: JWTClaims }>" + description: "" +throws: [] +examples: + - id: gated-standalone-pipeline + title: Gated standalone pipeline + lang: ts + code: | + import { pipeline } from '@supabase/middleware' + import { withRequiredClaims } from '@supabase/server/middleware/required-claims' + import { withPostgresClient } from '@supabase/server/middleware/postgres' + + export default { + fetch: pipeline([withRequiredClaims(), withPostgresClient()], async (req, ctx) => { + const rows = await ctx.postgres.query`select id, title from posts` + return Response.json({ rows, caller: ctx.jwtClaims.sub }) + }), + } +--- diff --git a/docs/reference-beta/definitions/server-allow-with-key.md b/docs/reference-beta/definitions/server-allow-with-key.md new file mode 100644 index 0000000..28b9c3c --- /dev/null +++ b/docs/reference-beta/definitions/server-allow-with-key.md @@ -0,0 +1,15 @@ +--- +id: server-allow-with-key +kind: type +category: Types +title: AllowWithKey +symbol: "@supabase/server.AllowWithKey" +summary: "" +description: "" +signature: type AllowWithKey = AuthModeWithKey +stability: stable +deprecated: true +examples: [] +--- + +> **Deprecated:** Use `AuthModeWithKey` instead. Will be removed in a future major release. diff --git a/docs/reference-beta/definitions/server-allow.md b/docs/reference-beta/definitions/server-allow.md new file mode 100644 index 0000000..3b099e5 --- /dev/null +++ b/docs/reference-beta/definitions/server-allow.md @@ -0,0 +1,15 @@ +--- +id: server-allow +kind: type +category: Types +title: Allow +symbol: "@supabase/server.Allow" +summary: "" +description: "" +signature: type Allow = AuthMode +stability: stable +deprecated: true +examples: [] +--- + +> **Deprecated:** Use `AuthMode` instead. Will be removed in a future major release. diff --git a/docs/reference-beta/definitions/server-api-key-format.md b/docs/reference-beta/definitions/server-api-key-format.md new file mode 100644 index 0000000..6402533 --- /dev/null +++ b/docs/reference-beta/definitions/server-api-key-format.md @@ -0,0 +1,15 @@ +--- +id: server-api-key-format +kind: type +category: Errors +title: ApiKeyFormat +symbol: "@supabase/server.ApiKeyFormat" +summary: How an `apikey` header value was classified by its public prefix. Used in diagnostics so a format mismatch can be reported without echoing the key. +description: |- + How an `apikey` header value was classified by its public prefix. Used in + diagnostics so a format mismatch can be reported without echoing the key. +signature: type ApiKeyFormat = "absent" | "publishable" | "secret" | "legacy-jwt" | "unrecognized" +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-auth-config.md b/docs/reference-beta/definitions/server-auth-config.md new file mode 100644 index 0000000..24d0d02 --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-config.md @@ -0,0 +1,34 @@ +--- +id: server-auth-config +kind: type +category: Types +title: AuthConfig +symbol: "@supabase/server.AuthConfig" +summary: "Accepted shape of the `auth` option: one mode, or an ordered list of modes tried left to right." +description: |- + Accepted shape of the `auth` option: one mode, or an ordered list of modes + tried left to right. + + `"none"` accepts every request, so it only carries meaning as the last + entry of a list — the modes before it are the ones that can produce an + identity, and anything after it is unreachable. On its own in a list + (`["none"]`) it says nothing that a bare `auth: 'none'` doesn't. So the + type accepts `"none"` alone or in final position behind at least one + credentialed mode, and nowhere else. + + A single mode needs no wrapping array — `"user"` and `["user"]` are the + same configuration, and the unwrapped form is the one the union names + first, so it is what shows up in editor completions. +signature: type AuthConfig = "none" | CredentialedAuthMode | [CredentialedAuthMode, ...CredentialedAuthMode[]] | [CredentialedAuthMode, ...CredentialedAuthMode[], "none"] +stability: stable +deprecated: false +examples: + - id: every-accepted-form + title: Every accepted form + lang: ts + code: | + withSupabase({ auth: 'user' }, handler) // one mode + withSupabase({ auth: ['secret', 'user'] }, handler) // first match wins + withSupabase({ auth: ['user', 'none'] }, handler) // optional user + withSupabase({ auth: 'none' }, handler) // no credentials required +--- diff --git a/docs/reference-beta/definitions/server-auth-error.md b/docs/reference-beta/definitions/server-auth-error.md new file mode 100644 index 0000000..1f4d8b4 --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-error.md @@ -0,0 +1,119 @@ +--- +id: server-auth-error +kind: class +category: Errors +title: AuthError +symbol: "@supabase/server.AuthError" +summary: Thrown when authentication or authorization fails. +description: |- + Thrown when authentication or authorization fails. + + Carries an HTTP `status` code suitable for returning directly in a response + (`401` when the request's credentials are at fault, `500` when the server is + misconfigured and could not have authenticated anyone). +signature: class AuthError extends SupabaseServerError +stability: stable +deprecated: false +parameters: + - name: message + location: argument + type: string + required: true + description: Human-readable description. Prefixed with `[@supabase/server]`. + - name: code + location: argument + type: string + required: false + description: Machine-readable code. + - name: status + location: argument + type: number + required: false + description: HTTP status. Defaults to `401`. + - name: options + location: argument + type: SupabaseServerErrorOptions + required: false + description: Optional `hint`, `details`, `docs`, and `cause`. + children: + - name: hint + location: argument + type: string + required: false + description: Actionable next step for whoever has to fix this. + - name: details + location: argument + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics. Never contains key values, token + payloads, or any other secret material. + - name: docs + location: argument + type: string + required: false + description: Override the generated documentation URL. + - name: cause + location: argument + type: unknown + required: false + description: Underlying error, when this one wraps another. +properties: + - name: source + location: property + type: '"@supabase/server"' + required: true + description: Always `"@supabase/server"`. + - name: code + location: property + type: string + required: true + description: Machine-readable error code. + - name: hint + location: property + type: string + required: false + description: Actionable next step, when one applies. + - name: docs + location: property + type: string + required: true + description: Documentation URL for this error's `code`. + - name: details + location: property + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics — accepted auth modes, which + credential headers were present, configured key *names*, JWT header + fields. Never key values or token payloads. + - name: toJSON + location: property + type: () => ErrorPayload + required: true + description: "" + - name: status + location: property + type: number + required: true + description: |- + HTTP status code. + + - `401` — The request's credentials are at fault (`MissingCredentialsError`, + `InvalidApiKeyError`, `InvalidJwtError`). + - `500` — The server is misconfigured (`JwksNotConfiguredError`, + `NoKeysConfiguredError`, `JwksFetchFailedError`, + `CreateSupabaseClientError`). +examples: + - id: catching-an-auth-error + title: Catching an AuthError + lang: ts + code: | + import { createSupabaseContext } from '@supabase/server' + + const { data: ctx, error } = await createSupabaseContext(request, { auth: 'user' }) + if (error) { + // error is an AuthError — `toJSON()` includes source, code, message, hint, docs, details + return Response.json(error.toJSON(), { status: error.status }) + } +--- diff --git a/docs/reference-beta/definitions/server-auth-failure-context.md b/docs/reference-beta/definitions/server-auth-failure-context.md new file mode 100644 index 0000000..309dadf --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-failure-context.md @@ -0,0 +1,76 @@ +--- +id: server-auth-failure-context +kind: type +category: Errors +title: AuthFailureContext +symbol: "@supabase/server.AuthFailureContext" +summary: Everything the auth pipeline knows about a failed attempt, minus anything secret. Used to build messages, hints, and `details`. +description: |- + Everything the auth pipeline knows about a failed attempt, minus anything + secret. Used to build messages, hints, and `details`. +signature: interface AuthFailureContext +stability: stable +deprecated: false +properties: + - name: authModes + location: property + type: readonly string[] + required: true + description: Auth modes that were attempted, in the order they were tried. + - name: received + location: property + type: ReceivedCredentials + required: true + description: Which credential headers the request carried. + children: + - name: authorization + location: property + type: '"absent" | "bearer" | "api-key" | "non-bearer-scheme"' + required: true + description: |- + What the `Authorization` header carried. + + - `'bearer'` — a bearer token that looks like a JWT + - `'api-key'` — an `sb_*` API key, which the Supabase SDK forwards here + alongside the `apikey` header; not a user token + - `'non-bearer-scheme'` — present but unusable (wrong scheme, wrong + casing, bare value, empty token) + - `'absent'` — no header + - name: apikey + location: property + type: ApiKeyFormat + required: true + description: The `apikey` header classified by prefix. Never the value itself. + - name: configuredKeyNames + location: property + type: Record + required: false + description: |- + Names (never values) of the keys configured for the attempted modes. + Omitted for modes that don't use API keys. + - name: matchedKey + location: property + type: '{ kind: "publishable" | "secret"; name: string; mode: string }' + required: false + description: |- + Set when the rejected `apikey` is a configured key of `kind` held under + `name`, and `mode` is the attempted mode that accepts a different name. + Carries the name only, never the value. + children: + - name: kind + location: property + type: '"publishable" | "secret"' + required: true + description: "" + - name: name + location: property + type: string + required: true + description: "" + - name: mode + location: property + type: string + required: true + description: "" +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-auth-generic-error.md b/docs/reference-beta/definitions/server-auth-generic-error.md new file mode 100644 index 0000000..a55e349 --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-generic-error.md @@ -0,0 +1,13 @@ +--- +id: server-auth-generic-error +kind: constant +category: Errors +title: AuthGenericError +symbol: "@supabase/server.AuthGenericError" +summary: Generic authentication error code. +description: Generic authentication error code. +signature: 'const AuthGenericError: "AUTH_ERROR"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-auth-mode-with-key.md b/docs/reference-beta/definitions/server-auth-mode-with-key.md new file mode 100644 index 0000000..d440cbb --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-mode-with-key.md @@ -0,0 +1,31 @@ +--- +id: server-auth-mode-with-key +kind: type +category: Types +title: AuthModeWithKey +symbol: "@supabase/server.AuthModeWithKey" +summary: Extended auth mode that supports targeting a specific named key. +description: |- + Extended auth mode that supports targeting a specific named key. + + Use the colon syntax (`"publishable:web_app"`) to require a specific named key + from the `SUPABASE_PUBLISHABLE_KEYS` or `SUPABASE_SECRET_KEYS` JSON object. + Use `"publishable:*"` or `"secret:*"` to accept any key in the set. The bare + form without a colon (`"publishable"` / `"secret"`) matches only the `default` key. +signature: type AuthModeWithKey = AuthMode | `publishable:${string}` | `secret:${string}` +stability: stable +deprecated: false +examples: + - id: named-key + title: Named key + lang: ts + code: | + // Accept only the "mobile" publishable key + withSupabase({ auth: 'publishable:mobile' }, handler) + + // Accept any secret key + withSupabase({ auth: 'secret:*' }, handler) + + // Mix named keys with other modes + withSupabase({ auth: ['user', 'publishable:web_app'] }, handler) +--- diff --git a/docs/reference-beta/definitions/server-auth-mode.md b/docs/reference-beta/definitions/server-auth-mode.md new file mode 100644 index 0000000..a5b2750 --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-mode.md @@ -0,0 +1,35 @@ +--- +id: server-auth-mode +kind: type +category: Types +title: AuthMode +symbol: "@supabase/server.AuthMode" +summary: Authentication mode that determines what credentials a request must provide. +description: |- + Authentication mode that determines what credentials a request must provide. + + - `"none"` — No credentials required. Every request is accepted. + - `"publishable"` — Requires a valid publishable key in the `apikey` header. Matches only the `default` key. + - `"secret"` — Requires a valid secret key in the `apikey` header (timing-safe comparison). Matches only the `default` key. + - `"user"` — Requires a valid JWT in the `Authorization: Bearer ` header. + + Bare `"publishable"` / `"secret"` resolve the `default` key from + `SUPABASE_PUBLISHABLE_KEYS` / `SUPABASE_SECRET_KEYS`. To target another key or + accept any key, see `AuthModeWithKey`. +signature: type AuthMode = "none" | "publishable" | "secret" | "user" +stability: stable +deprecated: false +examples: + - id: single-mode + title: Single mode + lang: ts + code: | + // Single mode + withSupabase({ auth: 'user' }, handler) + + // Multiple modes — the first match wins. + // A mode is tried only when its credential is present; a JWT that is + // present but fails verification rejects immediately rather than falling + // through to the next mode. + withSupabase({ auth: ['user', 'publishable'] }, handler) +--- diff --git a/docs/reference-beta/definitions/server-auth-result.md b/docs/reference-beta/definitions/server-auth-result.md new file mode 100644 index 0000000..bbb4be8 --- /dev/null +++ b/docs/reference-beta/definitions/server-auth-result.md @@ -0,0 +1,43 @@ +--- +id: server-auth-result +kind: type +category: Types +title: AuthResult +symbol: "@supabase/server.AuthResult" +summary: Result of credential verification. +description: |- + Result of credential verification. + + Contains the resolved auth mode, the verified token (for `"user"` mode), + decoded JWT claims, and the matched key name (for `"publishable"` / `"secret"` modes). +signature: interface AuthResult +stability: stable +deprecated: false +properties: + - name: authMode + location: property + type: AuthMode + required: true + description: The auth mode that was successfully matched. + - name: token + location: property + type: string | null + required: true + description: The verified JWT, or `null` for non-user auth modes. + - name: userClaims + location: property + type: UserClaims | null + required: true + description: Normalized user identity derived from the JWT, or `null` when no JWT is present. + - name: jwtClaims + location: property + type: JWTClaims | null + required: true + description: Raw JWT payload, or `null` when no JWT is present. + - name: keyName + location: property + type: string | null + required: false + description: Name of the matched key (e.g. `"default"`, `"mobile"`), or `null` for `"user"` / `"none"` modes. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-client-auth.md b/docs/reference-beta/definitions/server-client-auth.md new file mode 100644 index 0000000..e703a43 --- /dev/null +++ b/docs/reference-beta/definitions/server-client-auth.md @@ -0,0 +1,24 @@ +--- +id: server-client-auth +kind: type +category: Types +title: ClientAuth +symbol: "@supabase/server.ClientAuth" +summary: Auth identity for client creation functions. +description: Auth identity for client creation functions. +signature: interface ClientAuth +stability: stable +deprecated: false +properties: + - name: token + location: property + type: string | null + required: false + description: The caller's JWT, or `null` for anonymous access. + - name: keyName + location: property + type: string | null + required: false + description: Name of the API key to use. Falls back to `"default"`, then first available. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-create-admin-client-options.md b/docs/reference-beta/definitions/server-create-admin-client-options.md new file mode 100644 index 0000000..47fa204 --- /dev/null +++ b/docs/reference-beta/definitions/server-create-admin-client-options.md @@ -0,0 +1,29 @@ +--- +id: server-create-admin-client-options +kind: type +category: Types +title: CreateAdminClientOptions +symbol: "@supabase/server.CreateAdminClientOptions" +summary: Options for `createAdminClient`. +description: Options for `createAdminClient`. +signature: interface CreateAdminClientOptions +stability: stable +deprecated: false +properties: + - name: auth + location: property + type: Pick + required: false + description: Auth identity — key name from the verified request. + - name: env + location: property + type: Partial + required: false + description: Override auto-detected environment variables. + - name: supabaseOptions + location: property + type: SupabaseClientOptions + required: false + description: Options forwarded to `createClient()`. `accessToken` is stripped; auth settings are force-overwritten. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-create-context-client-options.md b/docs/reference-beta/definitions/server-create-context-client-options.md new file mode 100644 index 0000000..1c1191d --- /dev/null +++ b/docs/reference-beta/definitions/server-create-context-client-options.md @@ -0,0 +1,40 @@ +--- +id: server-create-context-client-options +kind: type +category: Types +title: CreateContextClientOptions +symbol: "@supabase/server.CreateContextClientOptions" +summary: Options for `createContextClient`. +description: Options for `createContextClient`. +signature: interface CreateContextClientOptions +stability: stable +deprecated: false +properties: + - name: auth + location: property + type: ClientAuth + required: false + description: Auth identity — token and key name from the verified request. + children: + - name: token + location: property + type: string | null + required: false + description: The caller's JWT, or `null` for anonymous access. + - name: keyName + location: property + type: string | null + required: false + description: Name of the API key to use. Falls back to `"default"`, then first available. + - name: env + location: property + type: Partial + required: false + description: Override auto-detected environment variables. + - name: supabaseOptions + location: property + type: SupabaseClientOptions + required: false + description: Options forwarded to `createClient()`. `accessToken` is stripped; auth settings are force-overwritten. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-create-supabase-client-error.md b/docs/reference-beta/definitions/server-create-supabase-client-error.md new file mode 100644 index 0000000..344fef3 --- /dev/null +++ b/docs/reference-beta/definitions/server-create-supabase-client-error.md @@ -0,0 +1,13 @@ +--- +id: server-create-supabase-client-error +kind: constant +category: Errors +title: CreateSupabaseClientError +symbol: "@supabase/server.CreateSupabaseClientError" +summary: Failed to create a Supabase client after auth succeeded. +description: Failed to create a Supabase client after auth succeeded. +signature: 'const CreateSupabaseClientError: "CREATE_SUPABASE_CLIENT_ERROR"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-create-supabase-context.md b/docs/reference-beta/definitions/server-create-supabase-context.md new file mode 100644 index 0000000..63c25d9 --- /dev/null +++ b/docs/reference-beta/definitions/server-create-supabase-context.md @@ -0,0 +1,138 @@ +--- +id: server-create-supabase-context +kind: method +category: Middleware +title: createSupabaseContext +symbol: "@supabase/server.createSupabaseContext" +summary: Creates a `SupabaseContext` directly from a request. +description: |- + Creates a `SupabaseContext` directly from a request. + + Use this when you need the context without the full `withSupabase` wrapper — + e.g., inside framework route handlers or custom middleware. Returns a result tuple + instead of producing a `Response`. +signature: "createSupabaseContext(request: Request, options?: WithSupabaseConfig): Promise<{ data: SupabaseContext; error: null } | { data: null; error: AuthError }>" +stability: stable +deprecated: false +parameters: + - name: request + location: argument + type: Request + required: true + description: The incoming HTTP request. + - name: options + location: argument + type: WithSupabaseConfig + required: false + description: Auth modes, environment overrides. The `cors` option is ignored here. + children: + - name: auth + location: argument + type: AuthConfig + required: false + description: |- + Auth mode(s) to accept. Modes are tried in order — the first match wins. + A mode falls through only when its credential is absent; a present-but-invalid + JWT short-circuits the chain with `InvalidJwtError` (`INVALID_JWT`). + + `"none"` matches unconditionally, so it belongs last in a list or on its + own — see `AuthConfig`. + + Default: `"user"` + - name: allow + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. The `allow` option + is kept for backward compatibility and will be removed in a future major release. + When both `auth` and `allow` are provided, `auth` takes precedence. It keeps + the older, looser element type so code mid-migration still compiles; `auth` + is where the `AuthConfig` ordering rule is enforced. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: argument + type: Partial + required: false + description: |- + Override auto-detected environment variables. Useful for testing + or when running in environments without standard env var support. + - name: cors + location: argument + type: 'boolean | Record | "default" | "disabled" | { headers: Record }' + required: false + description: |- + CORS configuration for the `withSupabase` wrapper. + + - `'default'` — uses `@supabase/supabase-js` default CORS headers. + - `'disabled'` — disables CORS handling entirely. + - `{ headers }` — custom CORS headers. + + The boolean (`true`/`false`) and bare `Record` forms are + deprecated but still accepted for backward compatibility. + + Default: `'default'` + - name: supabaseOptions + location: argument + type: SupabaseClientOptions + required: false + description: |- + Options forwarded to both internal `createClient()` calls. + + `accessToken` is stripped, and auth settings (`persistSession`, `autoRefreshToken`, + `detectSessionInUrl`) are force-overwritten to server-safe values. + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in the response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Promise<{ data: SupabaseContext; error: null } | { data: null; error: AuthError }>" + description: "`{ data: SupabaseContext, error: null }` on success, `{ data: null, error: AuthError }` on failure." +throws: [] +examples: + - id: user-auth + title: User auth + lang: ts + code: | + const { data: ctx, error } = await createSupabaseContext(request, { auth: 'user' }) + if (error) { + // `toJSON()` yields { source, code, message, hint, docs, details } + return Response.json(error.toJSON(), { status: error.status }) + } + const { data } = await ctx.supabase.rpc('get_my_items') +--- diff --git a/docs/reference-beta/definitions/server-credentialed-auth-mode.md b/docs/reference-beta/definitions/server-credentialed-auth-mode.md new file mode 100644 index 0000000..2bfc76b --- /dev/null +++ b/docs/reference-beta/definitions/server-credentialed-auth-mode.md @@ -0,0 +1,15 @@ +--- +id: server-credentialed-auth-mode +kind: type +category: Types +title: CredentialedAuthMode +symbol: "@supabase/server.CredentialedAuthMode" +summary: An auth mode that requires a credential — every `AuthModeWithKey` except `"none"`, keyed forms included. +description: |- + An auth mode that requires a credential — every `AuthModeWithKey` + except `"none"`, keyed forms included. +signature: type CredentialedAuthMode = Exclude +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-credentials.md b/docs/reference-beta/definitions/server-credentials.md new file mode 100644 index 0000000..a01d07b --- /dev/null +++ b/docs/reference-beta/definitions/server-credentials.md @@ -0,0 +1,27 @@ +--- +id: server-credentials +kind: type +category: Types +title: Credentials +symbol: "@supabase/server.Credentials" +summary: Raw credentials extracted from an incoming HTTP request. +description: |- + Raw credentials extracted from an incoming HTTP request. + + Produced by `extractCredentials` from the `Authorization` and `apikey` headers. +signature: interface Credentials +stability: stable +deprecated: false +properties: + - name: token + location: property + type: string | null + required: true + description: "Bearer token from the `Authorization: Bearer ` header, or `null` if absent." + - name: apikey + location: property + type: string | null + required: true + description: API key from the `apikey` header, or `null` if absent. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-env-error.md b/docs/reference-beta/definitions/server-env-error.md new file mode 100644 index 0000000..522a870 --- /dev/null +++ b/docs/reference-beta/definitions/server-env-error.md @@ -0,0 +1,109 @@ +--- +id: server-env-error +kind: class +category: Errors +title: EnvError +symbol: "@supabase/server.EnvError" +summary: Thrown when a required environment variable is missing or malformed. +description: |- + Thrown when a required environment variable is missing or malformed. + + Always has `status: 500` — environment errors are server-side configuration issues. +signature: class EnvError extends SupabaseServerError +stability: stable +deprecated: false +parameters: + - name: message + location: argument + type: string + required: true + description: Human-readable description. Prefixed with `[@supabase/server]`. + - name: code + location: argument + type: string + required: false + description: Machine-readable code. + - name: options + location: argument + type: SupabaseServerErrorOptions + required: false + description: Optional `hint`, `details`, `docs`, and `cause`. + children: + - name: hint + location: argument + type: string + required: false + description: Actionable next step for whoever has to fix this. + - name: details + location: argument + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics. Never contains key values, token + payloads, or any other secret material. + - name: docs + location: argument + type: string + required: false + description: Override the generated documentation URL. + - name: cause + location: argument + type: unknown + required: false + description: Underlying error, when this one wraps another. +properties: + - name: source + location: property + type: '"@supabase/server"' + required: true + description: Always `"@supabase/server"`. + - name: code + location: property + type: string + required: true + description: Machine-readable error code. + - name: hint + location: property + type: string + required: false + description: Actionable next step, when one applies. + - name: docs + location: property + type: string + required: true + description: Documentation URL for this error's `code`. + - name: details + location: property + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics — accepted auth modes, which + credential headers were present, configured key *names*, JWT header + fields. Never key values or token payloads. + - name: toJSON + location: property + type: () => ErrorPayload + required: true + description: "" + - name: status + location: property + type: "500" + required: true + description: Always `500` — environment errors are server-side issues. +examples: + - id: catching-an-env-error + title: Catching an EnvError + lang: ts + code: | + import { EnvError } from '@supabase/server' + + try { + const client = createAdminClient() + } catch (e) { + if (e instanceof EnvError) { + console.error(`[${e.code}] ${e.message}\n${e.hint}`) + // → "[MISSING_SUPABASE_URL] [@supabase/server] SUPABASE_URL is required but not set." + // "Set SUPABASE_URL to your project URL (https://.supabase.co), …" + } + } +--- diff --git a/docs/reference-beta/definitions/server-env-generic-error.md b/docs/reference-beta/definitions/server-env-generic-error.md new file mode 100644 index 0000000..fe264e9 --- /dev/null +++ b/docs/reference-beta/definitions/server-env-generic-error.md @@ -0,0 +1,13 @@ +--- +id: server-env-generic-error +kind: constant +category: Errors +title: EnvGenericError +symbol: "@supabase/server.EnvGenericError" +summary: Generic environment error code. +description: Generic environment error code. +signature: 'const EnvGenericError: "ENV_ERROR"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-error-code-header.md b/docs/reference-beta/definitions/server-error-code-header.md new file mode 100644 index 0000000..c90f101 --- /dev/null +++ b/docs/reference-beta/definitions/server-error-code-header.md @@ -0,0 +1,15 @@ +--- +id: server-error-code-header +kind: constant +category: Errors +title: ErrorCodeHeader +symbol: "@supabase/server.ErrorCodeHeader" +summary: Response header `withSupabase` sets on every error response, carrying the error `code`. +description: |- + Response header `withSupabase` sets on every error response, carrying + the error `code`. +signature: 'const ErrorCodeHeader: "x-supabase-server-error"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-error-payload.md b/docs/reference-beta/definitions/server-error-payload.md new file mode 100644 index 0000000..3502005 --- /dev/null +++ b/docs/reference-beta/definitions/server-error-payload.md @@ -0,0 +1,46 @@ +--- +id: server-error-payload +kind: type +category: Errors +title: ErrorPayload +symbol: "@supabase/server.ErrorPayload" +summary: Serializable form of a `SupabaseServerError` — the exact JSON body `withSupabase` returns on failure. +description: |- + Serializable form of a `SupabaseServerError` — the exact JSON body + `withSupabase` returns on failure. +signature: interface ErrorPayload +stability: stable +deprecated: false +properties: + - name: source + location: property + type: '"@supabase/server"' + required: true + description: Always `"@supabase/server"`. Identifies which library produced the error. + - name: code + location: property + type: string + required: true + description: Machine-readable error code, also sent as the `x-supabase-server-error` header. + - name: message + location: property + type: string + required: true + description: Human-readable description, prefixed with `[@supabase/server]`. + - name: hint + location: property + type: string + required: false + description: Actionable next step. Omitted when there isn't a useful one. + - name: docs + location: property + type: string + required: true + description: Documentation URL for this specific code. + - name: details + location: property + type: Record + required: false + description: Structured, non-sensitive diagnostics. Omitted when there are none. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-error-response-config.md b/docs/reference-beta/definitions/server-error-response-config.md new file mode 100644 index 0000000..207c162 --- /dev/null +++ b/docs/reference-beta/definitions/server-error-response-config.md @@ -0,0 +1,45 @@ +--- +id: server-error-response-config +kind: type +category: Types +title: ErrorResponseConfig +symbol: "@supabase/server.ErrorResponseConfig" +summary: "Controls how much of an error goes in the response body. Accepted as `errors` by `withSupabase` and by every middleware that answers a request directly: `withClaims`, `withRequiredClaims`, `withPostgresClient`, `withPostgresAdminClient` and `withOAuthProtectedResource`." +description: |- + Controls how much of an error goes in the response body. Accepted as + `errors` by `withSupabase` and by every middleware that answers a + request directly: `withClaims`, `withRequiredClaims`, `withPostgresClient`, + `withPostgresAdminClient` and `withOAuthProtectedResource`. +signature: interface ErrorResponseConfig +stability: stable +deprecated: false +properties: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: + - id: trimming-the-response + title: Trimming the response + lang: ts + code: | + // Full payload: source, code, message, hint, docs, details + withSupabase({ auth: 'user' }, handler) + + // Trimmed: code and message only + withSupabase({ auth: 'user', errors: { detailed: false } }, handler) +--- diff --git a/docs/reference-beta/definitions/server-error-source.md b/docs/reference-beta/definitions/server-error-source.md new file mode 100644 index 0000000..b029892 --- /dev/null +++ b/docs/reference-beta/definitions/server-error-source.md @@ -0,0 +1,19 @@ +--- +id: server-error-source +kind: constant +category: Errors +title: ErrorSource +symbol: "@supabase/server.ErrorSource" +summary: Package identifier stamped on every error this library produces. +description: |- + Package identifier stamped on every error this library produces. + + Present as `source` on each error instance, as the `source` field of the JSON + body `withSupabase` returns, and as a `[@supabase/server]` prefix on + every `message` — so an error is traceable back here from a log line, a + response body, or a response header alone. +signature: 'const ErrorSource: "@supabase/server"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-errors.md b/docs/reference-beta/definitions/server-errors.md new file mode 100644 index 0000000..1821be6 --- /dev/null +++ b/docs/reference-beta/definitions/server-errors.md @@ -0,0 +1,123 @@ +--- +id: server-errors +kind: constant +category: Errors +title: Errors +symbol: "@supabase/server.Errors" +summary: Factory map for all error types. Keyed by error code constant, each entry returns a pre-configured `EnvError`, `AuthError`, or `PostgresPoolError` complete with `hint`, `docs`, and `details`. +description: |- + Factory map for all error types. Keyed by error code constant, each entry + returns a pre-configured `EnvError`, `AuthError`, or + `PostgresPoolError` complete with `hint`, `docs`, and `details`. +signature: 'const Errors: { MISSING_SUPABASE_URL: () => EnvError; MISSING_SECRET_KEY: (name: string, availableKeyNames?: readonly string[]) => EnvError; MISSING_DEFAULT_SECRET_KEY: (availableKeyNames?: readonly string[]) => EnvError; MISSING_PUBLISHABLE_KEY: (name: string, availableKeyNames?: readonly string[]) => EnvError; MISSING_DEFAULT_PUBLISHABLE_KEY: (availableKeyNames?: readonly string[]) => EnvError; MISSING_RESOURCE_SERVER: (runtime: string) => EnvError; MISSING_AUTHORIZATION_SERVER: () => EnvError; MISSING_CONNECTION_STRING: (middleware: string) => EnvError; MISSING_CREDENTIALS: (context: AuthFailureContext) => AuthError; UNUSABLE_CREDENTIAL: (context: Partial & { reason: string; hint: string }) => AuthError; INVALID_API_KEY: (context: AuthFailureContext) => AuthError; INVALID_JWT: (context: Partial & { reason: string; hint: string; jwt?: Record; cause?: unknown }) => AuthError; JWKS_NOT_CONFIGURED: (context: Partial & { middleware?: string }) => AuthError; JWKS_FETCH_FAILED: (context: Partial & { reason: string; cause?: unknown }) => AuthError; NO_KEYS_CONFIGURED: (context: AuthFailureContext & { mode: string; keyKind: "publishable" | "secret" }) => AuthError; INVALID_CREDENTIALS: (context?: AuthFailureContext) => AuthError; CREATE_SUPABASE_CLIENT_ERROR: (options?: { cause?: unknown }) => AuthError; UNSUPPORTED_ROLE: (context: { requestedRole: unknown; supportedRoles: readonly string[] }) => AuthError; POSTGRES_POOL_BUSY: (context: { max: number; waitedMs: number }) => PostgresPoolError; POSTGRES_CONNECT_PAUSED: (context: { remainingMs: number; cause: unknown }) => PostgresPoolError }' +stability: stable +deprecated: false +properties: + - name: MISSING_SUPABASE_URL + location: property + type: () => EnvError + required: true + description: "" + - name: MISSING_SECRET_KEY + location: property + type: "(name: string, availableKeyNames?: readonly string[]) => EnvError" + required: true + description: "" + - name: MISSING_DEFAULT_SECRET_KEY + location: property + type: "(availableKeyNames?: readonly string[]) => EnvError" + required: true + description: "" + - name: MISSING_PUBLISHABLE_KEY + location: property + type: "(name: string, availableKeyNames?: readonly string[]) => EnvError" + required: true + description: "" + - name: MISSING_DEFAULT_PUBLISHABLE_KEY + location: property + type: "(availableKeyNames?: readonly string[]) => EnvError" + required: true + description: "" + - name: MISSING_RESOURCE_SERVER + location: property + type: "(runtime: string) => EnvError" + required: true + description: "" + - name: MISSING_AUTHORIZATION_SERVER + location: property + type: () => EnvError + required: true + description: "" + - name: MISSING_CONNECTION_STRING + location: property + type: "(middleware: string) => EnvError" + required: true + description: "" + - name: MISSING_CREDENTIALS + location: property + type: "(context: AuthFailureContext) => AuthError" + required: true + description: "" + - name: UNUSABLE_CREDENTIAL + location: property + type: "(context: Partial & { reason: string; hint: string }) => AuthError" + required: true + description: "" + - name: INVALID_API_KEY + location: property + type: "(context: AuthFailureContext) => AuthError" + required: true + description: "" + - name: INVALID_JWT + location: property + type: "(context: Partial & { reason: string; hint: string; jwt?: Record; cause?: unknown }) => AuthError" + required: true + description: "" + - name: JWKS_NOT_CONFIGURED + location: property + type: "(context: Partial & { middleware?: string }) => AuthError" + required: true + description: "" + - name: JWKS_FETCH_FAILED + location: property + type: "(context: Partial & { reason: string; cause?: unknown }) => AuthError" + required: true + description: "" + - name: NO_KEYS_CONFIGURED + location: property + type: '(context: AuthFailureContext & { mode: string; keyKind: "publishable" | "secret" }) => AuthError' + required: true + description: "" + - name: INVALID_CREDENTIALS + location: property + type: "(context?: AuthFailureContext) => AuthError" + required: true + description: "" + - name: CREATE_SUPABASE_CLIENT_ERROR + location: property + type: "(options?: { cause?: unknown }) => AuthError" + required: true + description: "" + - name: UNSUPPORTED_ROLE + location: property + type: "(context: { requestedRole: unknown; supportedRoles: readonly string[] }) => AuthError" + required: true + description: "" + - name: POSTGRES_POOL_BUSY + location: property + type: "(context: { max: number; waitedMs: number }) => PostgresPoolError" + required: true + description: "" + - name: POSTGRES_CONNECT_PAUSED + location: property + type: "(context: { remainingMs: number; cause: unknown }) => PostgresPoolError" + required: true + description: "" +examples: + - id: throwing-typed-errors + title: Throwing typed errors + lang: ts + code: | + throw Errors[MissingSupabaseURLError]() + throw Errors[MissingPublishableKeyError]('mobile', ['default', 'web']) +--- diff --git a/docs/reference-beta/definitions/server-from-supabase-url.md b/docs/reference-beta/definitions/server-from-supabase-url.md new file mode 100644 index 0000000..ac46438 --- /dev/null +++ b/docs/reference-beta/definitions/server-from-supabase-url.md @@ -0,0 +1,43 @@ +--- +id: server-from-supabase-url +kind: method +category: Middleware +title: fromSupabaseUrl +symbol: "@supabase/server.fromSupabaseUrl" +summary: Points `authorizationServer` at a Supabase project's Auth issuer. +description: |- + Points `authorizationServer` at a Supabase project's Auth + issuer. + + Use this off Supabase Edge Functions, where the app's own origin is unrelated + to the Supabase project's, so the issuer cannot be derived from the request. +signature: "fromSupabaseUrl(supabaseUrl: string): string" +stability: stable +deprecated: false +parameters: + - name: supabaseUrl + location: argument + type: string + required: true + description: |- + The project URL, e.g. `https://.supabase.co` (the + same value passed to `createClient()`). +returns: + type: string + description: "" +throws: [] +examples: + - id: example-1 + title: Example 1 + lang: ts + code: | + import { withOAuthProtectedResource, fromSupabaseUrl } from '@supabase/server' + + withOAuthProtectedResource( + { + resourceServer: (req) => new URL(req.url).origin + '/api/mcp', + authorizationServer: fromSupabaseUrl('https://abc123.supabase.co'), + }, + handler, + ) +--- diff --git a/docs/reference-beta/definitions/server-invalid-api-key-error.md b/docs/reference-beta/definitions/server-invalid-api-key-error.md new file mode 100644 index 0000000..f51494e --- /dev/null +++ b/docs/reference-beta/definitions/server-invalid-api-key-error.md @@ -0,0 +1,15 @@ +--- +id: server-invalid-api-key-error +kind: constant +category: Errors +title: InvalidApiKeyError +symbol: "@supabase/server.InvalidApiKeyError" +summary: An `apikey` header was present but matched none of the keys configured for the accepted auth modes. +description: |- + An `apikey` header was present but matched none of the keys configured for + the accepted auth modes. +signature: 'const InvalidApiKeyError: "INVALID_API_KEY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-invalid-credentials-error.md b/docs/reference-beta/definitions/server-invalid-credentials-error.md new file mode 100644 index 0000000..2db08da --- /dev/null +++ b/docs/reference-beta/definitions/server-invalid-credentials-error.md @@ -0,0 +1,20 @@ +--- +id: server-invalid-credentials-error +kind: constant +category: Errors +title: InvalidCredentialsError +symbol: "@supabase/server.InvalidCredentialsError" +summary: Generic credential failure. Retained as the fallback code for cases that don't match a more specific one. +description: |- + Generic credential failure. Retained as the fallback code for cases that + don't match a more specific one. +signature: 'const InvalidCredentialsError: "INVALID_CREDENTIALS"' +stability: stable +deprecated: false +examples: [] +--- + +Prior to v1.5 this was the only code `withSupabase` ever +returned for a failed request. Prefer matching on the specific codes — +`MissingCredentialsError`, `InvalidApiKeyError`, +`InvalidJwtError` — which now cover nearly every real failure. diff --git a/docs/reference-beta/definitions/server-invalid-jwt-error.md b/docs/reference-beta/definitions/server-invalid-jwt-error.md new file mode 100644 index 0000000..08500ed --- /dev/null +++ b/docs/reference-beta/definitions/server-invalid-jwt-error.md @@ -0,0 +1,17 @@ +--- +id: server-invalid-jwt-error +kind: constant +category: Errors +title: InvalidJwtError +symbol: "@supabase/server.InvalidJwtError" +summary: A JWT was present in the `Authorization` header but failed verification. `details.jwt` and the message carry the specific reason (expired, bad signature, unknown `kid`, malformed token or claim, no `sub`, mismatched or missing `aud` / `iss`, `nbf` in the future). +description: |- + A JWT was present in the `Authorization` header but failed verification. + `details.jwt` and the message carry the specific reason (expired, bad + signature, unknown `kid`, malformed token or claim, no `sub`, mismatched or + missing `aud` / `iss`, `nbf` in the future). +signature: 'const InvalidJwtError: "INVALID_JWT"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-jwks-fetch-failed-error.md b/docs/reference-beta/definitions/server-jwks-fetch-failed-error.md new file mode 100644 index 0000000..01fdff6 --- /dev/null +++ b/docs/reference-beta/definitions/server-jwks-fetch-failed-error.md @@ -0,0 +1,15 @@ +--- +id: server-jwks-fetch-failed-error +kind: constant +category: Errors +title: JwksFetchFailedError +symbol: "@supabase/server.JwksFetchFailedError" +summary: "The remote JWKS endpoint could not be fetched or returned something unusable. Server-side / upstream failure (`status: 500`), not a bad request." +description: |- + The remote JWKS endpoint could not be fetched or returned something + unusable. Server-side / upstream failure (`status: 500`), not a bad request. +signature: 'const JwksFetchFailedError: "JWKS_FETCH_FAILED"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-jwks-not-configured-error.md b/docs/reference-beta/definitions/server-jwks-not-configured-error.md new file mode 100644 index 0000000..5e4151d --- /dev/null +++ b/docs/reference-beta/definitions/server-jwks-not-configured-error.md @@ -0,0 +1,16 @@ +--- +id: server-jwks-not-configured-error +kind: constant +category: Errors +title: JwksNotConfiguredError +symbol: "@supabase/server.JwksNotConfiguredError" +summary: 'Auth mode `"user"` was requested and a JWT was supplied, but no JWKS is configured — so the token cannot be verified. Server misconfiguration (`status: 500`), not a bad request.' +description: |- + Auth mode `"user"` was requested and a JWT was supplied, but no JWKS is + configured — so the token cannot be verified. Server misconfiguration + (`status: 500`), not a bad request. +signature: 'const JwksNotConfiguredError: "JWKS_NOT_CONFIGURED"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-jwtclaims.md b/docs/reference-beta/definitions/server-jwtclaims.md new file mode 100644 index 0000000..71c5531 --- /dev/null +++ b/docs/reference-beta/definitions/server-jwtclaims.md @@ -0,0 +1,62 @@ +--- +id: server-jwtclaims +kind: type +category: Types +title: JWTClaims +symbol: "@supabase/server.JWTClaims" +summary: Standard JWT claims as defined by RFC 7519, extended with Supabase-specific fields. +description: |- + Standard JWT claims as defined by RFC 7519, extended with Supabase-specific fields. + + This is the raw JWT payload — use `UserClaims` for a normalized, camelCase view. +signature: interface JWTClaims +stability: stable +deprecated: false +properties: + - name: sub + location: property + type: string + required: true + description: Subject — the user's unique ID. + - name: iss + location: property + type: string + required: false + description: Issuer — typically your Supabase project URL. + - name: aud + location: property + type: string | string[] + required: false + description: Audience — who the token is intended for. + - name: exp + location: property + type: number + required: false + description: Expiration time (seconds since epoch). + - name: iat + location: property + type: number + required: false + description: Issued at (seconds since epoch). + - name: role + location: property + type: string + required: false + description: Supabase role (e.g. `"authenticated"`, `"anon"`). + - name: email + location: property + type: string + required: false + description: User's email address from Supabase Auth. + - name: app_metadata + location: property + type: Record + required: false + description: Application-level metadata set via Supabase Auth admin APIs. + - name: user_metadata + location: property + type: Record + required: false + description: User-editable metadata set via Supabase Auth. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-minimal-error-payload.md b/docs/reference-beta/definitions/server-minimal-error-payload.md new file mode 100644 index 0000000..3359b38 --- /dev/null +++ b/docs/reference-beta/definitions/server-minimal-error-payload.md @@ -0,0 +1,17 @@ +--- +id: server-minimal-error-payload +kind: type +category: Errors +title: MinimalErrorPayload +symbol: "@supabase/server.MinimalErrorPayload" +summary: "Reduced error body produced when `errors: { detailed: false }` is set." +description: |- + Reduced error body produced when `errors: { detailed: false }` is set. + + `message` keeps its `[@supabase/server]` prefix, so the error is still + traceable back here even without the `source` field. +signature: type MinimalErrorPayload = Pick +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-authorization-server-error.md b/docs/reference-beta/definitions/server-missing-authorization-server-error.md new file mode 100644 index 0000000..474c413 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-authorization-server-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-authorization-server-error +kind: constant +category: Errors +title: MissingAuthorizationServerError +symbol: "@supabase/server.MissingAuthorizationServerError" +summary: "`withOAuthProtectedResource` has no `authorizationServer` and cannot derive one." +description: "`withOAuthProtectedResource` has no `authorizationServer` and cannot derive one." +signature: 'const MissingAuthorizationServerError: "MISSING_AUTHORIZATION_SERVER"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-connection-string-error.md b/docs/reference-beta/definitions/server-missing-connection-string-error.md new file mode 100644 index 0000000..8f21531 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-connection-string-error.md @@ -0,0 +1,15 @@ +--- +id: server-missing-connection-string-error +kind: constant +category: Errors +title: MissingConnectionStringError +symbol: "@supabase/server.MissingConnectionStringError" +summary: No Postgres connection string is configured, so the `withPostgresClient` / `withPostgresAdminClient` middleware cannot connect. +description: |- + No Postgres connection string is configured, so the `withPostgresClient` / + `withPostgresAdminClient` middleware cannot connect. +signature: 'const MissingConnectionStringError: "MISSING_CONNECTION_STRING"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-credentials-error.md b/docs/reference-beta/definitions/server-missing-credentials-error.md new file mode 100644 index 0000000..649c1ac --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-credentials-error.md @@ -0,0 +1,15 @@ +--- +id: server-missing-credentials-error +kind: constant +category: Errors +title: MissingCredentialsError +symbol: "@supabase/server.MissingCredentialsError" +summary: "The request carried no credentials at all — neither an `apikey` header nor an `Authorization: Bearer` token — and no accepted auth mode allows that." +description: |- + The request carried no credentials at all — neither an `apikey` header nor + an `Authorization: Bearer` token — and no accepted auth mode allows that. +signature: 'const MissingCredentialsError: "MISSING_CREDENTIALS"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-default-publishable-key-error.md b/docs/reference-beta/definitions/server-missing-default-publishable-key-error.md new file mode 100644 index 0000000..0e254eb --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-default-publishable-key-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-default-publishable-key-error +kind: constant +category: Errors +title: MissingDefaultPublishableKeyError +symbol: "@supabase/server.MissingDefaultPublishableKeyError" +summary: No default publishable key found. +description: No default publishable key found. +signature: 'const MissingDefaultPublishableKeyError: "MISSING_DEFAULT_PUBLISHABLE_KEY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-default-secret-key-error.md b/docs/reference-beta/definitions/server-missing-default-secret-key-error.md new file mode 100644 index 0000000..6fc80e8 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-default-secret-key-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-default-secret-key-error +kind: constant +category: Errors +title: MissingDefaultSecretKeyError +symbol: "@supabase/server.MissingDefaultSecretKeyError" +summary: No default secret key found. +description: No default secret key found. +signature: 'const MissingDefaultSecretKeyError: "MISSING_DEFAULT_SECRET_KEY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-publishable-key-error.md b/docs/reference-beta/definitions/server-missing-publishable-key-error.md new file mode 100644 index 0000000..74a612b --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-publishable-key-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-publishable-key-error +kind: constant +category: Errors +title: MissingPublishableKeyError +symbol: "@supabase/server.MissingPublishableKeyError" +summary: Named publishable key not found in `SUPABASE_PUBLISHABLE_KEYS`. +description: Named publishable key not found in `SUPABASE_PUBLISHABLE_KEYS`. +signature: 'const MissingPublishableKeyError: "MISSING_PUBLISHABLE_KEY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-resource-server-error.md b/docs/reference-beta/definitions/server-missing-resource-server-error.md new file mode 100644 index 0000000..928a486 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-resource-server-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-resource-server-error +kind: constant +category: Errors +title: MissingResourceServerError +symbol: "@supabase/server.MissingResourceServerError" +summary: "`withOAuthProtectedResource` has no `resourceServer` and cannot derive one." +description: "`withOAuthProtectedResource` has no `resourceServer` and cannot derive one." +signature: 'const MissingResourceServerError: "MISSING_RESOURCE_SERVER"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-secret-key-error.md b/docs/reference-beta/definitions/server-missing-secret-key-error.md new file mode 100644 index 0000000..0890091 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-secret-key-error.md @@ -0,0 +1,13 @@ +--- +id: server-missing-secret-key-error +kind: constant +category: Errors +title: MissingSecretKeyError +symbol: "@supabase/server.MissingSecretKeyError" +summary: Named secret key not found in `SUPABASE_SECRET_KEYS`. +description: Named secret key not found in `SUPABASE_SECRET_KEYS`. +signature: 'const MissingSecretKeyError: "MISSING_SECRET_KEY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-missing-supabase-urlerror.md b/docs/reference-beta/definitions/server-missing-supabase-urlerror.md new file mode 100644 index 0000000..53b1723 --- /dev/null +++ b/docs/reference-beta/definitions/server-missing-supabase-urlerror.md @@ -0,0 +1,13 @@ +--- +id: server-missing-supabase-urlerror +kind: constant +category: Errors +title: MissingSupabaseURLError +symbol: "@supabase/server.MissingSupabaseURLError" +summary: "`SUPABASE_URL` is not set." +description: "`SUPABASE_URL` is not set." +signature: 'const MissingSupabaseURLError: "MISSING_SUPABASE_URL"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-no-keys-configured-error.md b/docs/reference-beta/definitions/server-no-keys-configured-error.md new file mode 100644 index 0000000..24ac2cf --- /dev/null +++ b/docs/reference-beta/definitions/server-no-keys-configured-error.md @@ -0,0 +1,16 @@ +--- +id: server-no-keys-configured-error +kind: constant +category: Errors +title: NoKeysConfiguredError +symbol: "@supabase/server.NoKeysConfiguredError" +summary: 'An `"publishable"` or `"secret"` auth mode was requested but no keys of that kind are configured, so the mode could never match. Server misconfiguration (`status: 500`).' +description: |- + An `"publishable"` or `"secret"` auth mode was requested but no keys of that + kind are configured, so the mode could never match. Server + misconfiguration (`status: 500`). +signature: 'const NoKeysConfiguredError: "NO_KEYS_CONFIGURED"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-oauth-protected-resource-config.md b/docs/reference-beta/definitions/server-oauth-protected-resource-config.md new file mode 100644 index 0000000..e17f2ac --- /dev/null +++ b/docs/reference-beta/definitions/server-oauth-protected-resource-config.md @@ -0,0 +1,68 @@ +--- +id: server-oauth-protected-resource-config +kind: type +category: Types +title: OAuthProtectedResourceConfig +symbol: "@supabase/server.OAuthProtectedResourceConfig" +summary: Configuration for `withOAuthProtectedResource`. +description: |- + Configuration for `withOAuthProtectedResource`. + + Both options accept a fixed string or a function of the request. Both default + to values derived from the request as it arrives through the Supabase Edge + Functions proxy, so no configuration is needed there. +signature: interface OAuthProtectedResourceConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: resourceServer + location: property + type: UrlOption + required: false + description: |- + The resource identifier to advertise — this endpoint's externally-visible + URL, which RFC 9728 §3.3 requires to equal the URL the client called. + + Defaults to the Edge Functions derivation. Required on any other backend, + usually from the request — `(req) => new URL(req.url).origin + '/api/mcp'`. + Unset there, every request other than the metadata route's `OPTIONS` + preflight is answered with a `500` and code `MISSING_RESOURCE_SERVER`. + - name: authorizationServer + location: property + type: UrlOption + required: false + description: |- + The OAuth 2.1 authorization server to advertise, as an issuer identifier. + + Defaults to the project's Supabase Auth on Edge Functions. Elsewhere it + falls back to `SUPABASE_PUBLIC_URL`, then `SUPABASE_URL`, each with + `/auth/v1` appended; with neither set, the metadata route is answered with + a `500` and code `MISSING_AUTHORIZATION_SERVER`. Pass + `fromSupabaseUrl` for a specific project, or any other issuer + directly. + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-postgres-connect-paused-error.md b/docs/reference-beta/definitions/server-postgres-connect-paused-error.md new file mode 100644 index 0000000..c22f482 --- /dev/null +++ b/docs/reference-beta/definitions/server-postgres-connect-paused-error.md @@ -0,0 +1,16 @@ +--- +id: server-postgres-connect-paused-error +kind: constant +category: Errors +title: PostgresConnectPausedError +symbol: "@supabase/server.PostgresConnectPausedError" +summary: A connection attempt failed and the pool is pausing new attempts, so a query that needed a new connection was refused without trying. `cause` is the failure and `details.retryAfterMs` the time left in the pause. +description: |- + A connection attempt failed and the pool is pausing new attempts, so a query + that needed a new connection was refused without trying. `cause` is the + failure and `details.retryAfterMs` the time left in the pause. +signature: 'const PostgresConnectPausedError: "POSTGRES_CONNECT_PAUSED"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-postgres-pool-busy-error.md b/docs/reference-beta/definitions/server-postgres-pool-busy-error.md new file mode 100644 index 0000000..ff05ce1 --- /dev/null +++ b/docs/reference-beta/definitions/server-postgres-pool-busy-error.md @@ -0,0 +1,16 @@ +--- +id: server-postgres-pool-busy-error +kind: constant +category: Errors +title: PostgresPoolBusyError +symbol: "@supabase/server.PostgresPoolBusyError" +summary: Every pooled connection stayed busy for the whole checkout wait, so the query could not get one. `details.max` is the pool size and `details.waitedMs` the wait. +description: |- + Every pooled connection stayed busy for the whole checkout wait, so the + query could not get one. `details.max` is the pool size and + `details.waitedMs` the wait. +signature: 'const PostgresPoolBusyError: "POSTGRES_POOL_BUSY"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-postgres-pool-error.md b/docs/reference-beta/definitions/server-postgres-pool-error.md new file mode 100644 index 0000000..4c5e623 --- /dev/null +++ b/docs/reference-beta/definitions/server-postgres-pool-error.md @@ -0,0 +1,120 @@ +--- +id: server-postgres-pool-error +kind: class +category: Errors +title: PostgresPoolError +symbol: "@supabase/server.PostgresPoolError" +summary: "Thrown when the Postgres pool cannot hand a query a connection: every pooled connection stayed busy for the whole checkout wait, or new connection attempts are paused after one failed." +description: |- + Thrown when the Postgres pool cannot hand a query a connection: every pooled + connection stayed busy for the whole checkout wait, or new connection + attempts are paused after one failed. + + Always has `status: 503`. Both conditions are transient, so the request can + be retried. `details.retryAfterMs` gives the time left when a pause is + running. + + `ctx.postgres` and `ctx.postgresAdmin` throw this from the query call. The + middleware do not turn it into a response; the handler or the host's error + handler decides how the request answers. +signature: class PostgresPoolError extends SupabaseServerError +stability: stable +deprecated: false +parameters: + - name: message + location: argument + type: string + required: true + description: Human-readable description. Prefixed with `[@supabase/server]`. + - name: code + location: argument + type: string + required: true + description: Machine-readable code. + - name: options + location: argument + type: SupabaseServerErrorOptions + required: false + description: Optional `hint`, `details`, `docs`, and `cause`. + children: + - name: hint + location: argument + type: string + required: false + description: Actionable next step for whoever has to fix this. + - name: details + location: argument + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics. Never contains key values, token + payloads, or any other secret material. + - name: docs + location: argument + type: string + required: false + description: Override the generated documentation URL. + - name: cause + location: argument + type: unknown + required: false + description: Underlying error, when this one wraps another. +properties: + - name: source + location: property + type: '"@supabase/server"' + required: true + description: Always `"@supabase/server"`. + - name: code + location: property + type: string + required: true + description: Machine-readable error code. + - name: hint + location: property + type: string + required: false + description: Actionable next step, when one applies. + - name: docs + location: property + type: string + required: true + description: Documentation URL for this error's `code`. + - name: details + location: property + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics — accepted auth modes, which + credential headers were present, configured key *names*, JWT header + fields. Never key values or token payloads. + - name: toJSON + location: property + type: () => ErrorPayload + required: true + description: "" + - name: status + location: property + type: "503" + required: true + description: Always `503`. Nothing about the request is wrong; the pool has no connection for it yet. +examples: + - id: answering-503-with-a-retry-after-header + title: Answering 503 with a Retry-After header + lang: ts + code: | + import { PostgresPoolError } from '@supabase/server' + + try { + return Response.json(await ctx.postgres.query`select * from notes`) + } catch (e) { + if (e instanceof PostgresPoolError) { + const retryAfterMs = Number(e.details?.retryAfterMs ?? 1000) + return Response.json(e.toJSON(), { + status: e.status, + headers: { 'Retry-After': String(Math.ceil(retryAfterMs / 1000)) }, + }) + } + throw e + } +--- diff --git a/docs/reference-beta/definitions/server-received-credentials.md b/docs/reference-beta/definitions/server-received-credentials.md new file mode 100644 index 0000000..1684813 --- /dev/null +++ b/docs/reference-beta/definitions/server-received-credentials.md @@ -0,0 +1,32 @@ +--- +id: server-received-credentials +kind: type +category: Errors +title: ReceivedCredentials +symbol: "@supabase/server.ReceivedCredentials" +summary: Non-sensitive summary of the credentials a request carried. +description: Non-sensitive summary of the credentials a request carried. +signature: interface ReceivedCredentials +stability: stable +deprecated: false +properties: + - name: authorization + location: property + type: '"absent" | "bearer" | "api-key" | "non-bearer-scheme"' + required: true + description: |- + What the `Authorization` header carried. + + - `'bearer'` — a bearer token that looks like a JWT + - `'api-key'` — an `sb_*` API key, which the Supabase SDK forwards here + alongside the `apikey` header; not a user token + - `'non-bearer-scheme'` — present but unusable (wrong scheme, wrong + casing, bare value, empty token) + - `'absent'` — no header + - name: apikey + location: property + type: ApiKeyFormat + required: true + description: The `apikey` header classified by prefix. Never the value itself. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-resource-metadata-options.md b/docs/reference-beta/definitions/server-resource-metadata-options.md new file mode 100644 index 0000000..b28e556 --- /dev/null +++ b/docs/reference-beta/definitions/server-resource-metadata-options.md @@ -0,0 +1,24 @@ +--- +id: server-resource-metadata-options +kind: type +category: Types +title: ResourceMetadataOptions +symbol: "@supabase/server.ResourceMetadataOptions" +summary: Options for `resourceMetadataResponse`. +description: Options for `resourceMetadataResponse`. +signature: interface ResourceMetadataOptions +stability: stable +deprecated: false +properties: + - name: resource + location: property + type: string + required: false + description: Override the resource URI. + - name: authorizationServers + location: property + type: string[] + required: false + description: Override the authorization servers list. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-resource-metadata-response.md b/docs/reference-beta/definitions/server-resource-metadata-response.md new file mode 100644 index 0000000..e46c73a --- /dev/null +++ b/docs/reference-beta/definitions/server-resource-metadata-response.md @@ -0,0 +1,43 @@ +--- +id: server-resource-metadata-response +kind: method +category: Middleware +title: resourceMetadataResponse +symbol: "@supabase/server.resourceMetadataResponse" +summary: RFC 9728 OAuth Protected Resource Metadata response. Advertises the authorization server, resource URI, and bearer methods supported. URLs default to the Edge Functions derivation and throw off platform; pass `resource` / `authorizationServers` to override. +description: |- + RFC 9728 OAuth Protected Resource Metadata response. + Advertises the authorization server, resource URI, and bearer methods supported. + URLs default to the Edge Functions derivation and throw off platform; pass + `resource` / `authorizationServers` to override. +signature: "resourceMetadataResponse(req: Request, options?: ResourceMetadataOptions): Response" +stability: stable +deprecated: false +parameters: + - name: req + location: argument + type: Request + required: true + description: "" + - name: options + location: argument + type: ResourceMetadataOptions + required: false + description: "" + children: + - name: resource + location: argument + type: string + required: false + description: Override the resource URI. + - name: authorizationServers + location: argument + type: string[] + required: false + description: Override the authorization servers list. +returns: + type: Response + description: "" +throws: [] +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-short-circuit-config.md b/docs/reference-beta/definitions/server-short-circuit-config.md new file mode 100644 index 0000000..bc81d4f --- /dev/null +++ b/docs/reference-beta/definitions/server-short-circuit-config.md @@ -0,0 +1,42 @@ +--- +id: server-short-circuit-config +kind: type +category: Types +title: ShortCircuitConfig +symbol: "@supabase/server.ShortCircuitConfig" +summary: "The option shared by every middleware that answers a request itself: `withSupabase`, `withClaims`, `withRequiredClaims`, `withPostgresClient`, `withPostgresAdminClient` and `withOAuthProtectedResource`. Each applies `errors` to its own responses." +description: |- + The option shared by every middleware that answers a request itself: + `withSupabase`, `withClaims`, `withRequiredClaims`, `withPostgresClient`, + `withPostgresAdminClient` and `withOAuthProtectedResource`. Each applies + `errors` to its own responses. +signature: interface ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-supabase-context.md b/docs/reference-beta/definitions/server-supabase-context.md new file mode 100644 index 0000000..7e29ecc --- /dev/null +++ b/docs/reference-beta/definitions/server-supabase-context.md @@ -0,0 +1,50 @@ +--- +id: server-supabase-context +kind: type +category: Types +title: SupabaseContext +symbol: "@supabase/server.SupabaseContext" +summary: The Supabase context created for each authenticated request. +description: |- + The Supabase context created for each authenticated request. + + Contains pre-configured Supabase clients and the caller's identity. + Identical regardless of which layer or adapter produced it. +signature: interface SupabaseContext +stability: stable +deprecated: false +properties: + - name: supabase + location: property + type: SupabaseClient + required: true + description: Supabase client scoped to the caller's identity. RLS policies apply. + - name: supabaseAdmin + location: property + type: SupabaseClient + required: true + description: Admin Supabase client that bypasses Row-Level Security. + - name: userClaims + location: property + type: UserClaims | null + required: true + description: JWT-derived identity. For the full Supabase User object, call `supabase.auth.getUser()`. + - name: jwtClaims + location: property + type: JWTClaims | null + required: true + description: Raw JWT payload. `null` for non-user auth modes. + - name: authMode + location: property + type: AuthMode + required: true + description: The auth mode that was used for this request. + - name: authKeyName + location: property + type: string + required: false + description: |- + The auth key name of the API key that was used for this request. + Omitted for `'user'` and `'none'` modes, which don't match a named key. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-supabase-env.md b/docs/reference-beta/definitions/server-supabase-env.md new file mode 100644 index 0000000..4b80b79 --- /dev/null +++ b/docs/reference-beta/definitions/server-supabase-env.md @@ -0,0 +1,57 @@ +--- +id: server-supabase-env +kind: type +category: Types +title: SupabaseEnv +symbol: "@supabase/server.SupabaseEnv" +summary: Resolved Supabase environment configuration. +description: |- + Resolved Supabase environment configuration. + + Holds the project URL, API keys, and JWKS needed by every other primitive. + Typically resolved automatically from environment variables by `resolveEnv`, + but can be passed explicitly via the `env` option. +signature: interface SupabaseEnv +stability: stable +deprecated: false +properties: + - name: url + location: property + type: string + required: true + description: Supabase project URL (e.g. `"https://.supabase.co"`). Sourced from `SUPABASE_URL`. + - name: publishableKeys + location: property + type: Record + required: true + description: |- + Named publishable keys. Sourced from `SUPABASE_PUBLISHABLE_KEYS` (JSON object) + or `SUPABASE_PUBLISHABLE_KEY` (single key, stored as `{ default: "" }`). + - name: secretKeys + location: property + type: Record + required: true + description: |- + Named secret keys. Sourced from `SUPABASE_SECRET_KEYS` (JSON object) + or `SUPABASE_SECRET_KEY` (single key, stored as `{ default: "" }`). + - name: jwks + location: property + type: JSONWebKeySet | URL | null + required: true + description: |- + JWKS source used for JWT verification. + + Sourced from one of (in priority order): + - `SUPABASE_JWKS` — inline JSON. Resolves to a `JSONWebKeySet`. + - `SUPABASE_JWKS_URL` — remote endpoint. Resolves to a `URL`; keys + are fetched lazily and cached in memory (cooldown / max-age handled by + `jose`). `https://` is always accepted; plain `http://` is accepted + only for loopback hosts (`localhost`, `127.0.0.0/8`, `::1`) to support + the Supabase CLI. Any other `http://` URL is rejected to prevent MITM + swap-in of a forged signing key. + + `null` when no JWKS is configured (JWT verification will be unavailable). + Each env var is authoritative when set: a malformed value resolves to + `null` rather than falling through to the other variable. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-supabase-server-error-options.md b/docs/reference-beta/definitions/server-supabase-server-error-options.md new file mode 100644 index 0000000..ceee2ca --- /dev/null +++ b/docs/reference-beta/definitions/server-supabase-server-error-options.md @@ -0,0 +1,36 @@ +--- +id: server-supabase-server-error-options +kind: type +category: Errors +title: SupabaseServerErrorOptions +symbol: "@supabase/server.SupabaseServerErrorOptions" +summary: Optional diagnostics attached to a `SupabaseServerError`. +description: Optional diagnostics attached to a `SupabaseServerError`. +signature: interface SupabaseServerErrorOptions +stability: stable +deprecated: false +properties: + - name: hint + location: property + type: string + required: false + description: Actionable next step for whoever has to fix this. + - name: details + location: property + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics. Never contains key values, token + payloads, or any other secret material. + - name: docs + location: property + type: string + required: false + description: Override the generated documentation URL. + - name: cause + location: property + type: unknown + required: false + description: Underlying error, when this one wraps another. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-supabase-server-error.md b/docs/reference-beta/definitions/server-supabase-server-error.md new file mode 100644 index 0000000..d4805ea --- /dev/null +++ b/docs/reference-beta/definitions/server-supabase-server-error.md @@ -0,0 +1,110 @@ +--- +id: server-supabase-server-error +kind: class +category: Errors +title: SupabaseServerError +symbol: "@supabase/server.SupabaseServerError" +summary: Base class for every error `@supabase/server` produces. +description: |- + Base class for every error `@supabase/server` produces. + + Catch this to handle anything originating from this library, regardless of + whether it's an `EnvError` or an `AuthError`: +signature: class SupabaseServerError extends Error +stability: stable +deprecated: false +parameters: + - name: message + location: argument + type: string + required: true + description: "" + - name: code + location: argument + type: string + required: true + description: "" + - name: options + location: argument + type: SupabaseServerErrorOptions + required: false + description: "" + children: + - name: hint + location: argument + type: string + required: false + description: Actionable next step for whoever has to fix this. + - name: details + location: argument + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics. Never contains key values, token + payloads, or any other secret material. + - name: docs + location: argument + type: string + required: false + description: Override the generated documentation URL. + - name: cause + location: argument + type: unknown + required: false + description: Underlying error, when this one wraps another. +properties: + - name: source + location: property + type: '"@supabase/server"' + required: true + description: Always `"@supabase/server"`. + - name: status + location: property + type: number + required: true + description: HTTP status code appropriate for this error. + - name: code + location: property + type: string + required: true + description: Machine-readable error code. + - name: hint + location: property + type: string + required: false + description: Actionable next step, when one applies. + - name: docs + location: property + type: string + required: true + description: Documentation URL for this error's `code`. + - name: details + location: property + type: Record + required: false + description: |- + Structured, non-sensitive diagnostics — accepted auth modes, which + credential headers were present, configured key *names*, JWT header + fields. Never key values or token payloads. + - name: toJSON + location: property + type: () => ErrorPayload + required: true + description: "" +examples: + - id: catching-any-library-error + title: Catching any library error + lang: ts + code: | + import { SupabaseServerError } from '@supabase/server' + + try { + const supabase = createAdminClient() + } catch (e) { + if (e instanceof SupabaseServerError) { + console.error(e.code, e.message, e.hint, e.docs) + return Response.json(e.toJSON(), { status: e.status }) + } + throw e + } +--- diff --git a/docs/reference-beta/definitions/server-unauthorized-response-options.md b/docs/reference-beta/definitions/server-unauthorized-response-options.md new file mode 100644 index 0000000..cce56cd --- /dev/null +++ b/docs/reference-beta/definitions/server-unauthorized-response-options.md @@ -0,0 +1,19 @@ +--- +id: server-unauthorized-response-options +kind: type +category: Types +title: UnauthorizedResponseOptions +symbol: "@supabase/server.UnauthorizedResponseOptions" +summary: Options for `unauthorizedResponse`. +description: Options for `unauthorizedResponse`. +signature: interface UnauthorizedResponseOptions +stability: stable +deprecated: false +properties: + - name: resourceMetadataUrl + location: property + type: string + required: false + description: Absolute URL override for the resource metadata endpoint. +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-unauthorized-response.md b/docs/reference-beta/definitions/server-unauthorized-response.md new file mode 100644 index 0000000..3421518 --- /dev/null +++ b/docs/reference-beta/definitions/server-unauthorized-response.md @@ -0,0 +1,38 @@ +--- +id: server-unauthorized-response +kind: method +category: Middleware +title: unauthorizedResponse +symbol: "@supabase/server.unauthorizedResponse" +summary: '`401` response with a `WWW-Authenticate: Bearer resource_metadata="..."` header (RFC 9728). The metadata URL defaults to the Edge Functions derivation and throws off platform; pass `resourceMetadataUrl` to override for custom setups.' +description: |- + `401` response with a + `WWW-Authenticate: Bearer resource_metadata="..."` header (RFC 9728). + The metadata URL defaults to the Edge Functions derivation and throws off + platform; pass `resourceMetadataUrl` to override for custom setups. +signature: "unauthorizedResponse(req: Request, options?: UnauthorizedResponseOptions): Response" +stability: stable +deprecated: false +parameters: + - name: req + location: argument + type: Request + required: true + description: "" + - name: options + location: argument + type: UnauthorizedResponseOptions + required: false + description: "" + children: + - name: resourceMetadataUrl + location: argument + type: string + required: false + description: Absolute URL override for the resource metadata endpoint. +returns: + type: Response + description: "" +throws: [] +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-unsupported-role-error.md b/docs/reference-beta/definitions/server-unsupported-role-error.md new file mode 100644 index 0000000..bf403e2 --- /dev/null +++ b/docs/reference-beta/definitions/server-unsupported-role-error.md @@ -0,0 +1,17 @@ +--- +id: server-unsupported-role-error +kind: constant +category: Errors +title: UnsupportedRoleError +symbol: "@supabase/server.UnsupportedRoleError" +summary: The caller's verified `role` claim names a Postgres role the middleware will not assume — either one that would bypass RLS, or one it does not support yet. Returned by `withPostgresClient` instead of silently running the query as `anon`. +description: |- + The caller's verified `role` claim names a Postgres role the middleware + will not assume — either one that would bypass RLS, or one it does not + support yet. Returned by `withPostgresClient` instead of silently running + the query as `anon`. +signature: 'const UnsupportedRoleError: "UNSUPPORTED_ROLE"' +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-unusable-credential-error.md b/docs/reference-beta/definitions/server-unusable-credential-error.md new file mode 100644 index 0000000..edd2332 --- /dev/null +++ b/docs/reference-beta/definitions/server-unusable-credential-error.md @@ -0,0 +1,22 @@ +--- +id: server-unusable-credential-error +kind: constant +category: Errors +title: UnusableCredentialError +symbol: "@supabase/server.UnusableCredentialError" +summary: A credential *did* arrive, but not one any accepted auth mode can use — an `sb_*` API key in the `Authorization` header, or a header this library cannot read a bearer token out of (wrong scheme, wrong casing, bare value, empty token). +description: |- + A credential *did* arrive, but not one any accepted auth mode can use — an + `sb_*` API key in the `Authorization` header, or a header this library cannot + read a bearer token out of (wrong scheme, wrong casing, bare value, empty + token). +signature: 'const UnusableCredentialError: "UNUSABLE_CREDENTIAL"' +stability: stable +deprecated: false +examples: [] +--- + +Distinct from `MissingCredentialsError` on purpose. The two +partition the "nothing authenticated" space exactly — nothing arrived vs. +something arrived that could not be used — so the code stays true on its own +when `errors: { detailed: false }` strips `hint` and `details`. diff --git a/docs/reference-beta/definitions/server-url-option.md b/docs/reference-beta/definitions/server-url-option.md new file mode 100644 index 0000000..4cd5b17 --- /dev/null +++ b/docs/reference-beta/definitions/server-url-option.md @@ -0,0 +1,13 @@ +--- +id: server-url-option +kind: type +category: Types +title: UrlOption +symbol: "@supabase/server.UrlOption" +summary: "A configured URL: either a fixed value, or derived per request." +description: "A configured URL: either a fixed value, or derived per request." +signature: "type UrlOption = string | (req: Request) => string" +stability: stable +deprecated: false +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-user-claims.md b/docs/reference-beta/definitions/server-user-claims.md new file mode 100644 index 0000000..9029316 --- /dev/null +++ b/docs/reference-beta/definitions/server-user-claims.md @@ -0,0 +1,44 @@ +--- +id: server-user-claims +kind: type +category: Types +title: UserClaims +symbol: "@supabase/server.UserClaims" +summary: Normalized, camelCase view of the authenticated user's identity. +description: |- + Normalized, camelCase view of the authenticated user's identity. + + Derived from `JWTClaims`. For the full Supabase `User` object + (including email confirmation status, providers, etc.), call + `supabase.auth.getUser()` using the context client. +signature: interface UserClaims +stability: stable +deprecated: false +properties: + - name: id + location: property + type: string + required: true + description: User's unique ID (same as `JWTClaims.sub`). + - name: role + location: property + type: string + required: false + description: Supabase role (e.g. `"authenticated"`). + - name: email + location: property + type: string + required: false + description: User's email address. + - name: appMetadata + location: property + type: Record + required: false + description: Application-level metadata (e.g. roles, permissions). + - name: userMetadata + location: property + type: Record + required: false + description: User-editable profile metadata (e.g. display name, avatar). +examples: [] +--- diff --git a/docs/reference-beta/definitions/server-with-oauth-protected-resource.md b/docs/reference-beta/definitions/server-with-oauth-protected-resource.md new file mode 100644 index 0000000..d730fa4 --- /dev/null +++ b/docs/reference-beta/definitions/server-with-oauth-protected-resource.md @@ -0,0 +1,145 @@ +--- +id: server-with-oauth-protected-resource +kind: method +category: Middleware +title: withOAuthProtectedResource +symbol: "@supabase/server.withOAuthProtectedResource" +summary: Wraps a request handler with OAuth 2.1 Protected Resource behavior (RFC 9728). +description: |- + Wraps a request handler with OAuth 2.1 Protected Resource + behavior (RFC 9728). + + - Serves OAuth Protected Resource Metadata at `GET {resource}/oauth-protected-resource` + (with permissive CORS, including the `OPTIONS` preflight, so browser-based clients can read it) + - Enriches a `401` from the inner handler with `WWW-Authenticate: Bearer resource_metadata="..."`, + unless the handler already set a `WWW-Authenticate` header (its value wins) + - Passes any other path through to the inner handler unchanged (composition, + not routing, decides what happens to it) + - Answers a default URL it cannot derive with the JSON error response + `withSupabase` returns for its own configuration failures (`500`, + `x-supabase-server-error`); a throw from a configured `resourceServer` or + `authorizationServer` function is the caller's and propagates + + The metadata route is matched on the path *suffix*, so **any** `GET` or + `OPTIONS` ending in `/oauth-protected-resource` is answered here and never + reaches the inner handler, at any depth. Other methods pass through. + + Zero-config on Supabase Edge Functions. Elsewhere + `resourceServer` is required and + `authorizationServer` falls back to + `SUPABASE_URL`; one that cannot be resolved is reported as + `MISSING_RESOURCE_SERVER` / `MISSING_AUTHORIZATION_SERVER`. + + Contributes `ctx.oauthProtectedResource` (the resolved metadata URL) to the + downstream context. Nested under `withSupabase`, the key is typed on the + handler's `ctx` when the outermost call is anchored with + `satisfies FetchHandler` — see `withSupabase`'s type note. Placed directly + after `withSupabase` with an auth mode that requires credentials, the + composition is refused when the stack is built, since the gate would + answer discovery and preflight before this middleware runs. +signature: "withOAuthProtectedResource(config?: OAuthProtectedResourceConfig): Entry<{ oauthProtectedResource: OAuthProtectedResourceContribution }>" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: OAuthProtectedResourceConfig + required: false + description: "" + children: + - name: resourceServer + location: argument + type: UrlOption + required: false + description: |- + The resource identifier to advertise — this endpoint's externally-visible + URL, which RFC 9728 §3.3 requires to equal the URL the client called. + + Defaults to the Edge Functions derivation. Required on any other backend, + usually from the request — `(req) => new URL(req.url).origin + '/api/mcp'`. + Unset there, every request other than the metadata route's `OPTIONS` + preflight is answered with a `500` and code `MISSING_RESOURCE_SERVER`. + - name: authorizationServer + location: argument + type: UrlOption + required: false + description: |- + The OAuth 2.1 authorization server to advertise, as an issuer identifier. + + Defaults to the project's Supabase Auth on Edge Functions. Elsewhere it + falls back to `SUPABASE_PUBLIC_URL`, then `SUPABASE_URL`, each with + `/auth/v1` appended; with neither set, the metadata route is answered with + a `500` and code `MISSING_AUTHORIZATION_SERVER`. Pass + `fromSupabaseUrl` for a specific project, or any other issuer + directly. + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in a short-circuit response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +returns: + type: "Entry<{ oauthProtectedResource: OAuthProtectedResourceContribution }>" + description: "" +throws: [] +examples: + - id: supabase-edge-functions-zero-config + title: Supabase Edge Functions — zero config + lang: ts + code: | + import { withOAuthProtectedResource, withSupabase } from '@supabase/server' + + Deno.serve( + withOAuthProtectedResource( + withSupabase({ auth: 'user' }, async (_req, { supabase }) => { + const { data, error } = await supabase.from('items').select('*') + if (error) throw error + return Response.json(data) + }), + ), + ) + - id: any-other-backend + title: Any other backend + lang: ts + code: | + import { withOAuthProtectedResource, fromSupabaseUrl } from '@supabase/server' + + export default { + fetch: withOAuthProtectedResource( + { + resourceServer: (req) => new URL(req.url).origin + '/api/mcp', + authorizationServer: fromSupabaseUrl('https://abc123.supabase.co'), + }, + handler, + ), + } + - id: a-non-supabase-authorization-server + title: A non-Supabase authorization server + lang: ts + code: | + withOAuthProtectedResource( + { + resourceServer: 'https://api.example.com/mcp', + authorizationServer: 'https://example.clerk.accounts.dev', + }, + handler, + ) +--- diff --git a/docs/reference-beta/definitions/server-with-supabase-config.md b/docs/reference-beta/definitions/server-with-supabase-config.md new file mode 100644 index 0000000..d859e8a --- /dev/null +++ b/docs/reference-beta/definitions/server-with-supabase-config.md @@ -0,0 +1,126 @@ +--- +id: server-with-supabase-config +kind: type +category: Types +title: WithSupabaseConfig +symbol: "@supabase/server.WithSupabaseConfig" +summary: Configuration for `withSupabase` and `createSupabaseContext`. +description: |- + Configuration for `withSupabase` and `createSupabaseContext`. + + Controls which auth modes are accepted, environment overrides, and CORS behavior. +signature: interface WithSupabaseConfig extends ShortCircuitConfig +stability: stable +deprecated: false +properties: + - name: auth + location: property + type: AuthConfig + required: false + description: |- + Auth mode(s) to accept. Modes are tried in order — the first match wins. + A mode falls through only when its credential is absent; a present-but-invalid + JWT short-circuits the chain with `InvalidJwtError` (`INVALID_JWT`). + + `"none"` matches unconditionally, so it belongs last in a list or on its + own — see `AuthConfig`. + + Default: `"user"` + - name: allow + location: property + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. The `allow` option + is kept for backward compatibility and will be removed in a future major release. + When both `auth` and `allow` are provided, `auth` takes precedence. It keeps + the older, looser element type so code mid-migration still compiles; `auth` + is where the `AuthConfig` ordering rule is enforced. + - name: audience + location: property + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: property + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: property + type: Partial + required: false + description: |- + Override auto-detected environment variables. Useful for testing + or when running in environments without standard env var support. + - name: cors + location: property + type: 'boolean | Record | "default" | "disabled" | { headers: Record }' + required: false + description: |- + CORS configuration for the `withSupabase` wrapper. + + - `'default'` — uses `@supabase/supabase-js` default CORS headers. + - `'disabled'` — disables CORS handling entirely. + - `{ headers }` — custom CORS headers. + + The boolean (`true`/`false`) and bare `Record` forms are + deprecated but still accepted for backward compatibility. + + Default: `'default'` + - name: supabaseOptions + location: property + type: SupabaseClientOptions + required: false + description: |- + Options forwarded to both internal `createClient()` calls. + + `accessToken` is stripped, and auth settings (`persistSession`, `autoRefreshToken`, + `detectSessionInUrl`) are force-overwritten to server-safe values. + - name: errors + location: property + type: ErrorResponseConfig + required: false + description: How much of an error to include in the response body. + children: + - name: detailed + location: property + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` +examples: + - id: basic-usage + title: Basic usage + lang: ts + code: | + // Require authenticated users, auto-CORS enabled (default) + const config: WithSupabaseConfig = { auth: 'user' } + + // Accept users or service-to-service calls, custom CORS headers + const config: WithSupabaseConfig = { + auth: ['user', 'secret'], + cors: { 'Access-Control-Allow-Origin': 'https://myapp.com' }, + } + + // No auth required, CORS disabled + const config: WithSupabaseConfig = { auth: 'none', cors: 'disabled' } +--- diff --git a/docs/reference-beta/definitions/server-with-supabase.md b/docs/reference-beta/definitions/server-with-supabase.md new file mode 100644 index 0000000..ac8f495 --- /dev/null +++ b/docs/reference-beta/definitions/server-with-supabase.md @@ -0,0 +1,159 @@ +--- +id: server-with-supabase +kind: method +category: Middleware +title: withSupabase +symbol: "@supabase/server.withSupabase" +summary: Wraps a request handler with Supabase auth, client creation, and CORS handling. +description: |- + Wraps a request handler with Supabase auth, client creation, and CORS handling. + + Built for the Web API `Request`/`Response` standard that all modern runtimes + implement natively. Handles CORS preflight, credential verification, + context creation, and error responses. Your handler only runs on successful auth. +signature: "withSupabase(config: WithSupabaseConfig, handler: (req: Request, ctx: NoInfer & SupabaseContext) => Promise): (req: Request, ctx?: Base) => Promise" +stability: stable +deprecated: false +parameters: + - name: config + location: argument + type: WithSupabaseConfig + required: true + description: Auth modes, CORS, and environment overrides. See `WithSupabaseConfig`. + children: + - name: auth + location: argument + type: AuthConfig + required: false + description: |- + Auth mode(s) to accept. Modes are tried in order — the first match wins. + A mode falls through only when its credential is absent; a present-but-invalid + JWT short-circuits the chain with `InvalidJwtError` (`INVALID_JWT`). + + `"none"` matches unconditionally, so it belongs last in a list or on its + own — see `AuthConfig`. + + Default: `"user"` + - name: allow + location: argument + type: AuthModeWithKey | AuthModeWithKey[] + required: false + description: |- + Deprecated. Use `auth` instead. The `allow` option + is kept for backward compatibility and will be removed in a future major release. + When both `auth` and `allow` are provided, `auth` takes precedence. It keeps + the older, looser element type so code mid-migration still compiles; `auth` + is where the `AuthConfig` ordering rule is enforced. + - name: audience + location: argument + type: string | string[] + required: false + description: |- + Accepted `aud` claim value(s) for `user` mode. When set, a token without + `aud` is rejected, and a token whose `aud` is an array passes when any + entry is accepted. + - name: issuer + location: argument + type: string | string[] + required: false + description: |- + Accepted `iss` claim value(s) for `user` mode. When set, a token without + `iss` is rejected. Supabase Auth issues `https://.supabase.co/auth/v1`, + which `fromSupabaseUrl(url)` builds from a project URL. + - name: env + location: argument + type: Partial + required: false + description: |- + Override auto-detected environment variables. Useful for testing + or when running in environments without standard env var support. + - name: cors + location: argument + type: 'boolean | Record | "default" | "disabled" | { headers: Record }' + required: false + description: |- + CORS configuration for the `withSupabase` wrapper. + + - `'default'` — uses `@supabase/supabase-js` default CORS headers. + - `'disabled'` — disables CORS handling entirely. + - `{ headers }` — custom CORS headers. + + The boolean (`true`/`false`) and bare `Record` forms are + deprecated but still accepted for backward compatibility. + + Default: `'default'` + - name: supabaseOptions + location: argument + type: SupabaseClientOptions + required: false + description: |- + Options forwarded to both internal `createClient()` calls. + + `accessToken` is stripped, and auth settings (`persistSession`, `autoRefreshToken`, + `detectSessionInUrl`) are force-overwritten to server-safe values. + - name: errors + location: argument + type: ErrorResponseConfig + required: false + description: How much of an error to include in the response body. + children: + - name: detailed + location: argument + type: boolean + required: false + description: |- + Whether to include the diagnostic fields in the response body. + + `hint` names the likely misconfiguration, `details` reports the endpoint's + accepted auth modes, which credential headers arrived, and the *names* of + configured keys, and `docs` links the relevant reference. All three are + aimed at whoever is building against the endpoint. + + Set to `false` to reduce the body to `code` and `message` alone. The + `x-supabase-server-error` header and the HTTP status are unaffected, and + `message` keeps its `[@supabase/server]` prefix — so the error stays + traceable without the `source` field. + + Default: `true` + - name: handler + location: argument + type: "(req: Request, ctx: NoInfer & SupabaseContext) => Promise" + required: true + description: Receives the `Request` and a fully-initialized `SupabaseContext`. +returns: + type: "(req: Request, ctx?: Base) => Promise" + description: |- + A fetch handler. The optional second parameter is the host's + platform argument (a Workers `env`, a Deno `ServeHandlerInfo`) — when the + runtime supplies one, it is captured as the platform env behind + `@supabase/middleware`'s `getEnv` for any composed middleware. Nested under + another middleware, it is that middleware's accumulated context instead, + which is reused rather than reseeded. At the entry point the request body + is buffered, so a nested middleware and the handler can both read it. + + **Type note.** `Base` carries an upstream middleware's contributions into the + handler's `ctx`: with `satisfies FetchHandler` on the outermost call, + `withOAuthProtectedResource(withSupabase(config, handler))` types + `ctx.oauthProtectedResource` with no annotation. The anchor is the same one + the engine already asks of nested stacks (it also gates collision detection + there): `Base` flows from the contextual return type, and without the anchor + the outer call resolves before it can push, so `Base` stays the empty + upstream and upstream keys are absent from `ctx`. Supplying `Database` explicitly + (`withSupabase(...)`) also defaults every later type parameter, `Base` + included; in that case annotate both (`withSupabase(...)`) + or read the upstream key through a cast. +throws: [] +examples: + - id: basic-usage + title: Basic usage + lang: ts + code: | + import { withSupabase } from '@supabase/server' + + export default { + fetch: withSupabase({ auth: 'user' }, async (req, ctx) => { + const { data } = await ctx.supabase.rpc('get_my_profile') + return Response.json(data) + }), + } +--- diff --git a/package.json b/package.json index 1510490..f4834ef 100644 --- a/package.json +++ b/package.json @@ -179,6 +179,8 @@ "check-exports": "attw --pack .", "dev": "tsdown --watch", "docs": "typedoc", + "docs:check": "node scripts/check-reference-beta.mjs", + "docs:reference-beta": "typedoc && node scripts/generate-reference-beta.mjs && pnpm run docs:check", "format": "prettier --write .", "gen:env": "bash e2e/scripts/gen-env.sh", "lint": "eslint src examples", @@ -237,6 +239,7 @@ "@types/node": "^26.0.1", "@types/pg": "^8.11.0", "@types/supertest": "^7.2.0", + "ajv": "^8.20.0", "elysia": "^1.4.0", "eslint": "^10.0.2", "h3": "2.0.1-rc.20", @@ -254,7 +257,8 @@ "typescript": "^5.9.3", "typescript-eslint": "^8.56.1", "unplugin-swc": "^1.5.9", - "vitest": "^5.0.0" + "vitest": "^5.0.0", + "yaml": "^2.8.3" }, "dependencies": { "@supabase/middleware": "^1.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7cd1a19..d104955 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -57,6 +57,9 @@ importers: '@types/supertest': specifier: ^7.2.0 version: 7.2.0 + ajv: + specifier: ^8.20.0 + version: 8.20.0 elysia: specifier: ^1.4.0 version: 1.4.29(@sinclair/typebox@0.34.49)(exact-mirror@1.0.0)(file-type@21.3.4)(openapi-types@12.1.3)(typescript@5.9.3) @@ -111,6 +114,9 @@ importers: vitest: specifier: ^5.0.0 version: 5.0.0(@types/node@26.0.1)(vite@7.3.2(@types/node@26.0.1)(jiti@2.7.0)(lightningcss@1.33.0)(yaml@2.8.3)) + yaml: + specifier: ^2.8.3 + version: 2.8.3 examples: devDependencies: @@ -1499,9 +1505,6 @@ packages: ajv@6.14.0: resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} - ajv@8.18.0: - resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==} - ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} @@ -3557,7 +3560,7 @@ snapshots: '@commitlint/config-validator@20.4.0': dependencies: '@commitlint/types': 20.4.0 - ajv: 8.18.0 + ajv: 8.20.0 '@commitlint/ensure@20.4.1': dependencies: @@ -4663,13 +4666,6 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 - ajv@8.18.0: - dependencies: - fast-deep-equal: 3.1.3 - fast-uri: 3.1.8 - json-schema-traverse: 1.0.0 - require-from-string: 2.0.2 - ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 diff --git a/scripts/check-reference-beta.mjs b/scripts/check-reference-beta.mjs new file mode 100644 index 0000000..7a3e034 --- /dev/null +++ b/scripts/check-reference-beta.mjs @@ -0,0 +1,68 @@ +// Validates every generated docs/reference-beta/definitions/*.md against the +// docs project's frontmatter schema (docs/reference-beta/definition.schema.json, +// a vendored copy of definition.schema.json from the supabase docs app). +// +// Beyond the schema, `id` must equal the file name — JSON Schema can't express +// that. Exits non-zero when any definition is invalid. +// +// Run after generating: `pnpm docs:reference-beta` (which runs this) or +// `pnpm docs:check`. + +import { readdirSync, readFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +import Ajv from 'ajv/dist/2020.js' +import { parse } from 'yaml' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const dir = resolve(root, 'docs/reference-beta/definitions') +const schema = JSON.parse( + readFileSync(resolve(root, 'docs/reference-beta/definition.schema.json')), +) + +const validate = new Ajv({ allErrors: true }).compile(schema) + +const files = readdirSync(dir).filter((f) => f.endsWith('.md')) +if (files.length === 0) { + console.error(`No definitions found in ${dir} — run pnpm docs:reference-beta`) + process.exit(1) +} + +let invalid = 0 +for (const file of files) { + const errors = [] + const match = readFileSync(resolve(dir, file), 'utf8').match( + /^---\n([\s\S]*?)\n---/, + ) + if (!match) { + errors.push('missing YAML frontmatter') + } else { + const data = parse(match[1]) + if (!validate(data)) { + errors.push( + ...validate.errors.map( + (e) => + `${e.instancePath || '/'} ${e.message}${ + e.params.additionalProperty + ? `: ${e.params.additionalProperty}` + : '' + }`, + ), + ) + } + if (data?.id !== file.replace(/\.md$/, '')) { + errors.push(`id "${data?.id}" does not match the file name`) + } + } + if (errors.length) { + invalid++ + console.error(`✗ ${file}\n${errors.map((e) => ` ${e}`).join('\n')}`) + } +} + +if (invalid) { + console.error(`\n${invalid} of ${files.length} definitions are invalid`) + process.exit(1) +} +console.log(`All ${files.length} definitions match the schema`) diff --git a/scripts/generate-reference-beta.mjs b/scripts/generate-reference-beta.mjs new file mode 100644 index 0000000..5b24d01 --- /dev/null +++ b/scripts/generate-reference-beta.mjs @@ -0,0 +1,297 @@ +// Experiment: turns typedoc's JSON output into one de-referenced Markdown file +// per documented definition under docs/reference-beta/definitions/. +// +// Each file is YAML frontmatter (the whole definition) plus optional notes. +// "De-referenced" means everything a reader needs is inlined: option interfaces +// become nested `children`, and `{@link X}` becomes the name of X. +// +// Run after typedoc has produced api-docs/spec.json: `pnpm docs:reference-beta`. + +import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { stringify } from 'yaml' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const outDir = resolve(root, 'docs/reference-beta/definitions') +const spec = JSON.parse( + readFileSync(resolve(root, 'api-docs/spec.json'), 'utf8'), +) + +// Every declaration by id, so references and links can be followed. +const byId = new Map() +const index = (r) => { + byId.set(r.id, r) + r.children?.forEach(index) +} +index(spec) +// Follows re-exports (`export { X } from ...`) to the real declaration. +const decl = (id) => { + const d = byId.get(id) + return d?.variant === 'reference' ? decl(d.target) : d +} + +const slug = (s) => + s + .replace(/([a-z\d])([A-Z])/g, '$1-$2') + .toLowerCase() + .replace(/[^a-z\d]+/g, '-') + .replace(/^-|-$/g, '') + +// Comment parts -> plain Markdown; links are replaced by the target's name. +const text = (parts = []) => + parts + .map((p) => + p.kind === 'inline-tag' + ? `\`${decl(p.target)?.name ?? p.text}\`` + : p.text, + ) + .join('') + .trim() + +// --- types -> strings ------------------------------------------------------- + +const sigType = (s) => `(${params(s)}) => ${type(s.type)}` +const params = (s) => + (s.parameters ?? []) + .map( + (p) => + `${p.flags.isRest ? '...' : ''}${p.name}${p.flags.isOptional ? '?' : ''}: ${type(p.type)}`, + ) + .join(', ') +const memberType = (m) => (m.type ? type(m.type) : sigType(m.signatures[0])) + +const type = (t) => { + switch (t.type) { + case 'intrinsic': + return t.name + case 'literal': + return JSON.stringify(t.value) + case 'reference': + return t.typeArguments + ? `${t.name}<${t.typeArguments.map(type).join(', ')}>` + : t.name + case 'array': { + const e = type(t.elementType) + return /[|&]|=>/.test(e) ? `(${e})[]` : `${e}[]` + } + case 'union': + return t.types.map(type).join(' | ') + case 'intersection': + return t.types.map(type).join(' & ') + case 'typeOperator': + return `${t.operator} ${type(t.target)}` + case 'tuple': + return `[${(t.elements ?? []).map(type).join(', ')}]` + case 'rest': + return `...${type(t.elementType)}` + case 'templateLiteral': + return `\`${t.head}${t.tail.map(([ty, s]) => `\${${type(ty)}}${s}`).join('')}\`` + case 'reflection': { + const d = t.declaration + if (d.signatures) return sigType(d.signatures[0]) + const props = (d.children ?? []).map( + (c) => `${c.name}${c.flags.isOptional ? '?' : ''}: ${memberType(c)}`, + ) + return props.length ? `{ ${props.join('; ')} }` : '{}' + } + default: + return t.type + } +} + +// --- parameters --------------------------------------------------------------- + +// Summary plus the tags that don't have a field of their own in the schema. +const describe = (comment) => + [ + text(comment?.summary), + ...(comment?.blockTags ?? []) + .filter((b) => b.tag === '@deprecated' || b.tag === '@defaultValue') + .map( + (b) => + `${b.tag === '@deprecated' ? 'Deprecated.' : 'Default:'} ${text(b.content)}`, + ), + ] + .filter(Boolean) + .join('\n\n') + +// Nested fields of a type: inlines interfaces and object type aliases. +const members = (t, seen, location) => { + if (t?.type === 'intersection') + return t.types.flatMap((x) => members(x, seen, location)) + if (t?.type === 'reflection') + return fields(t.declaration.children, seen, location) + if (t?.type === 'reference' && !seen.includes(t.target)) { + const d = decl(t.target) + const next = [...seen, t.target] + if (d?.kind === 256) return fields(d.children, next, location) // interface + if (d?.kind === 2097152) return members(d.type, next, location) // type alias + } + return [] +} + +const fields = (list = [], seen, location) => + list.map((p) => field(p, seen, location)) + +// `location` is `argument` for call parameters and `property` for the members +// of types and classes; nested children inherit it. +const field = (p, seen, location = 'argument') => { + const children = members(p.type, seen, location) + return { + name: p.name, + location, + type: memberType(p), + // A parameter's default makes it optional; a property's is just its initializer. + required: + !p.flags.isOptional && + (location === 'property' || p.defaultValue === undefined), + description: describe(p.comment), + ...(children.length && { children }), + } +} + +// `const withX = defineMiddleware(...)` is typed as the callable interface +// `Middleware`, which typedoc doesn't expand. +// Synthesize its config-only call, `withX(config?) => Entry<{ [Key]: Contribution }>`. +const middlewareSig = (d) => { + const [key, config, , contribution] = d.type.typeArguments + const all = config.type === 'union' ? config.types : [config] + const [cfg] = all.filter((t) => !['void', 'undefined'].includes(t.name)) + return { + parameters: cfg + ? [{ name: 'config', type: cfg, flags: { isOptional: all.length > 1 } }] + : [], + type: { + type: 'intrinsic', + name: `Entry<{ ${key.value}: ${type(contribution)} }>`, + }, + } +} + +const signatureOf = (d) => + d.signatures?.[0] ?? + d.type?.declaration?.signatures?.[0] ?? + (d.type?.package === '@supabase/middleware' && middlewareSig(d)) + +// --- definitions -------------------------------------------------------------- + +const generics = (x) => + x.typeParameters ? `<${x.typeParameters.map((p) => p.name).join(', ')}>` : '' + +const toDefinition = (mod, d) => { + const callable = d.kind === 64 || d.kind === 32 + const sig = callable && signatureOf(d) + const ctor = d.children?.find((c) => c.kind === 512)?.signatures[0] + const comment = sig?.comment ?? d.comment + const tags = (name) => comment?.blockTags?.filter((b) => b.tag === name) ?? [] + + // Only what the library files under a @category is public documentation. + const category = text(tags('@category')[0]?.content) + if (!category) return null + + const mods = comment?.modifierTags ?? [] + const description = text(comment?.summary) + const modPath = mod.name === 'index' ? '' : mod.name + const extended = d.extendedTypes?.map(type).join(', ') + + const [deprecated] = tags('@deprecated') + const remarks = tags('@remarks').map((t) => text(t.content)) + const notes = [ + deprecated && `> **Deprecated:** ${text(deprecated.content)}`, + ...remarks, + ].filter(Boolean) + + // Members of classes, interfaces, type aliases and object constants. + const properties = sig + ? [] + : d.kind === 128 + ? fields( + d.children.filter((c) => c.kind !== 512), + [d.id], + 'property', + ) + : members( + d.kind === 32 ? d.type : { type: 'reference', target: d.id }, + [], + 'property', + ) + + const frontmatter = { + id: slug(`${modPath || 'server'}-${d.name}`), + kind: sig + ? 'method' + : ({ 128: 'class' }[d.kind] ?? (d.kind === 32 ? 'constant' : 'type')), + category, + title: d.name, + symbol: `${['@supabase/server', modPath].filter(Boolean).join('/')}.${d.name}`, + summary: description.split('\n\n')[0].replace(/\n/g, ' '), + description, + signature: sig + ? `${d.name}${generics(sig)}(${params(sig)}): ${type(sig.type)}` + : d.kind === 2097152 + ? `type ${d.name}${generics(d)} = ${type(d.type)}` + : d.kind === 32 + ? `const ${d.name}: ${type(d.type)}` + : `${d.kind === 128 ? 'class' : 'interface'} ${d.name}${generics(d)}${extended ? ` extends ${extended}` : ''}`, + stability: mods.some((m) => ['@alpha', '@experimental'].includes(m)) + ? 'experimental' + : mods.includes('@beta') + ? 'beta' + : 'stable', + deprecated: Boolean(deprecated), + ...((sig || ctor) && { + parameters: ((sig || ctor).parameters ?? []).map((p) => field(p, [])), + }), + ...(properties.length && { properties }), + ...(sig && { + returns: { + type: type(sig.type), + description: text(tags('@returns')[0]?.content), + }, + throws: tags('@throws').map((t) => { + const [first, ...rest] = t.content + return first.kind === 'inline-tag' + ? { + type: decl(first.target)?.name ?? first.text, + description: text(rest), + } + : { description: text(t.content) } + }), + }), + examples: tags('@example').map((e, i) => { + const code = text(e.content) + const fence = code.match(/```(\w*)\n([\s\S]*?)\n```/) + const title = e.name ?? `Example ${i + 1}` + return { + id: slug(title), + title, + lang: fence?.[1] || 'ts', + code: `${fence?.[2] ?? code}\n`, + } + }), + } + + const body = notes.length ? `\n${notes.join('\n\n')}\n` : '' + return { + id: frontmatter.id, + content: `---\n${stringify(frontmatter, { lineWidth: 0 })}---\n${body}`, + } +} + +rmSync(outDir, { recursive: true, force: true }) +mkdirSync(outDir, { recursive: true }) + +let count = 0 +for (const mod of spec.children) { + for (const d of mod.children ?? []) { + // Re-exports have no comment of their own, so they drop out with the + // uncategorized ones; they're documented under their original module. + const def = toDefinition(mod, d) + if (!def) continue + writeFileSync(resolve(outDir, `${def.id}.md`), def.content) + count++ + } +} +console.log(`Wrote ${count} definitions to ${outDir}`)