Middleware
Routa middleware is part of the contract, not a side effect. Each middleware declares the context keys it requires, the context it provides, and the early responses it can return. Auth, tenant loading, and request enrichment stay visible in types, in generated metadata, and in OpenAPI.
import { createMiddleware } from "@routa-ts/core";import { z } from "zod";
export const withAuth = createMiddleware({ requires: ["session"], provides: { auth: z.object({ userId: z.string(), }), }, rejects: { unauthorized: { status: 401, schema: z.object({ message: z.string() }), }, }, run: ({ ctx, next }) => { if (!ctx.session.authenticated || !ctx.session.userId) { return { type: "unauthorized", data: { message: "Authentication required." } }; }
return next({ auth: { userId: ctx.session.userId } }); },});How It Works
Section titled “How It Works”requires lists context keys that must already exist. Routa checks the order statically,
so a middleware that requires session before anything provides it fails
routa check with ROUTA_MIDDLEWARE_ORDER rather than at request time.
provides maps new context keys to schemas. Calling next({ auth }) parses every declared
value before Routa merges any of them into ctx, so handlers receive transformed schema
outputs and never a partial update. Undeclared top-level keys are omitted. A normal
z.object() strips unknown keys inside its value; add .strict() when those nested keys
must be rejected. This validation runs in both routa dev and routa start, independent
of the response-validation policy.
rejects declares early responses. Returning { type: "unauthorized", data } ends the
request with the declared status and skips the rest of the chain, including the handler.
A reject is a full outcome: it may omit schema to be bodyless and declare headers and
cookies, and it follows the same declaration rules, response-validation policy, and
OpenAPI projection as a route outcome. A middleware can only return its own rejects, and a
handler only its route’s responses.
A middleware that calls next() continues the request, and must return what next()
resolves to. That value is opaque: middleware cannot read it, copy it, or add headers or
cookies to it, so the outcome the handler (or a later middleware) selected is the response.
TypeScript rejects a changed value, and Routa answers 500 Invalid handler output when a
middleware returns anything else after next(), including one of its own rejects. Routa
validates and serializes the selected outcome before next() resolves, so changing the
handler’s data, header, or cookie objects afterwards does not change the response.
input is optional and works exactly like a route’s input. It lets middleware read
validated headers, cookies, or query values without the route declaring them:
export const withRequest = createMiddleware({ input: { headers: z.object({ "x-request-id": z.string().optional(), }), }, provides: { requestId: z.string(), }, run: async ({ input, next }) => { return next({ requestId: input.headers["x-request-id"] ?? "local-request" }); },});Service Requirements
Section titled “Service Requirements”Middleware that needs an injected service declares a requirement
interface through a typed helper, and lists the same names in requiresServices:
import { createMiddleware } from "@routa-ts/core";
export interface RateLimitRequirements { limiter: { take(key: string): Promise<boolean> };}
const defineRateLimitMiddleware = createMiddleware<RateLimitRequirements>();
export const withRateLimit = defineRateLimitMiddleware({ requiresServices: ["limiter"], rejects: { tooManyRequests: { status: 429 } }, run: async ({ ctx, next }) => { if (!(await ctx.services.limiter.take("anonymous"))) { return { type: "tooManyRequests" }; }
return next(); },});The callback sees RateLimitRequirements as ctx.services. routa check verifies every
placement provides compatible services before the middleware runs; see
Middleware Service Requirements.
Where Middleware Applies
Section titled “Where Middleware Applies”Folder Inheritance
Section titled “Folder Inheritance”A middleware.ts file applies to every route in its folder and below. Export or re-export
middleware contracts from it; the export order is the execution order.
export { withRequest, withSession } from "../middleware/context.js";Context accumulates as routing gets more specific, which is why a group folder is a useful place to attach a chain:
Directorysrc/routes/
- middleware.ts
withRequest,withSession Directory(private)/
- middleware.ts
withAuth Directoryadmin/
- middleware.ts
withAdmin Directoryaudit-events/
- route.ts sees requestId, session, auth, admin
- middleware.ts
Directorytenants/
Directory$tenantId/
- middleware.ts
withTenant Directoryprojects/
- route.ts sees requestId, session, auth, tenant
- middleware.ts
- middleware.ts
- middleware.ts
Per Route and Per Method
Section titled “Per Route and Per Method”A route file can add middleware for all of its methods, or one method can add its own:
export default route({ middleware: [withRateLimit], get: createRoute({ middleware: [withReportAccess], // ... }), post: createRoute({ // runs withRateLimit, but not withReportAccess // ... }),});The full chain for a method is folder middleware, then route-level middleware, then method-level middleware.
Authentication Requirements
Section titled “Authentication Requirements”With authentication configured, a folder can
require it for every route below. Export a requireAuth
guard the way you export other middleware:
import { requireAuth } from "@routa-ts/core";
export const signedIn = requireAuth({ schemes: ["session", "userToken"] });The guard runs at its export position, before route and method middleware, and returns
authenticationRequired (401) to an anonymous request. Handlers below it see ctx.auth
narrowed to the authenticated branch, with ctx.auth.scheme typed "session" | "userToken".
A middleware with requires: ["auth"] still sees the anonymous-or-authenticated union.
Guards compose down the chain by intersection. An operation accepts only the schemes every
requireAuth from the root folder to the method allows, and Routa authenticates only
credentials of those schemes:
Directorysrc/routes/
Directory(staff)/
- middleware.ts
signedIn: session or userToken Directoryreports/
- route.ts GET accepts session or userToken; POST adds
requireAuth({ schemes: ["session"] })and accepts session
- route.ts GET accepts session or userToken; POST adds
Directorytenants/
Directory$tenantId/
- middleware.ts re-exports a session-only guard
Directoryprojects/
- route.ts accepts session
- middleware.ts
A descendant cannot remove an inherited requirement or widen its schemes. A route guard that
lists "serviceKey" under this folder still accepts only "session" and "userToken", and
routa check warns with ROUTA_AUTH_REQUIREMENT_WIDENED. Guards that share no scheme fail
with ROUTA_AUTH_REQUIREMENT_EMPTY.
Routa runs only the folder exports routa check reads. It reads a guard written as a literal
requireAuth(...) call bound to a const:
export const signedIn = requireAuth({ ... }), withrequireAuthimported by name, under an alias, or called on a namespace import ascore.requireAuth({ ... })- a
constbound to such a guard, declared in the folder or imported:const guard = requireAuth(); export const signedIn = guard; - a re-export of either form:
export { member as signedIn } from "../../guards.js"
A guard built any other way, through a factory call at any depth, a conditional, a
destructuring, or a let or var binding, fails with ROUTA_AUTH_REQUIREMENT_UNRESOLVED.
routa check follows your project’s functions, named imports, and re-exports to find it, but
not package code. Exporting a factory function itself is fine, since a function is not a guard.
Startup is the backstop. For every route, Routa loads each folder middleware.ts above it and
refuses to start when one exports a requireAuth guard the generated metadata does not list,
such as one a package builds, even with its own copy of @routa-ts/core, or one added after the
last routa generate. routa dev, routa start, and createTestApp all fail the same way:
src/routes/(staff)/middleware.ts exports signedIn, a requireAuth() guard .routa/routes.gen.ts does not list, so it would not run and the routes below would be public. Write it as export const signedIn = requireAuth({ ... }), or re-export a const declared that way, then run routa generate.Security Visibility
Section titled “Security Visibility”Middleware can describe what an operation requires without Routa implementing any of it:
createMiddleware({ openapi: { security: [{ bearerAuth: [] }], permissions: ["audit.read"], }, // Application-owned credential and permission logic in run.});Routa emits security and x-routa-authz on every operation the middleware covers, and
routa openapi breaking reports when a previously public operation becomes authenticated.
Migrating an Application-Owned Guard
Section titled “Migrating an Application-Owned Guard”An application can keep its own authentication middleware, such as the withAuth example
above. To move a folder to Routa’s guard, configure a credential scheme that reads the same
credential, move the verification into its authenticator, and export requireAuth from the
folder instead:
export { requireAuth } from "../../middleware/auth.js";import { requireAuth } from "@routa-ts/core";
export const signedIn = requireAuth({ schemes: ["session"] });Routa treats only the requireAuth imported from @routa-ts/core as the built-in guard, so an
application middleware that is also named requireAuth stays ordinary middleware. The names
collide once one module imports both. Rename the application guard, such as requireSession,
or import the core one under an alias:
import { requireAuth as requireRoutaAuth } from "@routa-ts/core". Give the folder export its
own name, such as signedIn, because it cannot share the imported name.
What changes with the move:
- Configuring
authenticationreservesctx.auth, so a middleware that providesauthfailsrouta checkwithROUTA_CONTEXT_RESERVED. Remove the old guard in the same change, and readctx.auth.principalwhere handlers read the old context. - OpenAPI declares the scheme in
components.securitySchemesunder its scheme name. Operations below the guard list that name insecurityinstead of the old middleware’sopenapi.securityentry, and every other operation gains{}and the scheme as optional alternatives. - The
401responses become theauthenticationRequiredandauthenticationFailedproblem documents with aWWW-Authenticatechallenge, in place of the old middleware’s reject. Every operation also documentsauthenticationFailed, since a presented invalid credential fails on public routes too. - A
401reject or route outcome you keep must require the same literal property as Routa’s problem documents, with its own value, orrouta checkreportsROUTA_RESPONSE_STATUS_AMBIGUOUS. Routa’s bodies require literaltypeandtitle, so use one of them, such astype: z.literal("https://example.com/problems/unauthorized"). A literal on a property Routa’s bodies lack, such askind, tells nothing apart. An outcome that reuses the name of one Routa adds to the operation, such asauthenticationFailed, reportsROUTA_OUTCOME_NAME_COLLISION. - Routa’s authentication outcomes set no cookies, so a guard that cleared a stale session
cookie on
401no longer does.
- Every outcome name must be unique across a method’s
responsesand its whole chain. A route outcome or a second middleware reusing a reject name such asforbiddenfailsrouta check(ROUTA_OUTCOME_NAME_COLLISION) and app registration. TypeScript also flags a route outcome named like a reject of the route’s ownmiddleware. - A reject reachable from a
HEADroute cannot declare aschema(ROUTA_RESPONSE_BODYLESS_SCHEMA). - Rejects that share a status with each other or with route outcomes must be distinguishable; see Outcomes That Share a Status.
- Reject statuses must be 4xx or 5xx (
ROUTA_MIDDLEWARE_REJECT_STATUS). - Always
awaitor returnnext(). Calling it without awaiting drops the downstream result and can leave the request hanging. next()may be called at most once per middleware invocation.- Middleware must be referenced as a direct identifier of a
createMiddlewareexport, or of a typed helper’s, such asdefineRateLimitMiddleware({ ... }). Spreading an array or computing the value at runtime producesROUTA_MIDDLEWARE_UNRESOLVED, because Routa could not check the contract. - A middleware that requires services must run where each service exists with a compatible
type. A missing service produces
ROUTA_SERVICES_UNAVAILABLE, and an incompatible one fails the TypeScript step ofrouta check. providesis an object literal or aconstobject literal it names. Anything else producesROUTA_MIDDLEWARE_PROVIDES_UNRESOLVED.ctx.servicesis reserved for injected services. Providingservicesor passing it tonext()fails TypeScript androuta check(ROUTA_CONTEXT_RESERVED); see the migration.- With
authenticationconfigured,ctx.authis reserved too, and Routa resolves it before the first middleware runs. A middleware reads it withrequires: ["auth"]. Providingauthfailsrouta check(ROUTA_CONTEXT_RESERVED) and registration.
Limits
Section titled “Limits”Routa makes security context and early responses visible at the HTTP boundary. Without
authentication in createRouta, Routa never authenticates a request: middleware such as
the example above owns it. With it, Routa reads Bearer, API-key, session-cookie, and
custom credentials, calls one authenticator, and enforces
requireAuth inline and in folders; see
Authentication. Your application still owns
credential verification, authorization rules, policy correctness, and secrets.