Configuration
Routa reads its runtime configuration from the default export of src/routa.ts. The file
is required — Routa reports ROUTA_PROJECT_REQUIRED without it — even when it sets no
options.
import { createRouta } from "@routa-ts/core";
export default createRouta({ host: "127.0.0.1", port: 3000, lifecycleHeaders: true, responseValidation: "always",});host?: stringThe interface the server binds to. Defaults to 127.0.0.1, which accepts local
connections only. Container and platform deployments generally need 0.0.0.0; set that
through the HOST environment variable so local development keeps the safer default.
Overridden by: HOST.
port?: numberThe TCP port to listen on. Defaults to 3000. When the port is unavailable the server
logs api.start_failed at error level and sets a non-zero exit code.
Overridden by: PORT.
logger
Section titled “logger”logger?: RoutaLogger | falseThe logger instance used for runtime lifecycle events, request logging, and ctx.logger
in every handler. Defaults to createLogger(), the built-in console logger at info
level.
Set false to disable logging entirely. Handlers still receive ctx.logger, implemented
as a complete no-op with the same type, so handler code never needs a configuration guard.
import { createRouta } from "@routa-ts/core";import { createLogger } from "@routa-ts/core/logger";
export default createRouta({ logger: process.env.NODE_ENV === "test" ? false : createLogger({ level: "debug" }),});Because RoutaLogger is a structural type, any object implementing its members is valid,
including an adapter over Pino, Winston, or a hosted logging SDK. See
Core reference for the full member list.
Routa enables logging when a logger is configured. Set logger: false to disable it. The
runtime emits two startup lifecycle events and two request events:
| Event | Level | Data |
|---|---|---|
api.started |
info |
host, port, routes |
api.start_failed |
error |
error, host, port |
http.request |
info |
method, path, status, durationMs |
http.error |
error |
method, path, status, error, name, stack, optional issues |
With application services, Routa also logs
services.cleanup_failed at error level, with a failures list, when a cleanup callback
throws or rejects.
http.error is emitted only for responses with a status of 500 or above. When response
or middleware context validation fails, issues contains only Zod code and path
fields. Routa never logs the rejected response or context values.
lifecycleHeaders
Section titled “lifecycleHeaders”lifecycleHeaders?: booleanWhether to emit deprecation headers on routes that declare deprecation. Defaults to
false. When enabled, a deprecated operation responds with:
| Header | Emitted when |
|---|---|
Deprecation: true |
The route declares any deprecation |
Sunset: <date> |
deprecation.sunset is set |
Link: <target>; rel="successor-version" |
deprecation.replacement is set |
Routes without deprecation are unaffected regardless of this setting. While this is on,
Routa owns those headers on deprecated routes, and an outcome that declares deprecation,
sunset, or (when a replacement is set) link in headers fails. routa check does not run
your code, so it treats any value other than an omitted key or a literal false as possibly on
and applies the same ownership rules. Declare a literal false to opt a route graph out.
responseValidation
Section titled “responseValidation”responseValidation?: "development" | "always"Controls when Routa parses handler responses and middleware reject responses through
their declared Zod schemas and compares the parsed value with the handler value. Defaults to
"development":
| Value | routa dev |
routa start |
|---|---|---|
"development" |
Parse and compare response data | Do not parse or compare |
"always" |
Parse and compare response data | Parse and compare response data |
The same policy applies to declared response header values.
Routa always checks the result envelope and response type, requires data for an outcome
with a schema and rejects it for one without, selects the declared status, checks declared
response headers (names, required headers, and safe values), and performs JSON
serialization. Parsing and comparing fail the response as invalid handler output when
the data does not match its schema or when the schema would change it. Routa never sends the
parsed value. Set "always" when production must reject response drift. Response schemas
must not change values; TypeScript rejects the common cases and routa check reports
ROUTA_RESPONSE_SCHEMA_MUTATION for the rest.
import { createRouta } from "@routa-ts/core";
export default createRouta({ responseValidation: "always",});This setting does not affect context passed through middleware provides. Routa always
parses those values before adding them to downstream context.
services
Section titled “services”services?: ApplicationServicesFactoryThe application services factory, declared through a defineServices helper. Routa runs it
once before the server listens and passes its services to handlers as ctx.services.
Omit it to keep every dependency a plain import. See
Services for the contract rules, cleanup, and
failure behavior.
import { createRouta } from "@routa-ts/core";import { defineAppServices } from "./services.js";
export default createRouta({ services: defineAppServices(() => ({ clock: { now: () => new Date() } })),});routa check reads services from source: a member of the createRouta object, or of a
const object literal, local or imported, that you pass to createRouta or spread into it.
A spread or computed key it cannot read may hide services unless a visible services
member follows it, so routa check warns with
ROUTA_SERVICES_SPREAD_UNRESOLVED.
Startup refuses services that routa generate did not read, and generated services that
src/routa.ts no longer configures.
authentication
Section titled “authentication”authentication?: { principal: PrincipalSchema; schemes: Record<string, CredentialScheme>; priority?: readonly string[]; multipleCredentials?: "priority" | "reject";}Turns on credential orchestration for every route. Routa reads each request’s credentials,
calls one authenticator once, validates the principal it returns, and gives every handler
ctx.auth. Omit it and Routa provides no ctx.auth: an application without
authentication behaves exactly as before, its own middleware may still provide auth, and
requireAuth fails routa check.
| Field | Purpose |
|---|---|
principal |
One Zod schema whose output has string id and type fields. It validates every principal |
schemes |
Credential schemes keyed by name. Each name is also the OpenAPI security scheme key |
priority |
The order Routa selects among presented credentials. Lists every scheme once. Defaults to declaration order |
multipleCredentials |
"priority" (default) authenticates the first presented credential by priority. "reject" answers 400 |
Declare schemes with three built-in descriptors, or with custom for any other credential.
Each takes the same authenticate function and returns the same result shape.
| Descriptor | Reads | Challenge |
|---|---|---|
bearer |
Authorization: Bearer <token> |
Bearer |
apiKey({ header }) |
The value of one request header | ApiKey |
sessionCookie({ cookie }) |
The value of one request cookie | Session |
custom({ transport, openapi }) |
One declared header, Authorization auth-scheme, or cookie |
The scheme name |
Each scheme needs its own transport. Two Bearer schemes, two API-key schemes whose headers
match ignoring case, two session schemes with the same cookie, an API-key header named
Authorization or Cookie, and a custom transport another scheme already reads all fail
routa check with
ROUTA_AUTH_TRANSPORT_OVERLAP.
Verify several token or key formats inside one authenticator instead. A scheme name starts
with a letter and uses only letters, digits, ., -, and _. A header or cookie name is an
RFC 9110 token: letters, digits, and !#$%&'*+-.^_`|~.
import { apiKey, bearer, createRouta, sessionCookie } from "@routa-ts/core";import { z } from "zod";import { findServiceKey, findSession, verifyAccessToken } from "./credentials.js";
const Principal = z.discriminatedUnion("type", [ z.object({ type: z.literal("user"), id: z.string(), email: z.string() }), z.object({ type: z.literal("service"), id: z.string() }),]);
export default createRouta({ authentication: { principal: Principal, schemes: { userToken: bearer({ challenge: { realm: "api" }, authenticate: async (token) => { const user = await verifyAccessToken(token); return user ? { type: "authenticated", principal: { type: "user", id: user.id, email: user.email } } : { type: "rejected" }; }, }), serviceKey: apiKey({ header: "x-api-key", authenticate: async (key) => { const service = await findServiceKey(key); return service ? { type: "authenticated", principal: { type: "service", id: service.id } } : { type: "rejected" }; }, }), session: sessionCookie({ cookie: "session", authenticate: async (value) => { const user = await findSession(value); return user ? { type: "authenticated", principal: { type: "user", id: user.id, email: user.email } } : { type: "rejected" }; }, }), }, priority: ["userToken", "session", "serviceKey"], },});verifyAccessToken, findServiceKey, and findSession stand for your own verification code,
such as a JWT library call or a session store lookup; Routa verifies nothing itself. TypeScript
checks each authenticator’s principal against the principal schema’s input, and a rejection
carries no other fields. The second argument holds the configured logger and, when
src/routa.ts declares them, the application services.
When a request presents credentials of several schemes, Routa selects the first by priority
and calls only that scheme’s authenticator. A rejected selected credential fails; Routa never
falls back to the next one. TypeScript rejects a priority entry that names no scheme, and
routa check also reports a duplicate or missing entry. Set multipleCredentials: "reject" to
answer ambiguousCredentials (400) instead, before any authenticator runs.
Runtime behavior gives the full
selection rules.
routa check reads scheme names, descriptor kinds, header and cookie names, custom
transports and openapi metadata, challenge overrides, priority, and multipleCredentials
from source, because they change the HTTP contract. Write authentication as an object literal in createRouta, or as a const object
literal you pass or spread into it, with a plain key for each scheme and a bearer({ ... }),
apiKey({ ... }), sessionCookie({ ... }), or custom({ ... }) call, or a const bound to
one, as its value. Write header, cookie, transport, openapi, priority, and
multipleCredentials as literals. Anything it cannot
read fails with
ROUTA_AUTH_CONFIG_UNRESOLVED.
Authenticators and custom extractors are ordinary runtime functions and may use any
expression. Startup refuses authentication that routa generate did not read, and scheme
names, a priority order, or a multipleCredentials mode that differ from the generated ones.
Run routa generate after changing any of them.
Runtime behavior describes how each
request’s credentials resolve.
Environment Variables
Section titled “Environment Variables”Environment variables are read at server start and take precedence over src/routa.ts.
| Variable | Overrides | Default |
|---|---|---|
HOST |
host |
127.0.0.1 |
PORT |
port |
3000 |
There is no environment override for logger, lifecycleHeaders, responseValidation,
services, or authentication; branch on your own variables inside src/routa.ts instead.
Precedence
Section titled “Precedence”environment variable > src/routa.ts > Routa default