Skip to content

feat: let a middleware declare that it must run before another - #59

Draft
johnstonmatt wants to merge 3 commits into
FUNC-1185/middleware/pipeline-anchored-stackfrom
FUNC-1180/middleware/before-ordering
Draft

johnstonmatt wants to merge 3 commits into
FUNC-1185/middleware/pipeline-anchored-stackfrom
FUNC-1180/middleware/before-ordering

Conversation

@johnstonmatt

@johnstonmatt johnstonmatt commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Stacked on #56.

export const withOAuthProtectedResource = defineMiddleware({
  key: 'oauthProtectedResource',
  before: ['authMode'], // must run outside anything that contributes `authMode`
  run: (config: OAuthProtectedResourceConfig | undefined) => async function* (req) { … },
})

pipeline([withSupabase({ auth: 'user' }), withRequestId(), withOAuthProtectedResource()], handler)
// TS2345: … not assignable to parameter of type
//   "middleware-order: 'oauthProtectedResource' must run before anything that contributes 'authMode'"
// and, with the types bypassed, the same message is thrown when the stack is built

defineMiddleware takes an optional before: keys that must not be on ctx yet when the middleware runs. The keys are inferred, so authors write no type argument. A middleware without before has exactly the types it has on the base branch: every new check resolves to the existing shape when Before is never.

Compile time, three checks:

  • ValidateEntries checks each entry's before keys against the accumulated context, so a pipeline fails at any distance, and against the enclosing context when it sits in a handler position.
  • The cascade and propagation overloads wrap the handler in InOrder (shaped like NoConflict, inside it), so nesting fails wherever a collision does.
  • The produced handler's ctx types each before key as an optional OutOfOrder sentinel. That is what catches withSupabase(cfg, withOAuthProtectedResource(o, h)): a hand-written outer whose keys never reach the inner call's Base rejects the handler at its own call. A string index signature of type any beside the sentinel keeps every other key known, so a host argument passed as an object literal (handler(req, { DB: '…' })) meets no excess-property check, as it doesn't against object.

Build time: a produced handler carries the before rules of everything inside it under Symbol.for('@supabase/middleware:before'). Each layer checks its own key against the rules of the handler it wraps and passes them outward, so the contributing layer throws at any distance, in either form, across the two, through composites (internal-key boundary included), and between two installed copies.

Entry, SingleKeyEntry, Middleware and Composite gain a Before parameter defaulting to never, AnyEntry is Entry<object, object, string>, and InOrder, OutOfOrder and Befores are exported. The cascade signature gains no type parameter and its Base no default. The authoring guide has a new variant, "running before another middleware".

Evidence

Before: there is no way to state the rule. pipeline([withSupabase(cfg), withRequestId(), withOAuthProtectedResource(o)], h) compiles, builds and runs, and discovery requests get a 401.

After, on TypeScript 5.6.2 (Deno 2.1.4's), with a withSupabase-shaped hand-written signature:

evidence.ts(25,95): error TS2345: Argument of type '() => Promise<Response>' is not assignable to parameter of type '"middleware-order: 'oauthProtectedResource' must run before anything that contributes 'authMode'"'.
evidence.ts(26,54): error TS2345: Argument of type '(req: Request, ctx?: (Record<never, never> & { readonly authMode?: "middleware-order: …" | undefined; }) | undefined) => Promise<...>' is not assignable to parameter of type '(req: Request, ctx: obj…
          Types of property 'authMode' are incompatible.
              Type '"user"' is not assignable to type '"middleware-order: 'oauthProtectedResource' must run before anything that contributes 'authMode'"'.
Error: middleware-order: 'oauthProtectedResource' must run before anything that contributes 'authMode'. Place it outside the middleware that contributes 'authMode': earlier in a pipeline, or further out when nesting.

Type-level coverage, from a probe of 56 shapes on TypeScript 5.4.2, 5.5.4, 5.6.2, 5.6.3, 5.7.3, 5.8.3, 5.9.2, 5.9.3, 6.0.3 and 7.0.2 (same on every version unless noted):

Wrong order Fails to compile
pipeline: adjacent, at distance, a composite entry, a hand-written signature's entry yes
pipeline as a handler argument, the enclosing layer contributes the key (anchored) yes
nested, anchored: adjacent, at distance, through a hand-written middle layer, composite inner or outer yes
nested directly inside a hand-written contributor (withSupabase shape), unanchored yes
nested at distance inside a hand-written contributor (withSupabase), anchored or not, inline-arrow leaf taking (req, ctx) yes, but not with the middleware-order message: a ctx mismatch on 5.4 to 5.8, implicit any on 5.9+; also throws at build
nested at distance inside a hand-written contributor, anchored or not, a leaf with no parameters or a named handler no; throws at build
nested, unanchored, defineMiddleware contributor 5.9+ with an inline-arrow leaf, otherwise no; throws at build. Collision detection on the base branch has the same profile

All 25 right-order shapes compile on every version and keep their ctx typing, including a before middleware nested inside a hand-written signature, the shape that breaks on 5.4 to 5.8 when a conditional type in the inner handler stays unevaluated. A stack whose outermost middleware has before accepts an object literal, an interface (Deno's ServeHandlerInfo shape) and object as its host argument, and is assignable to FetchHandler, a Deno handler and a Workers fetch.

Check Result
typecheck, lint, format:check, test (165 passed), build, smoke, typecheck:min, typecheck:consumer, check-exports, JSR dry run, test:deno, test:bun pass
tsc --noEmit on the source, including every new @ts-expect-error and a middleware with a hand-written signature, on all ten versions pass
test/ts-floor/consumer.ts against the built .d.ts, on all ten versions pass
Dependents (@supabase/server src, examples and e2e, @supabase-labs/middleware-openfeature, an internal dependent) against this build vs 1.0.0, all ten versions +0 errors everywhere
Server's three withSupabase nesting tests same lines fail on 5.4.2 for 1.0.0, the base branch and this branch; clean on 5.5+ for all three
deno check with @supabase/server 1.9.2 on this build, Deno 2.1.4, 2.4.5, 2.5.0, 2.9.8 right orders pass; all five wrong orders fail (flat, flat at distance, nested, nested arrow, nested at distance); existing probe cases unchanged from the base branch
TypeDoc same 4 warnings as the base branch

Merge Danger

Door: one-way

Blast Radius: low

  • Nesting without an anchor is not always caught by types: with a defineMiddleware contributor it needs TypeScript 5.9+ and an inline-arrow leaf, and at distance under a hand-written contributor, anchored or not, only an inline-arrow leaf taking (req, ctx) fails, with a ctx mismatch (5.4 to 5.8) or implicit any (5.9+) rather than the middleware-order message. The defineMiddleware case is the same gap collision detection has (the produced type records what a stack requires, not what it contributes). The build-time check catches every one of these shapes on the first start.
  • Once released, before, the Before parameters, the three exported types and the Symbol.for('@supabase/middleware:before') rules map are public, and the map is read across installed copies, so its shape (forbidden key to declaring key) is a contract.
  • A middleware declared with explicit type arguments has to pass Before as the fifth, and a Middleware<…>, Entry or SingleKeyEntry annotation without it is a type error rather than a dropped rule. @supabase/server's withOAuthProtectedResource needs both (FUNC-1181).
  • The rule cannot see config, so a middleware with before: ['authMode'] is refused behind a gate that allows 'none' too.
  • The produced handler's ctx parameter of a middleware with before carries { readonly [key: string]: any }. It only widens what callers may pass, which is already any object, and never reaches the ctx a handler reads.
  • A composite's sentinel names each key the composite contributes, not the part that declared the rule.
  • A conditional type in a dependent that matches Entry<infer C, infer In> no longer matches an entry with before; the engine's own folds match Entry<…, string>. None of the checked dependents match on Entry.

Refs FUNC-1180

`defineMiddleware` takes an optional `before`: keys that must not be on `ctx` yet when the middleware runs, such as `authMode` for OAuth discovery, which has to answer before an auth gate. The keys are inferred, and a middleware without `before` has exactly the types it has without the field.

A wrong order fails to compile in a `pipeline` at any distance, in a nested stack wherever a collision does (at any depth once the outermost call is anchored), and directly inside a hand-written signature that contributes the key, such as `withSupabase`, through a sentinel on the produced handler's `ctx`. It also throws when the stack is built: each produced handler carries the rules of what it wraps under a `Symbol.for` key, and the layer that contributes a named key throws, at any distance, in either form and across the two.

A composite carries its parts' `before` keys. `Entry`, `SingleKeyEntry`, `Middleware` and `Composite` gain a `Before` parameter defaulting to `never`, and `InOrder`, `OutOfOrder` and `Befores` are exported.

Refs FUNC-1180
The authoring guide gets a variant for `before`, and the root and core READMEs list ordering beside collision detection and prerequisites.

Refs FUNC-1180
@pkg-pr-new

pkg-pr-new Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@supabase/middleware@59

commit: 858610b

…efore`

A produced handler's `ctx` marks each `before` key with the order sentinel. A string index signature of type `any` beside it keeps every other key known, so `handler(req, { DB: '…' })` meets no excess-property check, as it doesn't against `object`, and an interface argument such as Deno's `ServeHandlerInfo` is still accepted.

Directly inside a hand-written signature that contributes the key, the wrong order still fails to compile; further in, the build-time check covers it on TypeScript 5.5 to 5.8.

Refs FUNC-1180

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant