Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,12 +263,12 @@ withSupabase(

`env` overrides environment variable resolution. Defaults to reading `SUPABASE_URL`, `SUPABASE_PUBLISHABLE_KEYS`, `SUPABASE_SECRET_KEYS`, and `SUPABASE_JWKS` from the runtime environment.

`middleware` composes additional entries onto the context — they run after the Supabase context is established and contribute their own typed keys. The first-party entries live on the `@supabase/server/middleware/*` subpaths; see [Postgres](#postgres-rls-scoped-queries).
Called with config only, `withSupabase(config)` returns an entry for `pipeline` from `@supabase/middleware`. Entries placed after it in the array receive the Supabase context and contribute their own typed keys; entries placed before it run ahead of the auth gate. The first-party entries live on the `@supabase/server/middleware/*` subpaths; see [Postgres](#postgres-rls-scoped-queries).

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

## Framework Adapters

Expand Down Expand Up @@ -447,20 +447,21 @@ export default {

## Postgres (RLS-scoped queries)

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

When PostgREST isn't the right tool — joins, CTEs, window functions — `withPostgresClient` puts a direct Postgres connection on `ctx.postgres`, scoped to the caller by RLS:

```ts
import { pipeline } from '@supabase/middleware'
import { withSupabase } from '@supabase/server'
import { withPostgresClient } from '@supabase/server/middleware/postgres'

export default {
fetch: withSupabase(
{ auth: 'user', middleware: [withPostgresClient()] },
fetch: pipeline(
[withSupabase({ auth: 'user' }), withPostgresClient()],
async (_req, ctx) => {
// No WHERE clause — RLS scopes the rows to the caller.
const notes = await ctx.postgres.query`select id, body from notes`
Expand All @@ -477,10 +478,7 @@ When a handler legitimately needs to cross user boundaries, `withPostgresAdminCl
```ts
import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin'

withSupabase(
{ auth: 'secret', middleware: [withPostgresAdminClient()] },
handler,
)
pipeline([withSupabase({ auth: 'secret' }), withPostgresAdminClient()], handler)
```

The pair mirrors `ctx.supabase` / `ctx.supabaseAdmin`, and they share one connection pool. Keeping them as two middleware is deliberate: bypassing RLS stays visible at the composition site, so you can grep for every handler that can do it.
Expand Down
76 changes: 43 additions & 33 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,37 @@ Wraps a fetch handler with auth, CORS, and client creation. Returns a `(req: Req
- Verifies credentials per `config.auth`
- Returns JSON error response on auth failure
- Adds CORS headers to all responses
- Buffers the request body at the entry point, so composed middleware and the handler can each read it
- Reading the raw `req.body` stream bypasses the buffer, so a handler that forwards the request with `fetch()` after another layer has read the body rebuilds it from `await req.arrayBuffer()`.

A `middleware` array selects a second overload, which accumulates each entry's
contribution onto the handler's `ctx`:
```ts
function withSupabase<Database = unknown>(
config: WithSupabaseConfig,
): Entry<SupabaseContext<Database>>
```

Called with config only, `withSupabase` is an entry for `pipeline` from `@supabase/middleware`. Position decides what runs before and after the auth gate. A config carrying a `middleware` key is refused when the stack is built; entries compose through `pipeline` or nesting:

```ts
function withSupabase<
Database = unknown,
const Entries extends readonly Entry[] = readonly Entry[],
>(
config: WithSupabaseConfig & { middleware: Entries },
handler: (
req: Request,
ctx: SupabaseContext<Database> & MiddlewareCtx<Entries>,
) => Promise<Response>,
): (req: Request) => Promise<Response>
import { pipeline } from '@supabase/middleware'
import { withOAuthProtectedResource, withSupabase } from '@supabase/server'
import { withPostgresClient } from '@supabase/server/middleware/postgres'

pipeline(
[
withOAuthProtectedResource(),
withSupabase({ auth: 'user' }),
withPostgresClient(),
],
handler,
)
```

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
Entries before `withSupabase` see every request, including unauthenticated ones, and observe its `401` responses on the way out. Entries after it receive the full `SupabaseContext` and may declare prerequisites on its keys; an entry contributing one of those keys is a compile-time conflict. Nesting works the same way: `withOAuthProtectedResource(withSupabase(config, handler))` places the OAuth middleware ahead of the gate, `withSupabase(config, withPostgresClient(handler))` places Postgres behind it. Placing `withOAuthProtectedResource` directly after `withSupabase` with an auth mode that requires credentials is refused when the stack is built; a pre-auth middleware separated from `withSupabase` by another entry is not detected and must be ordered by hand.

> **Alpha.** The entry form and the `@supabase/server/middleware/*` subpaths
> track `@supabase/middleware` 0.x — entry shapes and context keys may change
> between 0.x releases. Everything else in `@supabase/server` is stable.

### createSupabaseContext

Expand Down Expand Up @@ -189,10 +199,10 @@ Defaults to `auth: 'user'` when config is omitted.

## @supabase/server/middleware/claims

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

### withClaims

Expand Down Expand Up @@ -232,10 +242,10 @@ Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` (https endpoint

## @supabase/server/middleware/required-claims

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

### withRequiredClaims

Expand Down Expand Up @@ -273,7 +283,7 @@ pipeline([withRequiredClaims(), withPostgresClient()], async (req, ctx) => {

The gate's 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 gate's short-circuit responses.

Inside `withSupabase` the context already carries verified `jwtClaims`, so composing the gate through the `middleware` option is a compile-time conflict. Use `withSupabase({ auth: 'user' })` to gate that path.
After `withSupabase` in a `pipeline` the context already carries verified `jwtClaims`, so placing the gate there is a compile-time conflict. Use `withSupabase({ auth: 'user' })` to gate that path.

The gate contributes `jwtClaims` and nothing else. A handler that needs the full `SupabaseContext` behind an auth gate (for example `ctx.userClaims` or `ctx.authMode`, which no composable entry contributes) uses `withSupabase({ auth: 'user' })` directly. A host that takes an entries array can wrap it as the sole entry. `cors: 'disabled'` leaves CORS handling to the host:

Expand All @@ -296,10 +306,10 @@ Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` (https endpoint

## @supabase/server/middleware/postgres

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

### withPostgresClient

Expand Down Expand Up @@ -397,10 +407,10 @@ The minimal claims shape `withPostgresClient` requires upstream at `ctx.jwtClaim

## @supabase/server/middleware/postgres-admin

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

### withPostgresAdminClient

Expand Down
31 changes: 20 additions & 11 deletions docs/postgres.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Postgres (`ctx.postgres`)

> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*`
> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and
> config options may change between 0.x releases. Everything else in
> `@supabase/server` is stable.
> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the
> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x —
> entry shapes and context keys may change between 0.x releases. The
> `withSupabase(config, handler)` form is stable.

Two middleware give you a direct Postgres connection, mirroring the `ctx.supabase` / `ctx.supabaseAdmin` pair:

Expand All @@ -17,12 +17,13 @@ Reach for the scoped one by default. The admin one is a deliberate opt-out, cove
`withPostgresClient` puts a direct Postgres connection on `ctx.postgres`, scoped to the calling user by RLS. It is the safe version of "authenticate, then query as the user": you write plain SQL, and Postgres — not your application code — decides which rows the caller may see.

```ts
import { pipeline } from '@supabase/middleware'
import { withSupabase } from '@supabase/server'
import { withPostgresClient } from '@supabase/server/middleware/postgres'

export default {
fetch: withSupabase(
{ auth: 'user', middleware: [withPostgresClient()] },
fetch: pipeline(
[withSupabase({ auth: 'user' }), withPostgresClient()],
async (_req, ctx) => {
// No WHERE clause — RLS scopes the rows to the caller.
const notes = await ctx.postgres.query`select id, body from notes`
Expand Down Expand Up @@ -136,10 +137,10 @@ Reach for those helpers rather than reading settings by hand. In particular, the

`withPostgresClient` needs the caller's verified claims at `ctx.jwtClaims`. That prerequisite is enforced at compile time, so there are exactly two ways to satisfy it.

**Inside `withSupabase`** — the context already carries `jwtClaims`, so compose it directly:
**After `withSupabase`** — the context already carries `jwtClaims`, so place it next in the array:

```ts
withSupabase({ auth: 'user', middleware: [withPostgresClient()] }, handler)
pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], handler)
```

**Standalone** — in a Supabase-agnostic `pipeline`, pair it with [`withClaims`](../src/middleware/claims/index.ts), which verifies the Bearer token against the project JWKS:
Expand Down Expand Up @@ -180,12 +181,13 @@ Without the grant the query fails with `permission denied` (SQLSTATE `42501`) _b
When a handler legitimately needs to cross user boundaries — an admin dashboard, a cron aggregate, a background job — compose `withPostgresAdminClient` instead. It contributes `ctx.postgresAdmin`, which runs queries as-is under the connection-string role: no claim injection, no role switch, no wrapping transaction.

```ts
import { pipeline } from '@supabase/middleware'
import { withSupabase } from '@supabase/server'
import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin'

export default {
fetch: withSupabase(
{ auth: 'secret', middleware: [withPostgresAdminClient()] },
fetch: pipeline(
[withSupabase({ auth: 'secret' }), withPostgresAdminClient()],
async (_req, ctx) => {
const rows = await ctx.postgresAdmin
.query`select user_id, count(*) from notes group by user_id`
Expand All @@ -200,7 +202,14 @@ Unlike the scoped half it declares **no upstream prerequisite** — it never rea
Compose both when a handler needs each in turn. They share one pool, and `ctx.postgres` stays RLS-scoped regardless:

```ts
middleware: [withPostgresClient(), withPostgresAdminClient()]
pipeline(
[
withSupabase({ auth: 'user' }),
withPostgresClient(),
withPostgresAdminClient(),
],
handler,
)
```

Two things worth being deliberate about:
Expand Down
2 changes: 1 addition & 1 deletion e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Run a single adapter with `pnpm test:e2e h3`.
client is not scoped to the caller)
- `apps/core/app.ts` — same surface on the core `withSupabase(config, handler)`
fetch wrapper (no adapter) — what an Edge Function deploys, running on Node.
Plus `GET /my-notes-pg` (user, `middleware: [withPostgresClient()]` — a real `pg`
Plus `GET /my-notes-pg` (user, `pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], …)` — a real `pg`
connection, same unfiltered query, rows scoped by RLS alone). Only the core
and edge apps carry this route: `pg` needs raw TCP, which is precisely the
runtime claim under test.
Expand Down
12 changes: 7 additions & 5 deletions e2e/apps/core/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// The core wrapper has no router, so routes are dispatched on pathname and
// each auth mode gets its own wrapped handler.
import { withSupabase } from '../../../dist/index.mjs'
import { pipeline } from '@supabase/middleware'
import { withPostgresClient } from '../../../dist/middleware/postgres/index.mjs'
import { withPostgresAdminClient } from '../../../dist/middleware/postgres-admin/index.mjs'
import type { NoteRow } from '../notes.ts'
Expand Down Expand Up @@ -53,11 +54,12 @@ const userHandler = withSupabase({ auth: 'user' }, async (req, ctx) => {
// It carries no interpolation, so there is nothing to parameterize.
const PG_QUERY = 'select id, user_id, body from notes order by created_at'

const postgresHandler = withSupabase(
{
auth: 'user',
middleware: [withPostgresClient(), withPostgresAdminClient()],
},
const postgresHandler = pipeline(
[
withSupabase({ auth: 'user' }),
withPostgresClient(),
withPostgresAdminClient(),
],
async (req, ctx) => {
const { pathname } = new URL(req.url)
if (pathname === '/all-notes-pg') {
Expand Down
2 changes: 1 addition & 1 deletion e2e/supabase/functions/server-e2e/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"@supabase/server/middleware/postgres-admin": "../_vendor/package/dist/middleware/postgres-admin/index.mjs",
"@supabase/supabase-js": "npm:@supabase/supabase-js@2",
"@supabase/supabase-js/cors": "npm:@supabase/supabase-js@2/cors",
"@supabase/middleware": "npm:@supabase/middleware@0.3.1",
"@supabase/middleware": "npm:@supabase/middleware@0.5.0",
"jose": "npm:jose@6",
"pg": "npm:pg@8"
}
Expand Down
15 changes: 7 additions & 8 deletions e2e/supabase/functions/server-e2e/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { withSupabase } from '@supabase/server'
import { withPostgresClient } from '@supabase/server/middleware/postgres'
import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin'
import { pipeline } from '@supabase/middleware'

const COLUMNS = 'id, user_id, body'

Expand Down Expand Up @@ -96,14 +97,12 @@ const PG_QUERY = `select ${COLUMNS} from notes order by created_at`
// Both halves composed together, running the identical query: /my-notes-pg is
// RLS-scoped, /all-notes-pg bypasses RLS. Same security boundary as the core
// app, but on the real Deno runtime.
const postgresHandler = withSupabase(
{
auth: 'user',
middleware: [
withPostgresClient(pgConfig),
withPostgresAdminClient(pgConfig),
],
},
const postgresHandler = pipeline(
[
withSupabase({ auth: 'user' }),
withPostgresClient(pgConfig),
withPostgresAdminClient(pgConfig),
],
async (req, ctx) => {
if (route(req) === '/all-notes-pg') {
return Response.json(await ctx.postgresAdmin.queryRaw(PG_QUERY))
Expand Down
11 changes: 2 additions & 9 deletions jsr.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,7 @@
"./oauth-protected-resource": "./src/oauth-protected-resource/index.ts"
},
"publish": {
"include": [
"src/**/*.ts",
"README.md",
"LICENSE"
],
"exclude": [
"src/**/*.test.ts",
"src/**/*.spec.ts"
]
"include": ["src/**/*.ts", "README.md", "LICENSE"],
"exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"]
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@
"vitest": "^4.1.0"
},
"dependencies": {
"@supabase/middleware": "^0.4.0",
"@supabase/middleware": "^0.5.0",
"jose": "^6.2.0"
}
}
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading