Skip to content

Search docs

Jump between documentation pages.

Browse docs

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.

every() runs each layer in order
  1. 01layer 1requestId()tag the request
  2. 02layer 2bearerAuth()verify the token
  3. 03layer 3rateLimit()throttle the shared admin bucket
  4. 04resultHandlerone reusable adminStack value
Symbol-keyed security markers such as CORS, CSRF, session, and secure-headers are forwarded onto the merged bundle so boot-time guards still see them.
ts
import { App, every, requestId, bearerAuth, rateLimit, timingSafeEqual } from "@daloyjs/core";

const app = new App();

const adminStack = every(
  requestId(),
  bearerAuth({
    realm: "admin",
    validate: (token) => timingSafeEqual(token, process.env.ADMIN_TOKEN!),
  }),
  rateLimit({ windowMs: 60_000, max: 30, groupId: "admin" }),
);

app.use(adminStack);

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.

some() accepts any one proof
requestauth gate runs each bundle in orderfirst to pass wins
proof AbearerAuth()valid bearer token
proof Bsession authsigned cookie with a user id
acceptedFirst passing bundle winsits ctx.state and headers are preserved
A bundle that returns a Response counts as a denial and the next bundle gets a chance. If every bundle denies, the first denial wins.
ts
import { App, every, some, bearerAuth, session, timingSafeEqual } from "@daloyjs/core";

const app = new App();

const sessionAuth = every(
  session({ secret: process.env.SESSION_SECRET! }),
  {
    beforeHandle(ctx) {
      const sessionState = ctx.state.session as
        | { data?: Record<string, unknown> }
        | undefined;

      if (typeof sessionState?.data?.userId === "string") return;

      return new Response("Unauthorized", { status: 401 });
    },
  },
);

app.use(
  some(
    bearerAuth({
      realm: "api",
      validate: (token) => timingSafeEqual(token, process.env.PUBLIC_API_TOKEN!),
    }),
    sessionAuth,
  ),
);

Semantics worth knowing:

  • The first bundle that resolves without throwing or returning a Response wins. Its context mutations, including headers and ctx.state, are preserved.
  • A bundle that returns a Response is treated as a denial, and the next bundle gets a chance. If every bundle returns a denial, the first Response is sent.
  • Since 1.20.0 each bundle runs as a transaction over ctx.state. When it throws or returns a Response, every string or symbol key it added or changed is rolled back before the next bundle runs. A revoked token's ctx.state.user, or the "auth passed" record of a bearerAuth() that passed inside an every(bearerAuth(...), requireScopes([...])) branch whose scope check then denied, never reaches the winning branch, requireScopes(), requireRoles(), tenantFromClaim() or the handler. bearerAuth() and jwk() also set ctx.state.user only after their verify revocation 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-Authenticate challenge you want clients to see first.
  • Since 1.22.0 a bundle in optional mode (for example httpSignatureAuth({ 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 declares auth: answers 401 to 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, so some(every(bearerAuth(a), requireScopes(["a"])), every(bearerAuth(b), requireScopes(["b"]))) accepts a caller holding either scope. The conditional scope gate is still ordered ahead of responseCache() / idempotency() replays, so a stored response is never served past it. When a bundle pairs a preBody auth hook with a default-phase requireScopes(), the whole some() selects in preBody, ahead of body parsing and requestDecompression().
  • A bundle that returns anything else that is not nothing (false, { status: 401 }) has neither passed nor denied. Inside some() it counts as a failed branch, including when the value comes from the preBody of a bundle that also has a beforeHandle. Inside every() the request is refused with a 500, also when the every() bundle is wrapped by except(), some() or markAuthHook(). To reject, throw a typed error or return a Response.
  • Only the preBody/beforeHandle selection strategy changes. afterHandle, onSend, onResponse, and onError from 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.

ts
import { App, except, bearerAuth, timingSafeEqual } from "@daloyjs/core";

const app = new App();

app.use(
  except(
    ["/health", "/openapi.json", "/docs/**"],
    bearerAuth({ validate: (token) => timingSafeEqual(token, process.env.API_TOKEN!) }),
  ),
);

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 true to 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:

ts
app.use(except(["/admin/**"], cors({ origin: ["https://partner.example.com"] })));

// POST /api/orders from https://partner.example.com -> allowed
// POST /admin/users from https://partner.example.com -> 403, the policy is off here

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.

ts
import {
  App,
  every,
  except,
  requestId,
  secureHeaders,
  bearerAuth,
  timingSafeEqual,
} from "@daloyjs/core";

const app = new App();

const protectedStack = every(
  requestId(),
  secureHeaders(),
  except(
    ["/health", "/openapi.json", "/docs/**"],
    bearerAuth({ validate: (token) => timingSafeEqual(token, process.env.API_TOKEN!) }),
  ),
);

app.use(protectedStack);
Edit this page on GitHub

Last updated