Skip to content
Open
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
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,11 @@ root README in the same commit.

## Writing a middleware

The full authoring guide — `defineMiddleware`, request-side and generator forms, tests, publishing, and composing alongside the built-in entries — is in [`docs/authoring-guide.md`](./docs/authoring-guide.md). The composition primitives (`ctx` shape, conflict & prerequisite enforcement, the response seam) are documented in [`src/core/README.md`](./src/core/README.md), with [`feature-flag`](./src/middleware/feature-flag/README.md) and [`cors`](./src/middleware/cors/README.md) as worked examples.
The full authoring guide — `defineMiddleware`, request-side and generator forms, tests, publishing, and composing alongside the built-in entries — is in [`docs/authoring-guide.md`](./docs/authoring-guide.md). The composition primitives (`ctx` shape, conflict & prerequisite enforcement, the response seam) are documented in [`src/core/README.md`](./src/core/README.md), with [`feature-flag`](./src/middleware/feature-flag/README.md), [`cors`](./src/middleware/cors/README.md) and [`timing`](./src/middleware/timing/README.md) as worked examples.

Your middleware is its own package. This repository ships the composition primitives and two worked examples (`cors` and `feature-flag`) and takes no new middleware; the authoring guide's [Where it lives](./docs/authoring-guide.md#where-it-lives) section covers the options. Middleware Supabase maintains lives in [`@supabase/server`](https://github.com/supabase/server); to propose one, open an issue there.
Your middleware is its own package. This repository ships the composition primitives and three worked examples (`feature-flag`, `cors` and `timing`) and takes no new middleware; the authoring guide's [Where it lives](./docs/authoring-guide.md#where-it-lives) section covers the options. Middleware Supabase maintains lives in [`@supabase/server`](https://github.com/supabase/server); to propose one, open an issue there.

To change one of the two built-ins, see [`src/middleware/README.md`](./src/middleware/README.md) for the directory layout and subpath wiring.
To change one of the built-ins, see [`src/middleware/README.md`](./src/middleware/README.md) for the directory layout and subpath wiring.

## Submitting Changes

Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ deno add jsr:@supabase/middleware
| `@supabase/middleware` | `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, `seedContext`, `isContext`, and the core types: `Entry`, `FetchHandler`, `Middleware`, `BaseContext`. |
| `@supabase/middleware/feature-flag` | Provider-agnostic feature flag — admit or short-circuit per request. |
| `@supabase/middleware/cors` | CORS — answers preflight and stamps response headers (the worked example of the response seam). |
| `@supabase/middleware/timing` | Adds the time spent in middleware and in named calls (database queries) to `Server-Timing`. |

## Bundling several into one

Expand Down Expand Up @@ -206,13 +207,13 @@ run: (config) =>

The `yield` expression resolves to the downstream `Response` (typed as `Response`, inferred — no annotation). `yield` the contribution at most once — `yield` means "run downstream and hand me the response." To short-circuit (handler never runs), `return new Response(...)`, exactly as a plain request-side middleware does. `try/finally` around the `yield` gives request-spanning cleanup; `try/catch` can turn a downstream throw into a `Response`.

This is the **one** place the "request-side" guarantee is relaxed, and writing `function*` is the visible, opt-in signal — the 95% plain-`async` path is unchanged. [`/cors`](./src/middleware/cors/README.md) is the worked example.
This is the **one** place the "request-side" guarantee is relaxed, and writing `function*` is the visible, opt-in signal — the 95% plain-`async` path is unchanged. [`/cors`](./src/middleware/cors/README.md) and [`/timing`](./src/middleware/timing/README.md) are the worked examples.

## Docs

- [Authoring guide](./docs/authoring-guide.md) — **build your own middleware**: `defineMiddleware`, tests, publishing, and composing it in the same `pipeline` array as the built-in entries.
- [Composition primitives](./src/core/README.md) — `ctx` shape, conflict & prerequisite enforcement, composition rules, the response seam.
- Per-middleware: [feature-flag](./src/middleware/feature-flag/README.md) — the request-side worked example · [cors](./src/middleware/cors/README.md) — the response-seam worked example.
- Per-middleware: [feature-flag](./src/middleware/feature-flag/README.md) — the request-side worked example · [cors](./src/middleware/cors/README.md) and [timing](./src/middleware/timing/README.md) — the response-seam worked examples.

Full generated API reference: [supabase.github.io/middleware](https://supabase.github.io/middleware/).

Expand Down
142 changes: 81 additions & 61 deletions docs/authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ as for anyone else's:
[`@supabase-labs/middleware-openfeature`](https://github.com/supabase/middleware-openfeature)
is one.

This repository ships the composition primitives and two worked examples,
`withCors` and `withFeatureFlag`. It takes no new middleware.
This repository ships the composition primitives and three worked examples:
`withFeatureFlag`, `withCors` and `withTiming`. It takes no new middleware.

[`@supabase/server`](https://github.com/supabase/server) holds the middleware
Supabase maintains: `withSupabase`, `withSupabaseClient`, `withPostgresClient`,
Expand Down Expand Up @@ -1752,68 +1752,86 @@ When a concern is genuinely two-sided, write `run` as an `async function*`.
`yield` is the seam: code before it is the request phase, the `yield` expression
resolves to the downstream `Response`, and code after it is the response phase.

```ts
// src/with-timing.ts
import { defineMiddleware } from '@supabase/middleware'
import type { Middleware } from '@supabase/middleware'
The built-in [`withTiming`](../src/middleware/timing/with-timing.ts) is the
example. It starts a clock and hands the handler `ctx.timing`, whose `mark()`
ends the pipeline entry and whose `measure(name, fn)` times calls such as
database queries. Once the handler's response comes back, it writes what was
recorded to `Server-Timing`. Its `run`:

