Middleware combinators
DaloyJS exposes three composition primitives for Hooks bundles. Use every() to package a full stack, some() to accept any one valid proof, and except() to skip a gate for specific paths.
every(): run a whole stack in order
every(...layers) merges several Hooks bundles into one that runs each layer in registration order. It is equivalent to calling app.use(...) for each bundle, but lets you name and reuse a curated stack. All lifecycle phases compose: onRequest and onResponse run in order, preBody, beforeHandle, and onError stop on the first Response, and afterHandle plus onSend thread the value through each layer.
- 01layer 1requestId()tag the request
- 02layer 2bearerAuth()verify the token
- 03layer 3rateLimit()throttle the shared admin bucket
- 04resultHandlerone reusable adminStack value
some(): accept any one proof of identity
some(...layers) runs each bundle's auth gate in order and accepts the request as soon as one bundle passes without throwing or returning a Response. When every candidate uses preBody, selection happens before body I/O. Mixed stacks defer candidate selection to beforeHandle for compatibility. Use it for routes that accept more than one credential style, such as a bearer token or a signed session cookie.
Semantics worth knowing:
- The first bundle that resolves without throwing or returning a
Responsewins. Its context mutations, including headers andctx.state, are preserved. - A bundle that returns a
Responseis treated as a denial, and the next bundle gets a chance. If every bundle returns a denial, the firstResponseis sent. - Since 1.20.0 each bundle runs as a transaction over
ctx.state. When it throws or returns aResponse, every string or symbol key it added or changed is rolled back before the next bundle runs. A revoked token'sctx.state.user, or the "auth passed" record of abearerAuth()that passed inside anevery(bearerAuth(...), requireScopes([...]))branch whose scope check then denied, never reaches the winning branch,requireScopes(),requireRoles(),tenantFromClaim()or the handler.bearerAuth()andjwk()also setctx.state.useronly after theirverifyrevocation hook accepts. - When every bundle fails and the first denial was a thrown error, that error is rethrown. Put the auth method whose status and
WWW-Authenticatechallenge you want clients to see first. - Since 1.22.0 a bundle in
optionalmode (for examplehttpSignatureAuth({ optional: true })) that sees no credential does not win the selection: the remaining bundles still run, so a caller presenting a bearer token for a later bundle is authenticated by it instead of being passed through anonymously. The unauthenticated pass-through is honoured only when no bundle denies the request; any denial wins over it. The usual rule still applies afterwards: a route that declaresauth:answers401to a pass-through, routes without one proceed. - Since 1.22.0
requireScopes()inside a bundle applies to that bundle only.some()no longer advertises an all-of union of every bundle's scopes, sosome(every(bearerAuth(a), requireScopes(["a"])), every(bearerAuth(b), requireScopes(["b"])))accepts a caller holding either scope. The conditional scope gate is still ordered ahead ofresponseCache()/idempotency()replays, so a stored response is never served past it. When a bundle pairs apreBodyauth hook with a default-phaserequireScopes(), the wholesome()selects inpreBody, ahead of body parsing andrequestDecompression(). - A bundle that returns anything else that is not nothing (
false,{ status: 401 }) has neither passed nor denied. Insidesome()it counts as a failed branch, including when the value comes from thepreBodyof a bundle that also has abeforeHandle. Insideevery()the request is refused with a500, also when theevery()bundle is wrapped byexcept(),some()ormarkAuthHook(). To reject, throw a typed error or return aResponse. - Only the
preBody/beforeHandleselection strategy changes.afterHandle,onSend,onResponse, andonErrorfrom every bundle still compose normally.
Two more guarantees hold however some() is mounted. An optional-mode branch never counts as authentication just because an earlier hook (an app-level API key, mTLS) already authenticated the request: the strict branches still run. And when a mixed stack moves the whole some() to beforeHandle, any pre-body gate inside it (requireRoles(), bearerAuth()) is still ordered ahead of responseCache() and idempotency(), so a stored response is never replayed to a caller the gate would refuse.
except(): apply everywhere but a few paths
except(when, hooks) runs a bundle on every request except those matching when. The canonical use is applying auth everywhere except health checks, OpenAPI JSON, and docs assets.
The when matcher accepts:
- A path string starting with
/.*matches one non-empty path segment with no slash, and**matches any suffix. - An array of path patterns.
- A predicate function that receives the request context and returns
trueto skip the gated bundle.
Path matching uses the same new URL(request.url).pathname view the router sees. It is case-sensitive, exact for non-wildcard patterns, and does not add a rewrite or extra decode step. It also ignores trailing slashes on both the pattern and the request, just as the router does. So /docs/ is judged as /docs and never as a child of /docs/*, and except("/health/") covers /health too. That makes exemptions fail closed for case changes, trailing-slash mismatches, and encoded traversal tricks: a pattern can only exempt the route that actually runs.
Since 1.3.7 the Node and AWS Lambda adapters make this view and the router agree. A request-target such as /admin/%2e%2e/health or /admin\..\health is canonicalized by the Node adapter before routing, so except() and the router both see /health. A Host header carrying \ / ? # @ % or whitespace (for example h\health?) is refused with 400 by the Node and AWS Lambda adapters instead of shifting bytes into the path an exemption matches on. Router params and wildcards never bind . or ...
The wrapped bundle's preBody and beforeHandle gates are skipped. Its onRequest, afterHandle, onSend, and onResponse phases still run. Wrap each bundle with except() individually if you need to gate different phases with different rules.
A wrapped cors() policy is off on the exempted paths. It adds no CORS headers there, and since 1.20.0 it no longer lets the cross-origin write guard accept a POST, PUT, PATCH or DELETE from its origins there:
The guard runs before any hook, so it cannot evaluate a function when. With a predicate, the wrapped cors() never relaxes the guard on any path. Use path patterns when an exempted cors() must still accept cross-origin writes elsewhere.
every() and some() also hand App settings that bundles learn at registration (the behindProxy posture for rateLimit() and loginThrottle(), the body limit for idempotency(), the production flag) to every composed bundle. Before 1.20.0 only the first bundle received them, so in every(rateLimit(...), loginThrottle(...)) behind a proxy the throttle keyed every client onto the proxy's address.
Since 1.22.0 a request budget inside every() is also visible to the rest of the chain. In app.use(every(requestId(), rateLimit({ max: 2 }))) followed by app.use(bearerAuth(...)), a 401 from bearerAuth() charges the limiter like any other failed attempt (previously the bundle hid the budget from later rejections). A budget is charged at most once per request, however the bundles nest or are wrapped (markAuthHook(every(...)), except(path, every(...)), a spread). except(path, requireScopes([...])) likewise stops advertising its scopes on the exempted paths: the gate still runs, and still runs ahead of a replay, on every other path.
The boot guards that catch responseCache() / idempotency() mounted ahead of tenancy(), rateLimit() or loginThrottle() look inside every() bundles too since 1.22.0, and compare the earliest replay against the latest tenancy or budget layer, so a route-level rateLimit() registered after a global responseCache() is reported.
Composing the three
The primitives nest. A common production shape is to run correlation, secure headers, and authentication everywhere, but skip the auth gate for health and documentation endpoints.