Skip to content

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.

src/middleware/auth.ts
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 } });
},
});

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:

src/middleware/context.ts
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" });
},
});

Middleware that needs an injected service declares a requirement interface through a typed helper, and lists the same names in requiresServices:

src/middleware/rate-limit.ts
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.

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.

src/routes/middleware.ts
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
      • Directorytenants/
        • Directory$tenantId/
          • middleware.ts withTenant
          • Directoryprojects/
            • route.ts sees requestId, session, auth, tenant

A route file can add middleware for all of its methods, or one method can add its own:

src/routes/reports/route.ts
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.

With authentication configured, a folder can require it for every route below. Export a requireAuth guard the way you export other middleware:

src/routes/(staff)/middleware.ts
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
      • Directorytenants/
        • Directory$tenantId/
          • middleware.ts re-exports a session-only guard
          • Directoryprojects/
            • route.ts accepts session

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({ ... }), with requireAuth imported by name, under an alias, or called on a namespace import as core.requireAuth({ ... })
  • a const bound 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.

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.

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:

src/routes/(private)/middleware.ts (before)
export { requireAuth } from "../../middleware/auth.js";
src/routes/(private)/middleware.ts (after)
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 authentication reserves ctx.auth, so a middleware that provides auth fails routa check with ROUTA_CONTEXT_RESERVED. Remove the old guard in the same change, and read ctx.auth.principal where handlers read the old context.
  • OpenAPI declares the scheme in components.securitySchemes under its scheme name. Operations below the guard list that name in security instead of the old middleware’s openapi.security entry, and every other operation gains {} and the scheme as optional alternatives.
  • The 401 responses become the authenticationRequired and authenticationFailed problem documents with a WWW-Authenticate challenge, in place of the old middleware’s reject. Every operation also documents authenticationFailed, since a presented invalid credential fails on public routes too.
  • A 401 reject or route outcome you keep must require the same literal property as Routa’s problem documents, with its own value, or routa check reports ROUTA_RESPONSE_STATUS_AMBIGUOUS. Routa’s bodies require literal type and title, so use one of them, such as type: z.literal("https://example.com/problems/unauthorized"). A literal on a property Routa’s bodies lack, such as kind, tells nothing apart. An outcome that reuses the name of one Routa adds to the operation, such as authenticationFailed, reports ROUTA_OUTCOME_NAME_COLLISION.
  • Routa’s authentication outcomes set no cookies, so a guard that cleared a stale session cookie on 401 no longer does.
  • Every outcome name must be unique across a method’s responses and its whole chain. A route outcome or a second middleware reusing a reject name such as forbidden fails routa check (ROUTA_OUTCOME_NAME_COLLISION) and app registration. TypeScript also flags a route outcome named like a reject of the route’s own middleware.
  • A reject reachable from a HEAD route cannot declare a schema (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 await or return next(). 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 createMiddleware export, or of a typed helper’s, such as defineRateLimitMiddleware({ ... }). Spreading an array or computing the value at runtime produces ROUTA_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 of routa check.
  • provides is an object literal or a const object literal it names. Anything else produces ROUTA_MIDDLEWARE_PROVIDES_UNRESOLVED.
  • ctx.services is reserved for injected services. Providing services or passing it to next() fails TypeScript and routa check (ROUTA_CONTEXT_RESERVED); see the migration.
  • With authentication configured, ctx.auth is reserved too, and Routa resolves it before the first middleware runs. A middleware reads it with requires: ["auth"]. Providing auth fails routa check (ROUTA_CONTEXT_RESERVED) and registration.

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.