/** Per-instance configuration for {@link withTiming}. */
export interface WithTimingConfig {
/** Metric name used in the `Server-Timing` header. @defaultValue `'total'` */
metric?: string
}
```ts
run: (config) => {
// Outside the generator: runs once, when the stack is built.
const pipelineMetric = config?.pipelineMetric ?? 'mw'
assertMetricName(pipelineMetric)

// Inside: runs per request, so this state is per request.
return async function* () {
const startedAt = performance.now() // request phase
let pipelineDur: number | undefined
const measured = new Map<string, { dur: number; calls: number }>()

const timing: TimingContribution = {
mark() {
pipelineDur ??= performance.now() - startedAt
},
async measure(name, fn) {
assertMetricName(name)
const start = performance.now()
try {
return await fn()
} finally {
const entry = measured.get(name) ?? { dur: 0, calls: 0 }
entry.dur += performance.now() - start
entry.calls += 1
measured.set(name, entry)
}
},
}

/** Shape contributed at `ctx.timing`. */
export interface TimingContribution {
/** When the request entered this middleware, from `performance.now()`. */
startedAt: number
}
// Contribute, then suspend. The rest of the stack runs.
const response = yield { timing }

/**
* Times the request and stamps a `Server-Timing` header on the way out.
*
* Genuinely two-sided, so `run` is an `async function*`: code before the
* `yield` is the request phase, the `yield` expression resolves to the
* downstream `Response`, and code after it is the response phase.
*/
export const withTiming: Middleware<
'timing',
WithTimingConfig | undefined,
Record<never, never>,
TimingContribution
> = defineMiddleware<
'timing',
WithTimingConfig | undefined,
Record<never, never>,
TimingContribution
>({
key: 'timing',
run: (config) =>
async function* () {
const metric = config?.metric ?? 'total'
const startedAt = performance.now() // request phase

// Contribute, then suspend. The rest of the stack runs.
const response = yield { timing: { startedAt } }

// Response phase. Copy the headers so an immutable response is handled.
const headers = new Headers(response.headers)
headers.append(
'Server-Timing',
`${metric};dur=${(performance.now() - startedAt).toFixed(1)}`,
)
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
})
},
})
// Response phase.
const entries: string[] = []
if (pipelineDur !== undefined) {
entries.push(`${pipelineMetric};dur=${ms(pipelineDur)}`)
}
for (const [name, { dur, calls }] of measured) {
const desc = calls === 1 ? '1 call' : `${calls} calls`
entries.push(`${name};dur=${ms(dur)};desc="${desc}"`)
}
if (entries.length === 0) return response
if (response.status < 200 || response.status > 599) return response

// Copy the headers so an immutable response is handled.
const headers = new Headers(response.headers)
headers.append('Server-Timing', entries.join(', '))
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
})
}
},
```

Typing `Config` as `WithTimingConfig | undefined` is what makes the config
argument optional, so consumers can write `withTiming()` as well as
`withTiming({ metric: 'api' })`.
A few things here carry over to any seam middleware:

- **Per-request state lives inside the generator.** `run(config)` is called
once per stack, so anything above the `return` is shared by every request.
Validate config there, so a bad value fails at startup.
- **The contribution can be a set of methods,** not just data. The handler
calls back into the middleware through it, and the response phase reads what
it recorded.
- **The middleware can't see where the handler starts.** Placed first, it times
everything after it as one span, so the handler marks the boundary itself.
- **Pass through what you didn't change.** With nothing recorded it returns the
downstream response as is, and it leaves alone statuses the `Response`
constructor can't rebuild (`Response.error()`'s 0, a WebSocket 101).

`withTiming` types its `Config` as `WithTimingConfig | undefined`, which is what
makes the config argument optional: consumers can write `withTiming()` as well
as `withTiming({ pipelineMetric: 'setup' })`.

Rules for the seam:

Expand All @@ -1827,8 +1845,8 @@ Rules for the seam:
- Returning nothing passes the downstream response through untouched.

The runtime picks the path from what the body returns, so the plain `async` case
is unaffected. [`withCors`](../src/middleware/cors/with-cors.ts) is the
built-in worked example: it answers preflight with a `return` before the
is unaffected. [`withCors`](../src/middleware/cors/with-cors.ts) is the other
built-in seam middleware: it answers preflight with a `return` before the
`yield`, and stamps headers after.

