Runtime Behavior
Routa v0 runs on Hono. This page documents the request pipeline, every status Routa
produces on its own, and the shape of its error responses. Behavior described here comes
from createHonoApp and applies to routa dev, routa start, and any app you build
directly.
Request Pipeline
Section titled “Request Pipeline”For each matched route, in order:
- Credential resolution. Only when
src/routa.tsconfiguresauthentication. Routa reads the request’s credentials and setsctx.auth, or ends the request withauthenticationFailedor, in strict mode,ambiguousCredentials. See Authentication. - Accept negotiation. A request whose
Acceptheader cannot be satisfied by JSON receives406 Not Acceptable. A missingAcceptheader is treated as acceptable. - Input parsing. Declared
params,query,headers,cookies, andbodyare parsed with their Zod schemas. The body is read at most once per request and shared between middleware and the handler. - Context creation.
createContext()runs if provided. It must return a plain object. - Middleware chain. Each middleware’s
requireskeys are checked against the current context, thenrunexecutes. It either returns one of its own rejects, ending the request, or callsnext(ctx)and returns whatnext()resolves to, unchanged. Returning anything else afternext()fails as invalid handler output. Declaredprovidesvalues are parsed before any are merged, and undeclared top-level keys are omitted. - Handler.
runreceives the parsed input and the accumulated context, with framework-owned values such asloggerapplied last so they cannot be replaced. - Response validation. As soon as the handler or a middleware returns an outcome, before
earlier middleware resume, the result shape and
typeare checked against the outcomes of whoever returned it: the route’sresponsesfor the handler, or that middleware’s ownrejects. Itsdatais parsed according to the configured response-validation policy. Declared headers and cookie effects are checked the same way. A missing required cookie effect fails in every mode. - Serialization. The response is written at the same point as
application/json; charset=utf-8, with the outcome’s declared headers, its cookies as repeatedSet-Cookiefields, and, when enabled, lifecycle headers. A bodyless outcome gets no content headers. The selected response is then fixed: changes that code makes later to the objects the result was built from do not reach the client.
Status Codes Routa Produces
Section titled “Status Codes Routa Produces”| Status | Cause |
|---|---|
204 |
Automatic OPTIONS response |
400 |
Input failed schema validation, or the JSON body could not be parsed |
400 |
Strict mode received credentials of several accepted schemes (ambiguousCredentials) |
401 |
A presented credential failed authentication (authenticationFailed) |
401 |
A requireAuth guard received an anonymous request (authenticationRequired) |
404 |
No route matches the request path |
405 |
The path exists but does not declare the requested method |
406 |
The Accept header cannot be satisfied by JSON |
415 |
The request body’s content type is not a JSON media type |
500 |
A handler or middleware returned output that does not match its contract |
500 |
A route-file or method service factory failed during the request |
500 |
A handler or middleware threw an error it did not handle |
500 |
An authenticator threw, or returned a result or principal that breaks its contract |
Every other status comes from your contract: a handler outcome or a middleware reject.
Error Response Shape
Section titled “Error Response Shape”For most errors Routa generates, it returns problem documents. Responses with status 404, 405, or 406 are the plain-text exceptions, and their body is the text in the Title column of the table below:
{ "type": "https://routa-ts.dev/problems/validation", "title": "Validation failed", "status": 400, "issues": [{ "path": ["body", "email"], "message": "Invalid email address" }]}type |
Title | Status |
|---|---|---|
…/problems/validation |
Validation failed | 400 |
…/problems/invalid-json |
Invalid JSON body | 400 |
…/problems/ambiguous-credentials |
Ambiguous credentials | 400 |
…/problems/authentication-failed |
Authentication failed | 401 |
…/problems/authentication-required |
Authentication required | 401 |
| Plain text (no problem type) | 404 Not Found | 404 |
| Plain text (no problem type) | Method Not Allowed | 405 |
| Plain text (no problem type) | Not Acceptable | 406 |
…/problems/unsupported-media-type |
Unsupported Media Type | 415 |
…/problems/handler-output |
Invalid handler output | 500 |
…/problems/internal |
Internal Server Error | 500 |
Only input validation problems include issues in the response. Handler-output problems
never leak the underlying message or response values, since they may contain internal
data.
Authentication
Section titled “Authentication”When src/routa.ts configures authentication,
Routa resolves every matched request’s credentials before anything else reads the request.
Each scheme reads its own transport:
| Scheme | Presented when | Malformed, so its authenticator does not run |
|---|---|---|
bearer |
Authorization names the Bearer scheme |
The token is empty or not an RFC 6750 b64token |
apiKey |
The configured header is present | The value is empty, or holds a comma, as a repeated header does |
sessionCookie |
The Cookie header carries the configured name |
The value is empty, or the cookie appears more than once |
custom |
Its header is present, its Authorization auth-scheme matches ignoring case, or its cookie is present |
The value is empty, a header value holds a comma, or the cookie appears more than once; or extract returns { type: "malformed" } |
Headers joins a repeated header into one value separated by , , so Routa cannot tell a
repeated API-key header from a key that holds a comma. Both fail. A session cookie value is
percent-decoded the same way as declared cookies input. An Authorization header that no
configured scheme reads, such as Basic … without a custom scheme for Basic, Bearer …
without a Bearer scheme, or Bearer followed by a tab instead of spaces, is an unsupported
credential. A custom transport { header: "authorization" } without a scheme reads every
Authorization header, so none is unsupported.
A custom scheme’s extract runs only for a selected, well-formed credential, receives the
value alone, and returns before the authenticator runs. The authenticator runs at most once
per request. Routa parses an accepted principal once with
the principal schema, and ctx.auth.principal is the schema’s output. ctx.auth is readonly:
middleware cannot replace it, and writing it fails the request with the generic 500.
A requireAuth guard runs at its position in the
middleware chain, after input parsing. A guard a folder middleware.ts exports runs with the
folder’s middleware, before route and method middleware. It returns authenticationRequired
for an anonymous request and passes an authenticated one on. The handler sees the authenticated branch of
ctx.auth. Startup refuses a folder middleware.ts that exports a requireAuth guard the
generated metadata does not list, because Routa would never run it; see
Authentication Requirements.
Credential Selection
Section titled “Credential Selection”Each operation accepts a set of schemes, which Routa computes once at startup: the schemes
every requireAuth guard in its middleware chain allows, from the root folder to the method,
or every configured scheme when no guard applies. Only credentials of accepted schemes are eligible. For each request:
| Presented credentials | Result |
|---|---|
| None | ctx.auth is { status: "anonymous" } |
| Only unsupported, or only of schemes not accepted | authenticationFailed; no authenticator runs |
| Exactly one eligible, in either mode | It is selected |
Two or more eligible, multipleCredentials: "priority" |
The first eligible by priority is selected |
Two or more eligible, multipleCredentials: "reject" |
ambiguousCredentials (400); no authenticator runs |
Routa then checks the selected credential. A malformed one fails without calling the
authenticator. Otherwise the scheme’s authenticator alone runs: an accepted principal makes
ctx.auth { status: "authenticated", scheme, principal }, and a rejection returns
authenticationFailed. Routa never falls back to another credential, and a presented
credential that fails never downgrades to anonymous, on public operations and protected ones
alike. Because resolution runs first, a request it fails receives authenticationFailed or
ambiguousCredentials whatever its Accept header or body.
A credential of a scheme the operation does not accept never authenticates it. A route behind
requireAuth({ schemes: ["session"] }), inline or inherited from a folder, that receives only
a valid Bearer token returns authenticationFailed, challenging Session, and the Bearer
authenticator never runs. When the same request also carries a session
cookie, Routa ignores the Bearer token and authenticates the session.
Outcomes and Challenges
Section titled “Outcomes and Challenges”Both 401 outcomes are problem documents with a WWW-Authenticate challenge:
{ "type": "https://routa-ts.dev/problems/authentication-failed", "title": "Authentication failed", "status": 401}Each scheme’s challenge names its auth-scheme, Bearer, ApiKey, Session, or for a
custom scheme its name or the override’s scheme, with realm="…" when the scheme declares a
static challenge override:
| Situation | Outcome | WWW-Authenticate |
|---|---|---|
No credential behind requireAuth |
authenticationRequired |
Every accepted scheme, in priority order |
| Only unsupported or not-accepted credentials | authenticationFailed |
Every accepted scheme, in priority order |
| Malformed or rejected Bearer token | authenticationFailed |
Bearer error="invalid_token", with the realm first |
| Malformed or rejected API key or session | authenticationFailed |
That scheme alone: ApiKey or Session, with its realm |
| Malformed or rejected custom credential | authenticationFailed |
That scheme alone, such as Basic realm="api" |
Several challenges share one header, such as Bearer realm="api", Session. Routa adds
error="invalid_token" to Bearer challenges only, and never adds error_description,
error_uri, or any value from the request, the application, or its provider.
In strict mode, ambiguousCredentials is a 400 problem document without a challenge, since
the client already holds credentials and must send one:
{ "type": "https://routa-ts.dev/problems/ambiguous-credentials", "title": "Ambiguous credentials", "status": 400}It applies only to operations that accept two or more schemes. On an explicit HEAD
operation every authentication outcome keeps its status and challenge without a body.
Authenticator Failures
Section titled “Authenticator Failures”| Authenticator behavior | Response |
|---|---|
Returns { type: "rejected" } |
401 authenticationFailed |
| Throws | 500 …/problems/internal |
Returns a principal the principal schema rejects, or parses to a value without string id and type |
500 …/problems/internal |
Returns anything other than authenticated or rejected, or a result whose type throws when read |
500 …/problems/internal |
A custom extract returns { type: "malformed" } |
401 authenticationFailed; no authenticator runs |
A custom extract throws, or returns neither credential nor malformed, such as a promise |
500 …/problems/internal; no authenticator runs |
An invalid result is an application contract violation, not a client error. When an authenticator or extractor throws, the log names only the scheme, never the thrown value, which may carry the credential. A thrown error stays a server error so an outage at a provider never reads as a bad credential.
Methods
Section titled “Methods”Applications declare get, post, put, patch, delete, and optionally head.
OPTIONSis automatic. Every known path answersOPTIONSwith204and anAllowheader derived from that path’s methods, including the implicitHEADforGETandOPTIONSitself. Declaringoptionsis a registration error.HEADis implicit forGET. Declareheadexplicitly only when it needs its own contract; explicitHEADcontracts are registered ahead ofGETso they win without intercepting realGETrequests.GETandHEADcannot declare a body. Registration throws.- Unsupported methods return
405with the sameAllowheader.
CORS Preflight
Section titled “CORS Preflight”A preflight carrying both Origin and Access-Control-Request-Method receives the derived
method list as Access-Control-Allow-Methods, plus
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers. Routa never
sets Access-Control-Allow-Origin, so cross-origin access still requires an explicit CORS
policy in your application.
Input Parsing Details
Section titled “Input Parsing Details”| Source | Behavior |
|---|---|
params |
Values from dynamic path segments |
query |
The query string as a flat record; repeated keys collapse to the last value |
headers |
All request headers, lowercased |
cookies |
Parsed from the Cookie header and URI-decoded, falling back to the raw value on malformed encoding |
body |
Requires application/json or a +json media type, otherwise 415 |
Response Serialization
Section titled “Response Serialization”Handlers and middleware rejects return { type, data }, or just { type } for an outcome
without a schema. An outcome that declares headers or cookies also returns them. Routa
always looks up the type and status from the matching response definition. It requires data for an outcome with a schema and rejects data on one
without, so an outcome without a schema sends an empty body whatever its status. With the
default responseValidation: "development", Routa parses data through the response schema
in routa dev, compares the parsed value with the value the handler returned, and skips
both in routa start. Set responseValidation: "always" to do both in both modes. The CLI
passes the mode explicitly; Routa does not infer it from NODE_ENV.
Routa sends the value the handler returned, never the parsed value. Data that does not match the schema, or that the schema would change, produces a handler-output problem. Data that cannot be serialized as JSON also produces a handler-output problem rather than a partial response. See Configuration for the policy table.
An outcome’s declared headers are part of the same step. In every mode Routa checks that
the result writes only declared names, writes each once whatever its case, includes every
required header, and uses safe values: strings without line breaks or surrounding
whitespace, finite numbers, and booleans. It serializes values to strings in declaration
order. A violation, or a header that a lifecycle header also claims, is a handler-output
problem, and Routa never overwrites a header. Parsing header values and comparing the result
follow responseValidation exactly like data.
Return the declared result object from handlers and middleware. A raw Response is not a
response escape hatch: returning one is invalid handler output, while throwing one is
handled as an internal error. Both produce a generic 500 problem response.
Logging
Section titled “Logging”When a logger is configured, createHonoApp records http.request at info for every
completed request with method, path, status, and durationMs, and http.error at
error for responses of 500 or above with the error message, name, and stack. Response
and middleware context schema failures also include structured issues containing only
each Zod issue’s code and path; rejected values are never logged.
For an authenticator that throws, http.error carries the message
Authenticator for scheme "<name>" threw. and the scheme, never anything the thrown value
carries, such as its message, stack, or name, because a provider error may include the
credential. An
invalid principal logs the scheme in the message and the principal schema’s issues. Request
events record no headers or cookies, so Bearer tokens, API keys, and session values never reach
the logs.
Handlers always receive ctx.logger. With logging disabled it is a complete no-op
implementation of the same type.