mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 17:35:10 +03:00
## See the changes * https://docs-git-docs-middleware-usage-examples-supabase.vercel.app/docs/reference/middleware/usage-examples * https://docs-git-docs-middleware-usage-examples-supabase.vercel.app/docs/reference/middleware/build-your-own ## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Docs update. ## What is the current behavior? The `@supabase/middleware` reference has two hand-written pages, Introduction and Installing, followed directly by the generated API reference. There is no worked example of composing middleware and no guidance on writing one. The authoring guide lives only in the [middleware repo](https://github.com/supabase/middleware/blob/main/docs/authoring-guide.md). ## What is the new behavior? Two new partials sit between Installing and the generated reference: - **Usage examples**: two `pipeline` examples. The first composes `withCors` and `withFeatureFlag` from `@supabase/middleware`. The second adds `withSupabase` from `@supabase/server`: `withCors` first, `withSupabase({ auth: 'user', cors: 'disabled' })` second, and an environment-driven flag last. The prose explains why a CORS layer must precede the auth gate, what `withSupabase` does for CORS on its own, and that the entry form of `withSupabase` is alpha and needs `@supabase/server` 1.6.0 or later. - **Build your own middleware**: the `defineMiddleware` shape (four type arguments, when `run` receives the config, contribute vs short-circuit, reading `getEnv` inside the per-request function), composing a custom entry in `pipeline`, what `pipeline` checks at compile time, and when `satisfies FetchHandler` matters. It links to the full authoring guide for tests, packaging, and the variants. `partialsOrder` in `spec/reference/middleware/v1/config.json` registers both partials. The `docs/ref/middleware/` mirrors were generated with `pnpm codegen:references:new`. ## Additional context - Every snippet typechecks against `@supabase/middleware` and `@supabase/server` source on `main`. The "fails to compile" statements were confirmed with negative typechecks (duplicate key, unmet prerequisite, in both the `pipeline` and nested forms). - The second example's request flow was exercised end to end with a local JWKS: preflight `204`, missing credentials `401`, flag off `404`, flag on `200`, and the reversed order producing a `401` with no CORS headers. - The generated `sections.json` lists the four partials in order: Introduction, Installing, Usage examples, Build your own middleware. No local render check was done. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added usage examples for composing middleware pipelines with CORS, feature flags, authentication, and Supabase. * Added guidance for creating custom middleware, contributing request context, handling responses, and accessing runtime environment variables. * Documented middleware ordering, validation, preflight handling, and authentication behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
89 lines
3.9 KiB
Plaintext
89 lines
3.9 KiB
Plaintext
---
|
|
id: usage-examples
|
|
title: Usage examples
|
|
---
|
|
|
|
Each example builds one Fetch handler with `pipeline`. Entries run in array order on the request. The handler runs last and reads what the entries contributed to `ctx`.
|
|
|
|
### Gate a route behind CORS and a feature flag
|
|
|
|
<RefSubLayout.EducationRow>
|
|
<RefSubLayout.Details>
|
|
|
|
`withCors` runs first. It answers the CORS preflight (an `OPTIONS` request carrying `Access-Control-Request-Method`) with `204` before anything else runs. On the way out, it stamps `Access-Control-*` headers onto the response when the request's `Origin` is allowed.
|
|
|
|
`withFeatureFlag` runs second. `evaluate` receives the request and decides: `true` admits it, `false` rejects it. It can be async, and it can return a verdict object instead of a boolean. A rejected request gets a `404` and never reaches the handler. An admitted request reaches the handler with `ctx.featureFlag` set.
|
|
|
|
Both middleware ship in `@supabase/middleware`. The handler is plain Fetch, so the same stack runs on Node, Deno, Bun, and Cloudflare Workers; only the host entry point differs.
|
|
|
|
</RefSubLayout.Details>
|
|
|
|
<RefSubLayout.Examples>
|
|
|
|
```ts
|
|
import { pipeline } from '@supabase/middleware'
|
|
import { withCors } from '@supabase/middleware/cors'
|
|
import { withFeatureFlag } from '@supabase/middleware/feature-flag'
|
|
|
|
export default {
|
|
fetch: pipeline(
|
|
[
|
|
withCors({ origin: ['https://app.example.com'], credentials: true }),
|
|
withFeatureFlag({
|
|
name: 'beta-checkout',
|
|
evaluate: (req) => req.headers.get('x-beta') === '1',
|
|
}),
|
|
],
|
|
async (_req, ctx) => Response.json({ feature: ctx.featureFlag.name }),
|
|
),
|
|
}
|
|
```
|
|
|
|
</RefSubLayout.Examples>
|
|
</RefSubLayout.EducationRow>
|
|
|
|
### Roll out an authenticated endpoint behind a flag
|
|
|
|
<RefSubLayout.EducationRow>
|
|
<RefSubLayout.Details>
|
|
|
|
Middleware from [`@supabase/server`](/docs/reference/server/introduction) drop into the same array. `withCors` runs first, so the preflight is answered before the auth gate. `withSupabase` runs second with `cors: 'disabled'`, because `withCors` owns CORS here. It verifies the caller's JWT and puts an RLS-scoped client on `ctx.supabase`. A request without valid credentials gets a `401` and never reaches the flag or the handler.
|
|
|
|
The flag runs last. `evaluate` reads an environment variable through `getEnv`, so the endpoint returns `404` to every signed-in caller until `BETA_CHECKOUT` is set to `on`. Flip the variable to roll the endpoint out.
|
|
|
|
Without `withCors`, `withSupabase` answers every `OPTIONS` request itself with `204` and wildcard CORS headers (`Access-Control-Allow-Origin: *`). That is enough when you do not need an origin allowlist. A layer that owns CORS must sit before `withSupabase` in the array. Placed after it, the preflight reaches the auth gate and gets a `401`.
|
|
|
|
The entry form of `withSupabase` is alpha. It needs `@supabase/server` 1.6.0 or later.
|
|
|
|
</RefSubLayout.Details>
|
|
|
|
<RefSubLayout.Examples>
|
|
|
|
```ts
|
|
import { getEnv, pipeline } from '@supabase/middleware'
|
|
import { withCors } from '@supabase/middleware/cors'
|
|
import { withFeatureFlag } from '@supabase/middleware/feature-flag'
|
|
import { withSupabase } from '@supabase/server'
|
|
|
|
export default {
|
|
fetch: pipeline(
|
|
[
|
|
withCors({ origin: ['https://app.example.com'] }),
|
|
withSupabase({ auth: 'user', cors: 'disabled' }),
|
|
withFeatureFlag({
|
|
name: 'beta-checkout',
|
|
evaluate: () => getEnv('BETA_CHECKOUT') === 'on',
|
|
}),
|
|
],
|
|
async (_req, ctx) => {
|
|
const { data, error } = await ctx.supabase.from('carts').select()
|
|
if (error) return Response.json({ error: 'query_failed' }, { status: 500 })
|
|
return Response.json(data)
|
|
},
|
|
),
|
|
}
|
|
```
|
|
|
|
</RefSubLayout.Examples>
|
|
</RefSubLayout.EducationRow>
|