## Variant: bundling middleware into one
Expand Down Expand Up @@ -1960,5 +1978,7 @@ as any other nested stack.
request-side worked example.
- [`cors`](../src/middleware/cors/README.md) — the built-in response-seam
worked example.
- [`timing`](../src/middleware/timing/README.md) — the built-in response-seam
worked example whose contribution the handler calls back into.
- [Adding a middleware to this repository](../src/middleware/README.md) — for
built-ins rather than standalone packages.
3 changes: 2 additions & 1 deletion jsr.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"exports": {
".": "./src/index.ts",
"./feature-flag": "./src/middleware/feature-flag/index.ts",
"./cors": "./src/middleware/cors/index.ts"
"./cors": "./src/middleware/cors/index.ts",
"./timing": "./src/middleware/timing/index.ts"
},
"imports": {
"std-env": "npm:std-env@^4.2.0"
Expand Down
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@
"default": "./dist/middleware/cors/index.cjs"
}
},
"./timing": {
"import": {
"types": "./dist/middleware/timing/index.d.mts",
"default": "./dist/middleware/timing/index.mjs"
},
"require": {
"types": "./dist/middleware/timing/index.d.cts",
"default": "./dist/middleware/timing/index.cjs"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
Expand Down
22 changes: 11 additions & 11 deletions skills/supabase-middleware/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: supabase-middleware
description: Use when writing or modifying a Web Fetch handler that composes cross-cutting concerns with `@supabase/middleware` — CORS, feature flags, auth, rate limiting, logging — on Deno, Supabase Edge Functions, Cloudflare Workers, Bun, or Node. Trigger **before** writing or editing any file that imports from `@supabase/middleware` or a subpath (`/cors`, `/feature-flag`); calls `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, or `seedContext`; or annotates a handler with `satisfies FetchHandler`. Also trigger during planning — if a plan mentions any of the above, load this skill before drafting code. Also trigger when porting middleware idioms that do not apply here: `app.use()` registries, `next()` chains, Express/Koa/Hono middleware being translated, or hand-rolled `(req) => wrapper(wrapper(handler))` nesting.
description: Use when writing or modifying a Web Fetch handler that composes cross-cutting concerns with `@supabase/middleware` — CORS, feature flags, auth, rate limiting, logging — on Deno, Supabase Edge Functions, Cloudflare Workers, Bun, or Node. Trigger **before** writing or editing any file that imports from `@supabase/middleware` or a subpath (`/cors`, `/feature-flag`, `/timing`); calls `pipeline`, `defineMiddleware`, `getEnv`, `runtimeName`, or `seedContext`; or annotates a handler with `satisfies FetchHandler`. Also trigger during planning — if a plan mentions any of the above, load this skill before drafting code. Also trigger when porting middleware idioms that do not apply here: `app.use()` registries, `next()` chains, Express/Koa/Hono middleware being translated, or hand-rolled `(req) => wrapper(wrapper(handler))` nesting.
---

# @supabase/middleware
Expand Down Expand Up @@ -50,15 +50,15 @@ export default {

Paths are repo-relative. When `@supabase/middleware` is installed as a dependency, prefix them with `node_modules/@supabase/middleware/` — the same files ship in the package.

| Question | Doc |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| How do I compose a stack? What is on `ctx`? | `src/core/README.md` |
| When is `satisfies FetchHandler` required, and what breaks without it? | `src/core/README.md` |
| A middleware needs to see the response too | `src/core/README.md` (response seam), `src/middleware/cors/README.md` |
| How do I write and publish my own middleware? | `docs/authoring-guide.md`, and the `create-supabase-middleware` skill |
| How do I add a built-in to this repo? | `src/middleware/README.md` |
| Environment access, runtime differences, Workers `env` | `README.md` |
| Config for the bundled middleware | `src/middleware/feature-flag/README.md`, `src/middleware/cors/README.md` |
| Full API reference | <https://supabase.github.io/middleware/> |
| Question | Doc |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| How do I compose a stack? What is on `ctx`? | `src/core/README.md` |
| When is `satisfies FetchHandler` required, and what breaks without it? | `src/core/README.md` |
| A middleware needs to see the response too | `src/core/README.md` (response seam), `src/middleware/cors/README.md`, `src/middleware/timing/README.md` |
| How do I write and publish my own middleware? | `docs/authoring-guide.md`, and the `create-supabase-middleware` skill |
| How do I add a built-in to this repo? | `src/middleware/README.md` |
| Environment access, runtime differences, Workers `env` | `README.md` |
| Config for the bundled middleware | `src/middleware/feature-flag/README.md`, `src/middleware/cors/README.md`, `src/middleware/timing/README.md` |
| Full API reference | <https://supabase.github.io/middleware/> |

Release history and current status: <https://github.com/supabase/middleware/releases>.
1 change: 1 addition & 0 deletions src/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,4 @@ export default {
- [Authoring guide](../../docs/authoring-guide.md) — write your own middleware.
- [`feature-flag/`](../middleware/feature-flag/README.md) — the worked example (request-side).
- [`cors/`](../middleware/cors/README.md) — the worked example of the response seam (`async function*`).
- [`timing/`](../middleware/timing/README.md) — a response-seam middleware whose contribution the handler calls back into.
2 changes: 2 additions & 0 deletions src/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as root from './index.js'
import * as core from './core/index.js'
import * as cors from './middleware/cors/index.js'
import * as featureFlag from './middleware/feature-flag/index.js'
import * as timing from './middleware/timing/index.js'

/**
* Guards the public *value* exports of every entry point. Type-only exports are
Expand Down Expand Up @@ -40,5 +41,6 @@ describe('public API surface', () => {
it('middleware subpaths', () => {
expect(typeof featureFlag.withFeatureFlag).toBe('function')
expect(typeof cors.withCors).toBe('function')
expect(typeof timing.withTiming).toBe('function')
})
})
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*
* - `@supabase/middleware/feature-flag`
* - `@supabase/middleware/cors`
* - `@supabase/middleware/timing`
*
* @packageDocumentation
*/
Expand Down
Loading
Loading