diff --git a/apps/docs/docs/ref/middleware/build-your-own.mdx b/apps/docs/docs/ref/middleware/build-your-own.mdx
new file mode 100644
index 00000000000..b5ee46fca58
--- /dev/null
+++ b/apps/docs/docs/ref/middleware/build-your-own.mdx
@@ -0,0 +1,70 @@
+---
+id: build-your-own
+title: Build your own middleware
+---
+
+A middleware is a `withFoo` function built with `defineMiddleware`. It owns one key on `ctx` and runs before the handler on every request. A generator `run` can also act on the response on the way out; the guide calls that the response seam. This page covers the shape. The [authoring guide](https://github.com/supabase/middleware/blob/main/docs/authoring-guide.md) in the repo covers tests, packaging, and the variants: requiring an upstream key, a config callback that reads upstream context, a hand-written signature, wrapping a vendor SDK, the response seam, and bundling several middleware into one.
+
+### Define it
+
+
+
+
+ `defineMiddleware` takes four type arguments and a spec object. The last two have defaults, but pass all four: without the fourth, the contribution lands on `ctx` as `unknown`.
+
+ The type arguments are the key, the config type, the upstream context the middleware needs, and the contribution type. `void` config means the middleware takes no options. `Record` means it needs nothing from earlier middleware.
+
+ `run` receives the config when the stack is built and returns the per-request function. That function receives the request and the upstream `ctx`. It contributes by returning an object with the key, or short-circuits by returning a `Response`. Read `getEnv` inside the per-request function, not in the outer stage: on Cloudflare Workers the environment arrives with each request.
+
+
+
+
+
+ ```ts with-request-id.ts
+ import { defineMiddleware } from '@supabase/middleware'
+
+ export const withRequestId = defineMiddleware<
+ 'requestId',
+ void,
+ Record,
+ string
+ >({
+ key: 'requestId',
+ run: () => async (req) => ({
+ requestId: req.headers.get('x-request-id') ?? crypto.randomUUID(),
+ }),
+ })
+ ```
+
+
+
+
+### Compose it
+
+
+
+
+ Your middleware drops into the same `pipeline` array as the built-in ones. The handler reads `ctx.requestId` as a `string`, inferred from the entries.
+
+ `pipeline` checks the array at compile time. Two entries that contribute the same key fail with an error naming the key. An entry whose prerequisite no earlier entry supplies fails the same way. If you nest calls instead of using `pipeline`, keep `satisfies FetchHandler` on the outermost call; without that anchor, a nested stack with a duplicate key or a missing prerequisite compiles. `pipeline` already returns a `FetchHandler`, so the anchor adds nothing there.
+
+
+
+
+
+ ```ts
+ import { pipeline } from '@supabase/middleware'
+ import { withCors } from '@supabase/middleware/cors'
+ import { withRequestId } from './with-request-id'
+
+ export default {
+ fetch: pipeline(
+ [withCors({}), withRequestId()],
+ async (_req, ctx) =>
+ Response.json({ ok: true }, { headers: { 'x-request-id': ctx.requestId } }),
+ ),
+ }
+ ```
+
+
+
diff --git a/apps/docs/docs/ref/middleware/usage-examples.mdx b/apps/docs/docs/ref/middleware/usage-examples.mdx
new file mode 100644
index 00000000000..4a557683d32
--- /dev/null
+++ b/apps/docs/docs/ref/middleware/usage-examples.mdx
@@ -0,0 +1,88 @@
+---
+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
+
+
+
+
+ `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.
+
+
+
+
+
+ ```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 }),
+ ),
+ }
+ ```
+
+
+
+
+### Roll out an authenticated endpoint behind a flag
+
+
+
+
+ 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.
+
+
+
+
+
+ ```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)
+ },
+ ),
+ }
+ ```
+
+
+
diff --git a/apps/docs/spec/reference/middleware/v1/config.json b/apps/docs/spec/reference/middleware/v1/config.json
index 74fca13b72c..0e0a6cafb76 100644
--- a/apps/docs/spec/reference/middleware/v1/config.json
+++ b/apps/docs/spec/reference/middleware/v1/config.json
@@ -1,5 +1,5 @@
{
"categoryOrder": ["Composition", "Middleware", "Environment", "Types"],
- "partialsOrder": ["introduction", "installing"],
+ "partialsOrder": ["introduction", "installing", "usage-examples", "build-your-own"],
"navigationPrefixes": {}
}
diff --git a/apps/docs/spec/reference/middleware/v1/partials/build-your-own.mdx b/apps/docs/spec/reference/middleware/v1/partials/build-your-own.mdx
new file mode 100644
index 00000000000..b5ee46fca58
--- /dev/null
+++ b/apps/docs/spec/reference/middleware/v1/partials/build-your-own.mdx
@@ -0,0 +1,70 @@
+---
+id: build-your-own
+title: Build your own middleware
+---
+
+A middleware is a `withFoo` function built with `defineMiddleware`. It owns one key on `ctx` and runs before the handler on every request. A generator `run` can also act on the response on the way out; the guide calls that the response seam. This page covers the shape. The [authoring guide](https://github.com/supabase/middleware/blob/main/docs/authoring-guide.md) in the repo covers tests, packaging, and the variants: requiring an upstream key, a config callback that reads upstream context, a hand-written signature, wrapping a vendor SDK, the response seam, and bundling several middleware into one.
+
+### Define it
+
+
+
+
+ `defineMiddleware` takes four type arguments and a spec object. The last two have defaults, but pass all four: without the fourth, the contribution lands on `ctx` as `unknown`.
+
+ The type arguments are the key, the config type, the upstream context the middleware needs, and the contribution type. `void` config means the middleware takes no options. `Record` means it needs nothing from earlier middleware.
+
+ `run` receives the config when the stack is built and returns the per-request function. That function receives the request and the upstream `ctx`. It contributes by returning an object with the key, or short-circuits by returning a `Response`. Read `getEnv` inside the per-request function, not in the outer stage: on Cloudflare Workers the environment arrives with each request.
+
+
+
+
+
+ ```ts with-request-id.ts
+ import { defineMiddleware } from '@supabase/middleware'
+
+ export const withRequestId = defineMiddleware<
+ 'requestId',
+ void,
+ Record,
+ string
+ >({
+ key: 'requestId',
+ run: () => async (req) => ({
+ requestId: req.headers.get('x-request-id') ?? crypto.randomUUID(),
+ }),
+ })
+ ```
+
+
+
+
+### Compose it
+
+
+
+
+ Your middleware drops into the same `pipeline` array as the built-in ones. The handler reads `ctx.requestId` as a `string`, inferred from the entries.
+
+ `pipeline` checks the array at compile time. Two entries that contribute the same key fail with an error naming the key. An entry whose prerequisite no earlier entry supplies fails the same way. If you nest calls instead of using `pipeline`, keep `satisfies FetchHandler` on the outermost call; without that anchor, a nested stack with a duplicate key or a missing prerequisite compiles. `pipeline` already returns a `FetchHandler`, so the anchor adds nothing there.
+
+
+
+
+
+ ```ts
+ import { pipeline } from '@supabase/middleware'
+ import { withCors } from '@supabase/middleware/cors'
+ import { withRequestId } from './with-request-id'
+
+ export default {
+ fetch: pipeline(
+ [withCors({}), withRequestId()],
+ async (_req, ctx) =>
+ Response.json({ ok: true }, { headers: { 'x-request-id': ctx.requestId } }),
+ ),
+ }
+ ```
+
+
+
diff --git a/apps/docs/spec/reference/middleware/v1/partials/usage-examples.mdx b/apps/docs/spec/reference/middleware/v1/partials/usage-examples.mdx
new file mode 100644
index 00000000000..4a557683d32
--- /dev/null
+++ b/apps/docs/spec/reference/middleware/v1/partials/usage-examples.mdx
@@ -0,0 +1,88 @@
+---
+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
+
+
+
+
+ `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.
+
+
+
+
+
+ ```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 }),
+ ),
+ }
+ ```
+
+
+
+
+### Roll out an authenticated endpoint behind a flag
+
+
+
+
+ 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.
+
+
+
+
+
+ ```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)
+ },
+ ),
+ }
+ ```
+
+
+