Repository navigation
feat: let a middleware declare that it must run before another - #59
Draft
johnstonmatt wants to merge 3 commits into
Draft
johnstonmatt wants to merge 3 commits into
johnstonmatt wants to merge 3 commits into
Conversation
`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
commit: |
…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 was referenced Nov 27, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stacked on #56.
defineMiddlewaretakes an optionalbefore: keys that must not be onctxyet when the middleware runs. The keys are inferred, so authors write no type argument. A middleware withoutbeforehas exactly the types it has on the base branch: every new check resolves to the existing shape whenBeforeisnever.Compile time, three checks:
ValidateEntrieschecks each entry'sbeforekeys against the accumulated context, so apipelinefails at any distance, and against the enclosing context when it sits in a handler position.InOrder(shaped likeNoConflict, inside it), so nesting fails wherever a collision does.ctxtypes eachbeforekey as an optionalOutOfOrdersentinel. That is what catcheswithSupabase(cfg, withOAuthProtectedResource(o, h)): a hand-written outer whose keys never reach the inner call'sBaserejects the handler at its own call. A string index signature of typeanybeside 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 againstobject.Build time: a produced handler carries the
beforerules of everything inside it underSymbol.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,MiddlewareandCompositegain aBeforeparameter defaulting tonever,AnyEntryisEntry<object, object, string>, andInOrder,OutOfOrderandBeforesare exported. The cascade signature gains no type parameter and itsBaseno 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 a401.After, on TypeScript 5.6.2 (Deno 2.1.4's), with a
withSupabase-shaped hand-written signature: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):
pipeline: adjacent, at distance, a composite entry, a hand-written signature's entrypipelineas a handler argument, the enclosing layer contributes the key (anchored)withSupabaseshape), unanchoredwithSupabase), anchored or not, inline-arrow leaf taking(req, ctx)middleware-ordermessage: actxmismatch on 5.4 to 5.8, implicitanyon 5.9+; also throws at builddefineMiddlewarecontributorAll 25 right-order shapes compile on every version and keep their
ctxtyping, including abeforemiddleware 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 hasbeforeaccepts an object literal, an interface (Deno'sServeHandlerInfoshape) andobjectas its host argument, and is assignable toFetchHandler, a Deno handler and a Workersfetch.typecheck,lint,format:check,test(165 passed),build,smoke,typecheck:min,typecheck:consumer,check-exports, JSR dry run,test:deno,test:buntsc --noEmiton the source, including every new@ts-expect-erroranda middleware with a hand-written signature, on all ten versionstest/ts-floor/consumer.tsagainst the built.d.ts, on all ten versions@supabase/serversrc, examples and e2e,@supabase-labs/middleware-openfeature, an internal dependent) against this build vs 1.0.0, all ten versionswithSupabasenesting testsdeno checkwith@supabase/server1.9.2 on this build, Deno 2.1.4, 2.4.5, 2.5.0, 2.9.8Merge Danger
Door: one-way
Blast Radius: low
defineMiddlewarecontributor 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 actxmismatch (5.4 to 5.8) or implicitany(5.9+) rather than themiddleware-ordermessage. ThedefineMiddlewarecase 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.before, theBeforeparameters, the three exported types and theSymbol.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.Beforeas the fifth, and aMiddleware<…>,EntryorSingleKeyEntryannotation without it is a type error rather than a dropped rule.@supabase/server'swithOAuthProtectedResourceneeds both (FUNC-1181).before: ['authMode']is refused behind a gate that allows'none'too.ctxparameter of a middleware withbeforecarries{ readonly [key: string]: any }. It only widens what callers may pass, which is already any object, and never reaches thectxa handler reads.Entry<infer C, infer In>no longer matches an entry withbefore; the engine's own folds matchEntry<…, string>. None of the checked dependents match onEntry.Refs FUNC-1180