Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ No. `@supabase/ssr` handles cookie-based session management for frameworks like

| Export | What's in it |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `@supabase/server` | `withSupabase`, `createSupabaseContext` |
| `@supabase/server` | `withSupabase`, `createWithSupabase`, `createSupabaseContext` |
| `@supabase/server/core` | `verifyAuth`, `verifyCredentials`, `extractCredentials`, `createContextClient`, `createAdminClient`, `resolveEnv` |
| `@supabase/server/adapters/hono` | `withSupabase` (Hono middleware) |
| `@supabase/server/adapters/h3` | `withSupabase` (H3 / Nuxt middleware) |
Expand Down
30 changes: 30 additions & 0 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Wraps a fetch handler with auth, CORS, and client creation. Returns a `(req: Req
- 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()`.

Passing `Database` explicitly (`withSupabase<Database>(...)`) is deprecated in both forms. Choose it once with [`createWithSupabase`](#createwithsupabase) instead.

```ts
function withSupabase<Database = UntypedDatabase>(
config: WithSupabaseConfig,
Expand All @@ -49,6 +51,34 @@ pipeline(

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.

### createWithSupabase

```ts
function createWithSupabase<Database = UntypedDatabase>(): Composite<
SupabaseContext<Database>,
WithSupabaseConfig,
Record<never, never>
>
```

Returns a `withSupabase` whose `ctx.supabase` and `ctx.supabaseAdmin` are `SupabaseClient<Database>`. Call it once at module scope and use the result in both forms, `withSupabase(config, handler)` and `withSupabase(config)` as a `pipeline` entry. It is built from the same parts as `withSupabase` and behaves the same at runtime.

```ts
import { createWithSupabase } from '@supabase/server'
import type { Database } from './database.types.ts'

const withSupabase = createWithSupabase<Database>()

export default {
fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => {
const { data } = await ctx.supabase.from('todos').select('id, title')
return Response.json(data)
}),
}
```

The return type is `Composite` from `@supabase/middleware`, so the engine's composite checks apply: a middleware placed below it that contributes one of its keys fails to compile, in a `pipeline` and in a nested stack anchored with `satisfies FetchHandler`.

### createSupabaseContext

```ts
Expand Down
11 changes: 8 additions & 3 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ An MCP server your app exposes to its users is an HTTP endpoint that MCP clients

```ts
import { pipeline } from '@supabase/middleware'
import { withOAuthProtectedResource, withSupabase } from '@supabase/server'
import {
createWithSupabase,
withOAuthProtectedResource,
} from '@supabase/server'
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'
import { z } from 'zod/v4'
import type { Database } from './database.types'

const withSupabase = createWithSupabase<Database>()

export default {
fetch: pipeline(
[withOAuthProtectedResource(), withSupabase<Database>({ auth: 'user' })],
[withOAuthProtectedResource(), withSupabase({ auth: 'user' })],
async (req, { supabase }) => {
const handler = createMcpHandler(
() => {
Expand Down Expand Up @@ -44,7 +49,7 @@ export default {
}
```

Pass the `Database` generic (from `supabase gen types typescript`) when tools write. Without it the client is `SupabaseClient<unknown>` and `insert({ title })` fails type-checking with the argument resolved to `never[]`; reads compile either way.
Choose `Database` (from `supabase gen types typescript`) with `createWithSupabase` when tools write. Without it the client is `SupabaseClient<unknown>` and `insert({ title })` fails type-checking with the argument resolved to `never[]`; reads compile either way.

## The two entries

Expand Down
40 changes: 34 additions & 6 deletions docs/typescript-generics.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@ This produces a `Database` type that describes your schema.

## Using with withSupabase

Choose `Database` once with `createWithSupabase`, at module scope, and use the result wherever you'd use `withSupabase`:

```ts
import { withSupabase } from '@supabase/server'
import { createWithSupabase } from '@supabase/server'
import type { Database } from './database.types.ts'

const withSupabase = createWithSupabase<Database>()

export default {
fetch: withSupabase<Database>({ auth: 'user' }, async (_req, ctx) => {
// ctx.supabase is SupabaseClient<Database>
fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => {
// ctx.supabase and ctx.supabaseAdmin are SupabaseClient<Database>
// Fully typed: column names, return type, etc.
const { data } = await ctx.supabase
.from('todos')
Expand All @@ -35,6 +39,28 @@ export default {
}
```

The result composes the same way `withSupabase` does: nested around a handler or another middleware, or as a `pipeline` entry, where the entries after it see the typed clients.

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

export default {
fetch: pipeline(
[withSupabase({ auth: 'user' }), withPostgresClient()],
async (_req, ctx) => {
// ctx.supabase is SupabaseClient<Database>; ctx.postgres is RLS-scoped too
const { data } = await ctx.supabase.from('todos').select('id, title')
return Response.json(data)
},
),
}
```

`createWithSupabase` returns a `Composite` from `@supabase/middleware`, so the engine checks it like any composite. A middleware below it that contributes one of its keys fails to compile: `withClaims()` contributes `jwtClaims`, which it already provides. In a nested stack, the check needs `satisfies FetchHandler` on the outermost call.

Passing `Database` to `withSupabase` itself (`withSupabase<Database>(config, handler)`) is deprecated. It also fixes `withSupabase`'s second type parameter to its default, so keys from a middleware wrapped around it are missing from `ctx`.

## Using with createSupabaseContext

```ts
Expand Down Expand Up @@ -147,11 +173,13 @@ app.listen(3000)
If your tables are in a schema other than `public`, pass it via `supabaseOptions`:

```ts
import { withSupabase } from '@supabase/server'
import { createWithSupabase } from '@supabase/server'
import type { Database } from './database.types.ts'

const withSupabase = createWithSupabase<Database>()

export default {
fetch: withSupabase<Database>(
fetch: withSupabase(
{
auth: 'user',
supabaseOptions: { db: { schema: 'api' } },
Expand All @@ -173,7 +201,7 @@ export default {
- Auth settings (`persistSession`, `autoRefreshToken`, `detectSessionInUrl`) are force-set to server-safe values

```ts
withSupabase<Database>(
withSupabase(
{
auth: 'user',
supabaseOptions: {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
* @packageDocumentation
*/

export { withSupabase } from './with-supabase.js'
export { createWithSupabase, withSupabase } from './with-supabase.js'
export { createSupabaseContext } from './create-supabase-context.js'

export { withOAuthProtectedResource } from './oauth-protected-resource/with-oauth-protected-resource.js'
Expand Down
183 changes: 182 additions & 1 deletion src/with-supabase.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
import { defineMiddleware, getEnv, pipeline } from '@supabase/middleware'
import type { FetchHandler } from '@supabase/middleware'
import type { SupabaseClient } from '@supabase/supabase-js'
import { exportJWK, generateKeyPair, SignJWT } from 'jose'

import { _resetAllowDeprecationWarned } from './core/utils/deprecation.js'
Expand All @@ -16,7 +17,7 @@ import type { JWTClaims, SupabaseContext, WithSupabaseConfig } from './types.js'
import { withClaims } from './middleware/claims/index.js'
import { withPostgresClient } from './middleware/postgres/index.js'
import { withOAuthProtectedResource } from './oauth-protected-resource/with-oauth-protected-resource.js'
import { withSupabase } from './with-supabase.js'
import { createWithSupabase, withSupabase } from './with-supabase.js'

const baseEnv = {
url: 'https://test.supabase.co',
Expand All @@ -25,6 +26,21 @@ const baseEnv = {
jwks: null,
}

type Database = {
public: {
Tables: {
notes: {
Row: { id: number; body: string }
Insert: { id?: number; body: string }
Update: { id?: number; body?: string }
Relationships: []
}
}
Views: Record<never, never>
Functions: Record<never, never>
}
}

describe('withSupabase', () => {
it('handles OPTIONS preflight with CORS', async () => {
const handler = withSupabase({ auth: 'none', env: baseEnv }, async () =>
Expand Down Expand Up @@ -570,6 +586,104 @@ describe('type guarantees (tsc-verified)', () => {
})
})

describe('createWithSupabase type guarantees (tsc-verified)', () => {
const withTypedSupabase = createWithSupabase<Database>()
const config = { auth: 'user', env: baseEnv } as const

it('types ctx.supabase and ctx.supabaseAdmin for the chosen Database', () => {
const _handler = withTypedSupabase(config, async (_req, ctx) => {
expectTypeOf(ctx.supabase).toEqualTypeOf<SupabaseClient<Database>>()
expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf<SupabaseClient<Database>>()
await ctx.supabase.from('notes').insert({ body: 'typed' })
// @ts-expect-error — no such table in Database
await ctx.supabaseAdmin.from('missing').select()
return Response.json({ ok: true })
}) satisfies FetchHandler
void _handler
})

it('as a pipeline entry, passes its keys and the chosen Database on', () => {
const _handler = pipeline(
[withTypedSupabase(config), withPostgresClient()],
async (_req, ctx) => {
expectTypeOf(ctx.postgres).not.toBeAny()
expectTypeOf(ctx.supabase).toEqualTypeOf<SupabaseClient<Database>>()
expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf<
SupabaseClient<Database>
>()
return Response.json({ ok: true })
},
)
void _handler
})

it('nested: a middleware with a prerequisite composes as the handler', () => {
const _handler = withTypedSupabase(
config,
withPostgresClient(async (_req, ctx) => {
expectTypeOf(ctx.postgres).not.toBeAny()
expectTypeOf(ctx.supabase).toEqualTypeOf<SupabaseClient<Database>>()
expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf<
SupabaseClient<Database>
>()
return Response.json({ ok: true })
}),
) satisfies FetchHandler
void _handler
})

it('nested: Base flows in from an outer middleware alongside Database', () => {
const _composed = withOAuthProtectedResource(
withTypedSupabase(config, async (_req, ctx) => {
expectTypeOf(
ctx.oauthProtectedResource.resourceMetadataUrl,
).toEqualTypeOf<string>()
expectTypeOf(ctx.supabase).toEqualTypeOf<SupabaseClient<Database>>()
return Response.json({ ok: true })
}),
) satisfies FetchHandler
void _composed
})

it('accepts a handler annotated with SupabaseContext<Database>', () => {
async function handle(
_req: Request,
ctx: SupabaseContext<Database>,
): Promise<Response> {
return Response.json({ id: ctx.userClaims?.id ?? null })
}
const _handler = withTypedSupabase(config, handle) satisfies FetchHandler
void _handler
})

it('as a pipeline entry, a later entry contributing one of its keys fails to compile', () => {
const _handler = pipeline(
[withTypedSupabase(config), withClaims()],
// @ts-expect-error — middleware-conflict: it already contributes jwtClaims
async () => Response.json({ ok: true }),
)
void _handler
})

it('nested: a middleware contributing one of its keys fails to compile', () => {
const _handler = withTypedSupabase(
config,
// @ts-expect-error — middleware-conflict: it already contributes jwtClaims
withClaims(async () => Response.json({ ok: true })),
) satisfies FetchHandler
void _handler
})

it('nested: a second withSupabase inside it fails to compile', () => {
const _handler = withTypedSupabase(
config,
// @ts-expect-error — middleware-conflict: its keys are already on the context
withTypedSupabase(config, async () => Response.json({ ok: true })),
) satisfies FetchHandler
void _handler
})
})

describe('withSupabase as a pipeline entry', () => {
const oauthCfg = {
resourceServer: 'http://localhost/functions/v1/mcp',
Expand Down Expand Up @@ -852,6 +966,73 @@ describe('withSupabase config without a middleware option', () => {
})
})

describe('createWithSupabase at runtime', () => {
const withTypedSupabase = createWithSupabase<Database>()
const oauthCfg = {
resourceServer: 'http://localhost/functions/v1/mcp',
authorizationServer: 'https://test.supabase.co/auth/v1',
}
const ok = async () => new Response('ok')

it('exposes the same context keys as withSupabase', async () => {
const handler = withTypedSupabase(
{ auth: 'none', env: baseEnv },
async (_req, ctx) => Response.json({ keys: Object.keys(ctx).sort() }),
)
const body = await (await handler(new Request('http://localhost'))).json()
expect(body.keys).toEqual([
'authKeyName',
'authMode',
'jwtClaims',
'supabase',
'supabaseAdmin',
'userClaims',
])
})

it('answers a request without credentials with the gate 401', async () => {
const handler = pipeline(
[withTypedSupabase({ auth: 'user', env: baseEnv })],
ok,
)
const res = await handler(new Request('http://localhost'))
expect(res.status).toBe(401)
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')
})

it('refuses withOAuthProtectedResource behind its credentialed gate, in both forms', () => {
expect(() =>
pipeline(
[
withTypedSupabase({ auth: 'user', env: baseEnv }),
withOAuthProtectedResource(oauthCfg),
],
ok,
),
).toThrow(/withOAuthProtectedResource is placed after withSupabase/)
expect(() =>
withTypedSupabase(
{ auth: 'user', env: baseEnv },
withOAuthProtectedResource(oauthCfg, ok),
),
).toThrow(/placed after withSupabase/)
})

it('refuses a config carrying a middleware key', () => {
const config = {
auth: 'none',
env: baseEnv,
middleware: [],
} as unknown as WithSupabaseConfig
expect(() => withTypedSupabase(config, ok)).toThrow(
/has no `middleware` option/,
)
expect(() => withTypedSupabase(config)).toThrow(
/has no `middleware` option/,
)
})
})

describe('withSupabase audience and issuer validation', () => {
it('validates audience and issuer when configured', async () => {
const { privateKey, publicKey } = await generateKeyPair('RS256')
Expand Down
Loading
Loading