Skip to content

Core Reference

@routa-ts/core holds the helpers you write against and the runtime primitives generated code uses. It exposes four entry points, and hono and zod are peer dependencies rather than bundled.

Terminal window
npm install @routa-ts/core hono zod
Entry point Contents
@routa-ts/core createRouta, defineServices, createRoute, createRouteRoot, createRouteRootFactory, createMiddleware, bearer, apiKey, sessionCookie, requireAuth, and the contract types
@routa-ts/core/hono createHonoApp, createApplication, isBodylessStatus
@routa-ts/core/logger createLogger and the logger types
@routa-ts/core/query/helpers Sort, Fields
function createRouta<const TConfig extends RoutaConfig>(
config: TConfig & AuthenticationChecks<NoInfer<TConfig>>,
): TConfig & RoutaConfig

Preserves an application configuration object with Routa’s typing. Export the result as the default export of src/routa.ts, which the runtime imports at boot.

Option Type Default
host string "127.0.0.1"
port number 3000
logger RoutaLogger | false Built-in console logger
lifecycleHeaders boolean false
responseValidation "development" | "always" "development"
services ApplicationServicesFactory None
authentication AuthenticationConfig None

AuthenticationChecks fails a scheme whose authenticator returns a principal the principal schema does not accept as input, a rejection with fields besides type, or a priority entry that names no configured scheme.

src/routa.ts
import { createRouta } from "@routa-ts/core";
export default createRouta({
host: "127.0.0.1",
port: 3000,
lifecycleHeaders: true,
responseValidation: "always",
});

See Configuration for environment precedence.

function defineServices<TServices>(): ServicesHelper<TServices>
type ServicesHelper<TServices> = <TContext = ApplicationServicesContext>(
factory: (context: TContext) => TServices | Promise<TServices>,
) => (context: TContext) => TServices | Promise<TServices>

Fixes a service contract and returns a helper that checks a factory against it and returns the factory unchanged. TServices must name each service as a required property; optional services and index signatures are type errors. Where you place the helper’s result types the factory’s argument: createRouta({ services }) passes an ApplicationServicesContext, and a route root’s or createRoute’s services passes a RequestServicesContext.

Factory argument Type Purpose
logger RoutaLogger Application factories: the configured logger, or a no-op logger
ctx object Request factories: earlier middleware context, earlier services, logger
onCleanup OnCleanup Registers a callback that releases a resource the factory owns

The factory may be sync or async and returns exactly the contract’s services.

src/services.ts
import { defineServices } from "@routa-ts/core";
export interface AppServices {
clock: { now(): Date };
}
export const defineAppServices = defineServices<AppServices>();
export const appServices = defineAppServices(() => ({ clock: { now: () => new Date() } }));

routa check reports ROUTA_SERVICES_UNRESOLVED, ROUTA_SERVICES_CONTRACT_UNRESOLVED, or ROUTA_SERVICES_CONTRACT_UNSUPPORTED for a declaration it cannot read. See Services.

function createRoute<TInput, TResponses, TMiddleware>(
contract: RouteContract<TInput, TResponses, TCtx, TMiddleware>,
): RouteContract<TInput, TResponses, TCtx, TMiddleware>

Declares one HTTP method. The function returns its argument unchanged; its purpose is to capture literal types so run receives typed input, ctx, and response and is constrained to the declared outcomes.

Field Type Required
input { params?, query?, headers?, cookies?, body? } of Zod schemas No
responses Record<string, { status; description?; schema?; headers?; cookies? }> Yes
middleware readonly MiddlewareContract[] No
services A defineServices helper result, run once per request to this method No
deprecation { sunset?: string; replacement?: string } No
run ({ input, ctx, response }) => { type, data, headers, cookies } or a promise of it Yes

deprecation.replacement accepts a registered route path beginning with / or an absolute http:/https: URL. Local paths are checked against the generated route registry.

An outcome with a schema returns data typed from the schema. An outcome without one is intentionally bodyless: it returns only type and sends an empty body. description is optional text for the OpenAPI response; without it, Routa uses the outcome name, so notFound becomes “Not found”.

An outcome’s headers is a Zod object keyed by lowercase header names, with string, number, or boolean values. The result’s headers field is required when any declared header is required, optional when all are, and forbidden when the outcome declares none. Routa owns content-type, content-length, transfer-encoding, connection, and set-cookie, and with lifecycleHeaders on it owns deprecation, sunset, and the successor link. See Schemas.

An outcome’s cookies lists the createCookie handles it may emit. A bare handle is optional; { handle, required: true } requires a set or clear effect for it. The result’s cookies field is an array of set and clear effects for those handles, and it is forbidden when the outcome declares none. See createCookie.

Errors: returning an undeclared type is a compile error and, at runtime, an Invalid handler output problem response. Result objects may contain only type, data, headers, and cookies. data is required for an outcome with a schema and forbidden for one without. TypeScript also rejects a schema on a 204, 205, or 304 outcome and on any HEAD outcome, an informational 1xx status, a 304 outside GET and HEAD, and response schemas that change values. A hand-built contract that breaks the status and method rules fails when the app registers it. A response schema that changes values is caught by routa check, or at request time when response validation is on and the schema changes the returned value.

import { createRoute } from "@routa-ts/core";
import { z } from "zod";
export const getStatus = createRoute({
responses: {
success: { status: 200, schema: z.object({ ok: z.boolean() }) },
},
run: ({ response }) => response.success({ ok: true }),
});
type ResponseBuilders<TResponses extends RouteResponses> = {
readonly [K in Exclude<keyof TResponses & string, OutcomesWithRequiredCookies<TResponses>>]:
TResponses[K] extends { readonly schema: infer TSchema extends ZodType }
? (
data: SchemaOutput<TSchema>,
...headers: BuilderHeaderArgs<TResponses[K]>
) => Extract<OutcomeResult<K, TResponses[K]>, { readonly data: unknown }>
: (...headers: BuilderHeaderArgs<TResponses[K]>) => OutcomeResult<K, TResponses[K]>
}
// Internal helpers, not exported
type BuilderHeaderArgs<TOutcome> = TOutcome extends { readonly headers: infer THeaders extends ZodType }
? {} extends SchemaOutput<THeaders>
? [headers?: SchemaOutput<THeaders>] // every declared header is optional
: [headers: SchemaOutput<THeaders>]
: [] // no headers declared
type OutcomesWithRequiredCookies<TResponses extends RouteResponses> = {
[K in keyof TResponses & string]: TResponses[K] extends {
readonly cookies: readonly (infer TEntry)[]
}
? Extract<TEntry, { readonly required: true }> extends never
? never
: K
: never
}[keyof TResponses & string]

An outcome that lists a required cookie has no builder. Return its result object instead, so you can set the cookie effect.

import { createRoute } from "@routa-ts/core";
import { z } from "zod";
export const getItem = createRoute({
responses: {
ok: {
status: 200,
schema: z.object({ id: z.string() }),
headers: z.object({ etag: z.string(), "x-cached": z.boolean().optional() }),
},
notModified: { status: 304, headers: z.object({ etag: z.string() }) },
},
run: ({ response }) => {
const etag = '"v1"';
// A body outcome takes its data, then its headers.
return response.ok({ id: "1" }, { etag });
// A bodyless outcome takes only its headers: response.notModified({ etag })
},
});

A body outcome’s builder takes the data, then a headers argument when the outcome declares headers. A bodyless outcome’s builder takes only headers. The argument is required when any declared header is required, optional when all are, and absent when the outcome declares none.

Handlers receive response: ResponseBuilders<TResponses>. Each method uses the name and schema of one outcome in the route’s own responses declaration. There are no built-in outcome names, and middleware rejects do not add builder methods.

Parameter Type Purpose
data Selected outcome schema’s output type Body data for the result
headers Selected outcome headers output type Response headers, when the outcome declares any

An outcome without a schema has a builder with no data parameter, such as response.noContent(). An outcome that declares a required cookie has no builder; return its result object so you can set the cookie effect. A builder returns { type, data, headers }, or { type, headers } for an outcome without a schema (headers appears only when you pass it), without sending a response. Return that result from run to select the outcome. Routa applies the declared status, configured response validation, and JSON serialization. Existing object returns remain supported.

import { createRoute } from "@routa-ts/core";
import { z } from "zod";
export const getGreeting = createRoute({
responses: {
ok: { status: 200, schema: z.object({ message: z.string() }) },
},
run: ({ response }) => response.ok({ message: "Hello!" }),
});

Errors: TypeScript rejects undeclared methods and data that does not match the selected schema. Runtime payload validation follows the responseValidation setting. The response object is frozen; its methods cannot be replaced.

RouteHandlerArgs<TInput, TCtx, TResponses = RouteResponses> accepts the response contract as its third type parameter when you explicitly annotate handler arguments.

function createRouteRoot<const TPath extends RegisteredRoutePath>(
path: TPath,
): <const TConfig extends RouteRootConfigForCtx<Register["routeCtxByPath"][TPath]>>(
config: TConfig,
) => TConfig

Binds a file to a URL path and returns the helper used as the file’s default export. The returned helper accepts get, post, put, patch, delete, head, middleware, and services, and rejects every other key. options is never accepted. services takes a defineServices helper result that runs once per request to any of the file’s methods; see route-file and method services.

src/routes/users/$userId/route.ts
import { createRoute, createRouteRoot } from "@routa-ts/core";
import { z } from "zod";
import { withAudit } from "../../../middleware/audit.js";
const route = createRouteRoot("/users/:userId");
export default route({
middleware: [withAudit],
get: createRoute({
responses: {
success: {
status: 200,
schema: z.object({ id: z.string() }),
},
},
run: () => ({ type: "success", data: { id: "usr_1" } }),
}),
});

The path must use :name for dynamic segments even though the filesystem uses $name. Context types come from the Register augmentation in .routa/routes.gen.ts, so a path missing from generated metadata produces a type error.

function createRouteRootFactory<
TCtxByPath extends Record<string, Partial<Record<HttpMethod, unknown>>>,
>(): <TPath extends keyof TCtxByPath & string>(
path: TPath,
) => <const TConfig extends RouteRootConfigForCtx<TCtxByPath[TPath]>>(
config: TConfig,
) => TConfig

Returns a createRouteRoot bound to an explicit context map instead of the generated Register augmentation. Use it in tests, libraries, or tooling that must work without a generated project. Prefer createRouteRoot in application code.

import { createRoute, createRouteRootFactory } from "@routa-ts/core";
import { z } from "zod";
type TestContextByPath = {
"/health": { get: Record<never, never> };
};
const createTestRouteRoot = createRouteRootFactory<TestContextByPath>();
const route = createTestRouteRoot("/health");
export default route({
get: createRoute({
responses: {
success: { status: 200, schema: z.object({ ok: z.boolean() }) },
},
run: () => ({ type: "success", data: { ok: true } }),
}),
});
function createMiddleware<TRequires, TProvides, TRejects, TInput>(
contract: MiddlewareContract<TRequires, TProvides, TRejects, TInput>,
): MiddlewareContract<TRequires, TProvides, TRejects, TInput>
function createMiddleware<Requirements>(): MiddlewareHelper<Requirements>
type MiddlewareHelper<TServices extends object> = <
const TRequires extends readonly RegisteredCtxKey[] = readonly RegisteredCtxKey[],
const TProvides extends MiddlewareProvidesSpec = Record<never, never>,
const TRejects extends MiddlewareRejectsSpec = Record<never, never>,
const TInput extends RouteInput | undefined = undefined,
const TNames extends readonly (keyof TServices & string)[] = readonly (keyof TServices & string)[],
>(
contract: MiddlewareContract<TRequires, TProvides, TRejects, TInput, TServices> & {
readonly requiresServices: TNames & RequirementListChecks<TServices, NoInfer<TNames>>
readonly rejects?: ResponseChecks<NoInfer<TRejects>>
readonly provides?: ReservedContextChecks<NoInfer<TProvides>>
},
) => MiddlewareContract<TRequires, TProvides, TRejects, TInput, TServices>

RequirementListChecks fails a requiresServices list that is not a literal list, leaves out a name the requirement interface declares, or repeats one. ResponseChecks and ReservedContextChecks apply the same rules as the contract form.

Field Type Purpose
requires readonly string[] Context keys that must already exist
requiresServices readonly (keyof Requirements)[] Helper form only: every requirement name, once
provides Record<string, ZodType> Context keys this middleware adds
rejects Record<string, { status; description?; schema?; headers?; cookies? }> Early responses it can return
input Same shape as a route input Request data the middleware needs
openapi { security?, permissions? } Metadata emitted into generated OpenAPI
run ({ input, ctx, next }) => … The implementation

run either returns one of its own reject outcomes or returns next(providedCtx). next() resolves to an opaque MiddlewareContinuation, the outcome the rest of the chain selected; return it unchanged. Routa parses every declared provides value before merging any of them into ctx, and downstream code receives the parsed output. Undeclared top-level keys are omitted. A normal z.object() schema strips unknown nested keys; use .strict() on that schema when unknown nested keys must reject the request instead.

Errors: next() called more than once throws. A provides value that fails its schema, or a value other than next()’s result returned after calling it, produces an Invalid handler output response. Reject statuses must be 4xx or 5xx.

Called with only a type argument, createMiddleware<Requirements>() returns a MiddlewareHelper. The helper takes the same contract plus requiresServices, which must list each of the interface’s names exactly once, and types the callback’s ctx.services as Readonly<Requirements>. Requirements follows the service contract rules: required, plainly named members and no index signature. The direct form has no typed ctx.services and rejects requiresServices. A middleware whose required service is missing from its stage’s ctx.services at request time fails with the standard 500 problem before its callback runs; see Middleware Service Requirements.

import { randomUUID } from "node:crypto";
import { createMiddleware } from "@routa-ts/core";
import { z } from "zod";
export const withRequestId = createMiddleware({
provides: { requestId: z.string().uuid() },
run: ({ next }) => next({ requestId: randomUUID() }),
});
import { createMiddleware } from "@routa-ts/core";
export interface ClockRequirements {
clock: { now(): Date };
}
const defineClockMiddleware = createMiddleware<ClockRequirements>();
export const withClock = defineClockMiddleware({
requiresServices: ["clock"],
run: ({ ctx, next }) => {
ctx.services.clock.now();
return next();
},
});
function bearer<const TResult extends AuthenticationResult>(options: {
challenge?: { realm?: string };
authenticate: (
credential: string,
context: AuthenticatorContext,
) => TResult | Promise<TResult>;
}): BearerScheme<TResult>
type AuthenticationResult<TPrincipal = unknown> =
| { readonly type: "authenticated"; readonly principal: TPrincipal }
| { readonly type: "rejected" }

Declares a credential scheme that reads Authorization: Bearer <token>. Place it in authentication.schemes in createRouta, keyed by the scheme name. Routa extracts the token, calls authenticate once per request that presents one, and parses an authenticated principal with the principal schema.

Option Type Purpose
challenge { realm?: string } Static challenge override; a literal read by routa check
authenticate (credential, context) => AuthenticationResult Your verification code: return a principal candidate or a rejection

context holds logger and, when src/routa.ts declares them, the application services. It has no route-file or method services and no request. Return { type: "rejected" } for a credential that is not valid. Throw only for unexpected failures, which stay 500 responses. realm must be printable ASCII without " or \.

src/routa.ts
import { bearer, createRouta } from "@routa-ts/core";
import { z } from "zod";
export default createRouta({
authentication: {
principal: z.object({ type: z.literal("service"), id: z.string() }),
schemes: {
serviceToken: bearer({
challenge: { realm: "internal" },
authenticate: (token) =>
token === process.env.SERVICE_TOKEN
? { type: "authenticated", principal: { type: "service", id: "billing" } }
: { type: "rejected" },
}),
},
},
});

Errors: throws a TypeError when authenticate is not a function, or when challenge declares a key other than realm or an invalid realm.

function apiKey<const TResult extends AuthenticationResult>(options: {
header: string;
challenge?: { realm?: string };
authenticate: (
credential: string,
context: AuthenticatorContext,
) => TResult | Promise<TResult>;
}): ApiKeyScheme<TResult>

Declares a credential scheme that reads an API key from one request header. Routa passes the header’s value to authenticate once per request that selects it, and parses an authenticated principal with the principal schema. authenticate, context, and the result follow the same contract as bearer.

Option Type Purpose
header string The header that carries the key, such as "x-api-key"; a literal
challenge { realm?: string } Static challenge override; a literal read by routa check
authenticate (credential, context) => AuthenticationResult Your verification code: return a principal candidate or a rejection

The header name is an RFC 9110 token, compared ignoring case. It cannot be Authorization or Cookie, which Bearer and session schemes read. A missing credential challenges ApiKey, or ApiKey realm="…" with the override; a failed one challenges the same, with no error details. OpenAPI declares the scheme as { type: "apiKey", in: "header", name }.

src/routa.ts
import { apiKey, createRouta } from "@routa-ts/core";
import { z } from "zod";
import { findServiceKey } from "./service-keys.js";
export default createRouta({
authentication: {
principal: z.object({ type: z.literal("service"), id: z.string() }),
schemes: {
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" };
},
}),
},
},
});

Errors: throws a TypeError when header is not a header name, authenticate is not a function, or challenge declares a key other than realm or an invalid realm.

function sessionCookie<const TResult extends AuthenticationResult>(options: {
cookie: string;
challenge?: { realm?: string };
authenticate: (
credential: string,
context: AuthenticatorContext,
) => TResult | Promise<TResult>;
}): SessionCookieScheme<TResult>

Declares a credential scheme that reads a session from one request cookie. Routa passes the cookie’s percent-decoded value to authenticate once per request that selects it, and parses an authenticated principal with the principal schema. Your application owns sessions: how it creates, stores, signs, and expires them. authenticate, context, and the result follow the same contract as bearer.

Option Type Purpose
cookie string The cookie that carries the session, such as "session"; a literal
challenge { realm?: string } Static challenge override; a literal read by routa check
authenticate (credential, context) => AuthenticationResult Your verification code: return a principal candidate or a rejection

The cookie name is an RFC 6265 token, compared exactly. A missing credential challenges Session, or Session realm="…" with the override; a failed one challenges the same, with no error details. OpenAPI declares the scheme as { type: "apiKey", in: "cookie", name }.

src/routa.ts
import { createRouta, sessionCookie } from "@routa-ts/core";
import { z } from "zod";
import { findSession } from "./sessions.js";
export default createRouta({
authentication: {
principal: z.object({ type: z.literal("user"), id: z.string() }),
schemes: {
session: sessionCookie({
cookie: "session",
authenticate: async (value) => {
const session = await findSession(value);
return session
? { type: "authenticated", principal: { type: "user", id: session.userId } }
: { type: "rejected" };
},
}),
},
},
});

Errors: throws a TypeError when cookie is not a cookie name, authenticate is not a function, or challenge declares a key other than realm or an invalid realm.

function custom<
const TResult extends AuthenticationResult,
TExtraction extends CustomExtraction = { type: "credential"; credential: string },
>(options: {
transport: { header: string; scheme?: string } | { cookie: string };
challenge?: { scheme?: string; realm?: string };
openapi:
| { type: "http"; scheme: string; bearerFormat?: string; description?: string }
| { type: "apiKey"; in: "header" | "cookie"; name: string; description?: string }
| { type: "mutualTLS"; description?: string };
extract?: (value: string) => TExtraction;
authenticate: (
credential: ExtractedCredential<TExtraction>,
context: AuthenticatorContext,
) => TResult | Promise<TResult>;
}): CustomScheme<TResult, ExtractedCredential<TExtraction>>
type CustomExtraction<TCredential = unknown> =
| { type: "credential"; credential: TCredential }
| { type: "malformed" };
// The credential type of each { type: "credential" } member; { type: "malformed" } adds nothing.
type ExtractedCredential<TExtraction> = TExtraction extends {
type: "credential";
credential: infer TCredential;
}
? TCredential
: never;

ExtractedCredential is the type authenticate receives. For an extract that returns { type: "credential"; credential: { user: string; password: string } } | { type: "malformed" }, it is { user: string; password: string }. Without extract, it is string.

Declares a credential scheme for a credential the built-in schemes do not read, such as HTTP Basic. Routa reads the one value the transport declares, passes it alone to extract, and calls authenticate once with the credential extract returns. Selection, priority, requireAuth, principal parsing, ctx.auth, and OpenAPI treat the scheme like a built-in one. authenticate, context, and the result follow the same contract as bearer. Custom Credential Schemes has complete recipes.

Option Type Purpose
transport { header }, { header: "authorization", scheme }, or { cookie } The one value the scheme reads; a literal read by routa check
challenge { scheme?: string; realm?: string } Static challenge override; a literal read by routa check
openapi A Security Scheme Object Public OpenAPI metadata that agrees with the transport; a literal
extract (value: string) => CustomExtraction Optional, synchronous: turns the value into a credential or malformed
authenticate (credential, context) => AuthenticationResult Your verification code: return a principal candidate or a rejection

The transport is the scheme’s identity, so no other scheme may read it:

Transport Reads
{ header: "x-client-cert" } The whole header value. Header names compare ignoring case
{ header: "authorization", scheme: "Basic" } The credentials after Basic, when the auth-scheme matches ignoring case
{ header: "authorization" } The whole Authorization header, whatever its auth-scheme
{ cookie: "sid" } The percent-decoded cookie value, as sessionCookie reads it

Header names, auth-schemes, and cookie names are RFC 9110 tokens, and scheme applies only to Authorization. An empty value, a header value with a comma, and a repeated cookie are malformed, and extract does not run. Without extract, authenticate receives the value as a string; with it, authenticate receives the credential it returns, typed. extract receives no request, headers, or context. { type: "malformed" } answers authenticationFailed; a throw, or any other result such as a promise, answers 500.

A missing credential challenges the scheme name, such as basicUser, or the override’s scheme with its realm; a failed one challenges the same, with no error details.

openapi must describe the transport. { type: "http", scheme } needs an Authorization transport with the same auth-scheme, ignoring case, and allows bearerFormat only for bearer. { type: "apiKey", in, name } names the header or cookie the scheme reads whole. { type: "mutualTLS" } needs a header other than Authorization: it documents a client certificate a trusted proxy verifies during the TLS handshake and forwards in that header. description is optional everywhere. Routa emits the object as written under components.securitySchemes.

src/routa.ts
import { createRouta, custom } from "@routa-ts/core";
import { z } from "zod";
import { decodeBasic } from "./basic.js";
import { verifyPassword } from "./passwords.js";
export default createRouta({
authentication: {
principal: z.object({ type: z.literal("user"), id: z.string() }),
schemes: {
basicUser: custom({
transport: { header: "authorization", scheme: "Basic" },
challenge: { scheme: "Basic", realm: "api" },
openapi: { type: "http", scheme: "basic" },
extract: (value) => decodeBasic(value),
authenticate: async ({ user, password }) => {
const account = await verifyPassword(user, password);
return account
? { type: "authenticated", principal: { type: "user", id: account.id } }
: { type: "rejected" };
},
}),
},
},
});

Errors: throws a TypeError when the transport, challenge override, or openapi metadata is invalid or disagrees with the transport, extract is present but not a function, or authenticate is not a function.

function requireAuth(options?: { schemes: readonly SchemeName[] }): RequireAuthMiddleware

A middleware guard that returns authenticationRequired (401) for an anonymous request and lets an authenticated one continue. The handler sees ctx.auth narrowed to { status: "authenticated", scheme, principal }. Middleware placed after the guard receives an authenticated value at runtime, but a middleware contract that declares requires: ["auth"] is typed with the anonymous-or-authenticated union, so check ctx.auth.status before reading principal. Omit options to accept any configured scheme, or list the accepted schemes inline; SchemeName is the union of names routa generate read from src/routa.ts.

Write the call inline in a route root’s or a createRoute’s middleware, or export it from a folder middleware.ts, so routa check can read it. It requires authentication in createRouta.

src/routes/projects/route.ts
import { createRoute, createRouteRoot, requireAuth } from "@routa-ts/core";
import { z } from "zod";
export default createRouteRoot("/projects")({
post: createRoute({
middleware: [requireAuth()],
input: { body: z.object({ name: z.string() }) },
responses: { created: { status: 201, schema: z.object({ owner: z.string() }) } },
run: ({ ctx }) => ({ type: "created", data: { owner: ctx.auth.principal.id } }),
}),
});

A folder export protects every route in that folder and below. Like other folder middleware, it runs at its export position, before route and method middleware:

src/routes/(staff)/middleware.ts
import { requireAuth } from "@routa-ts/core";
export const signedIn = requireAuth({ schemes: ["session", "userToken"] });

The folder may also export a const bound to such a guard, call it on a namespace import as core.requireAuth(), or re-export a guard another module declares that way, such as export { signedIn } from "../../guards.js". A guard built any other way, such as through a factory call, a conditional, a destructuring, or a let binding, fails routa check, and startup refuses a guard export the generated metadata does not list, because Routa would not run it. See Authentication Requirements.

Every guard on an operation applies, from the root folder to the method, and the operation accepts only the schemes all of them allow. A descendant can narrow an inherited requirement but cannot remove or widen it: under the folder above, a method’s requireAuth({ schemes: ["session"] }) accepts sessions alone, and a route’s requireAuth({ schemes: ["session", "serviceKey"] }) still accepts sessions alone. The handler’s ctx.auth.scheme has the same narrowed type.

Listing schemes restricts which credentials can authenticate the operation, not only who passes the guard. Routa selects only among credentials of the schemes the operation accepts, so a valid Bearer token on that method fails with authenticationFailed without reaching its authenticator. See Credential selection.

The guard owns the authenticationRequired outcome, so a route outcome with that name is a type error. Its 401 carries a WWW-Authenticate challenge for every accepted scheme, in priority order; see Runtime behavior.

Errors: throws a TypeError for an empty schemes list. routa check reports ROUTA_AUTH_NOT_CONFIGURED, ROUTA_AUTH_SCHEME_UNKNOWN, ROUTA_AUTH_REQUIREMENT_EMPTY for an empty list or guards on one operation that allow no scheme in common, and ROUTA_AUTH_REQUIREMENT_UNRESOLVED for options or a folder export it cannot read. It warns with ROUTA_AUTH_REQUIREMENT_WIDENED when a guard lists a scheme an earlier guard excludes. Registration throws when authentication is not configured, a guard names an undeclared scheme, or the guards allow no scheme in common.

type AuthContext<TScheme extends string = string, TPrincipal = Principal> =
| AnonymousAuthContext
| AuthenticatedAuthContext<TScheme, TPrincipal>
type AnonymousAuthContext = { readonly status: "anonymous" }
type AuthenticatedAuthContext<TScheme extends string = string, TPrincipal = Principal> = {
readonly status: "authenticated"
readonly scheme: TScheme
readonly principal: TPrincipal
}

The type of ctx.auth. Routa provides it only when src/routa.ts configures authentication; otherwise ctx.auth exists only when application middleware provides it, with that middleware’s type. .routa/routes.gen.ts types it for each operation: an operation without requireAuth gets AuthContext, and an operation behind requireAuth, inline or inherited from a folder, gets AuthenticatedAuthContext with the schemes it accepts. TPrincipal is the principal schema’s output. Middleware reads ctx.auth by declaring requires: ["auth"] and sees AuthContext.

src/routes/me/route.ts
import { createRoute, createRouteRoot } from "@routa-ts/core";
import { z } from "zod";
export default createRouteRoot("/me")({
get: createRoute({
responses: { ok: { status: 200, schema: z.object({ id: z.string().nullable() }) } },
run: ({ ctx }) => ({
type: "ok",
data: { id: ctx.auth.status === "authenticated" ? ctx.auth.principal.id : null },
}),
}),
});
type Principal = { readonly id: string; readonly type: string }
type PrincipalSchema = z.ZodType<{ id: string; type: string }, any>
type PrincipalOf<TConfig> = TConfig extends {
readonly authentication: { readonly principal: infer TSchema extends z.ZodTypeAny }
}
? z.output<TSchema>
: never
type AuthenticatorContext = { readonly logger: RoutaLogger; readonly services: Readonly<AppServices> }
type Authenticator<TResult extends AuthenticationResult = AuthenticationResult, TCredential = string> =
(credential: TCredential, context: AuthenticatorContext) => TResult | Promise<TResult>
type CredentialChallenge = { readonly realm?: string }
type CustomChallenge = { readonly scheme?: string; readonly realm?: string }
type CustomTransport = { readonly header: string; readonly scheme?: string } | { readonly cookie: string }
type ExtractedCredential<TExtraction> = TExtraction extends {
readonly type: "credential"
readonly credential: infer TCredential
}
? TCredential
: never
type CredentialScheme = BearerScheme | ApiKeyScheme | SessionCookieScheme | CustomScheme
type RequireAuthOptions<TSchemes extends readonly string[]> = { readonly schemes: TSchemes }
type RequireAuthMiddleware = MiddlewareContract<
readonly [],
Record<never, never>,
{
readonly authenticationRequired: {
readonly status: 401
readonly description: "Authentication is required: the request presented no credential."
readonly schema: z.ZodObject<{
type: z.ZodLiteral<"https://routa-ts.dev/problems/authentication-required">
title: z.ZodLiteral<"Authentication required">
status: z.ZodLiteral<401>
}>
readonly headers: z.ZodObject<{ "www-authenticate": z.ZodString }>
}
},
undefined
>

The types behind authentication and the constructors above. You rarely write them: createRouta, the descriptors, and .routa/routes.gen.ts infer them. Annotate with them when an authenticator or extractor lives in its own module.

Type Describes
Principal What every principal carries: a stable id, and a type that may discriminate callers
PrincipalSchema The Zod schema authentication.principal accepts; its output must have string id and type
PrincipalOf<TConfig> The principal schema’s output for a createRouta configuration, such as PrincipalOf<typeof config>
AuthenticationResult<TPrincipal> What an authenticator returns; see bearer
Authenticator<TResult, TCredential> An authenticator function. TCredential is string, or the credential a custom extract returns
AuthenticatorContext The second argument: logger, and services when src/routa.ts declares application services
AuthenticationConfig The authentication field; see Configuration
CredentialChallenge, CustomChallenge Static challenge overrides for the built-in descriptors and for custom
CustomTransport, CustomOpenApi, CustomExtraction The transport, openapi, and extract result of custom
ExtractedCredential<TExtraction> The credential type an extraction result carries
BearerOptions, ApiKeyOptions, SessionCookieOptions, CustomOptions Each constructor’s options
BearerScheme, ApiKeyScheme, SessionCookieScheme, CustomScheme The frozen descriptor each constructor returns, with its kind and contract facts
CredentialScheme Any descriptor; the value type of authentication.schemes
RequireAuthOptions, RequireAuthMiddleware The requireAuth options and the middleware contract it returns
AuthContext, AnonymousAuthContext, AuthenticatedAuthContext The type of ctx.auth; see AuthContext

An authenticator in its own module, typed against the application’s principal. Export the principal schema from its own module and derive the type from it: src/routa.ts imports the authenticator, so typing it with PrincipalOf<typeof config> would make the configuration’s type depend on itself. Use PrincipalOf<typeof config> in modules src/routa.ts does not import, such as route files.

src/principal.ts
import { z } from "zod";
export const Principal = z.discriminatedUnion("type", [
z.object({ type: z.literal("account"), id: z.string() }),
z.object({ type: z.literal("service"), id: z.string() }),
]);
export type AppPrincipal = z.input<typeof Principal>;
src/authenticators.ts
import type { AuthenticationResult, Authenticator } from "@routa-ts/core";
import type { AppPrincipal } from "./principal.js";
export const authenticateKey: Authenticator<AuthenticationResult<AppPrincipal>> = (key, { logger }) => {
if (key !== process.env.SERVICE_KEY) {
logger.info("auth.key_rejected", "An API key was rejected.");
return { type: "rejected" };
}
return { type: "authenticated", principal: { type: "service", id: "billing" } };
};
src/routa.ts
import { apiKey, createRouta } from "@routa-ts/core";
import { authenticateKey } from "./authenticators.js";
import { Principal } from "./principal.js";
export default createRouta({
authentication: {
principal: Principal,
schemes: { serviceKey: apiKey({ header: "x-api-key", authenticate: authenticateKey }) },
},
});
function createCookie<const TConfig extends CookieConfig>(
config: TConfig, // also constrained by the cookie rules TypeScript can check
): CookieHandle<TConfig>
Field Type Required Purpose
name string Yes RFC 6265 token
schema Zod string, number, or boolean Yes Validates the value; must not change it
httpOnly boolean Yes Adds HttpOnly
secure boolean Yes Adds Secure
sameSite "strict" | "lax" | "none" Yes Sets SameSite; "none" requires secure: true
path string Yes Starts with /; printable ASCII, no trailing space
domain string No Host name, with or without a leading dot
maxAge number No Non-negative whole seconds
expires string No ISO 8601 date-time, such as "2030-01-01T00:00:00Z"
partitioned boolean No Adds Partitioned; requires secure: true
type CookieSameSite = "strict" | "lax" | "none"
type CookieHandle<TConfig extends CookieConfig> = Readonly<TConfig> & {
set(value: SchemaOutput<TConfig["schema"]>): CookieEffect<CookieHandle<TConfig>>
clear(): CookieEffect<CookieHandle<TConfig>>
}
type CookieEffect<THandle = AnyCookie> = {
readonly kind: "set" | "clear"
readonly cookie: THandle
readonly value?: unknown
}
type AnyCookie = Readonly<CookieConfig> & {
set(value: never): CookieEffect<any>
clear(): CookieEffect<any>
}
type RequiredCookie<THandle extends AnyCookie = AnyCookie> = {
readonly handle: THandle
readonly required: true
}

CookieConfig is the field table above. AnyCookie accepts any handle, and a RequiredCookie entry in an outcome’s cookies makes the outcome return an effect for that handle.

The handle exposes set(value) and clear(). Both are pure: they return a CookieEffect bound to the handle, and Routa turns the effects an outcome returns into repeated Set-Cookie fields. List the handle in an outcome’s cookies for the outcome to return its effects. routa check and OpenAPI read the name and attributes from source, so write them as literals.

Errors: TypeScript rejects missing required attributes, a value schema that is not scalar or that changes values, SameSite=None or Partitioned without secure: true, and the __Secure- and __Host- prefix rules. routa check (ROUTA_RESPONSE_COOKIE_*) and createCookie itself, which throws, also reject an invalid name, path, domain, maxAge, or expires. Returning an effect for a handle the outcome does not list, the same identity twice, or a value that cannot be encoded safely produces an Invalid handler output response. See Schemas for the rules, encoding, and clearing.

import { createCookie } from "@routa-ts/core";
import { z } from "zod";
export const theme = createCookie({
name: "theme",
schema: z.enum(["light", "dark"]),
httpOnly: false,
secure: true,
sameSite: "lax",
path: "/",
});
theme.set("dark"); // a set effect
theme.clear(); // a clear effect
function createHonoApp(routes: readonly HonoRoute[], options?: CreateHonoAppOptions): Hono

Builds the Hono application from route definitions. It provides no application services: routes that read them need createApplication with a services factory. Call it directly in tests of routes that use no application services.

Parameter Type Purpose
routes[].method HttpMethod Lowercase method name
routes[].path string Hono path with :name parameters
routes[].contract AnyRouteContract The createRoute result
routes[].createContext () => object Optional base context, must return a plain object
routes[].services RouteServices Optional routeFile and method request services
routes[].middlewareNames readonly string[] Names each middleware of the chain in messages
options.logger RoutaLogger Enables http.request and http.error logging
options.lifecycleHeaders boolean Emit Deprecation, Sunset, and Link
options.responseValidation "development" | "always" Response schema policy; defaults to "development"
options.runtimeMode "dev" | "start" Explicit mode; defaults to "dev" for direct use
options.authentication AuthenticationConfig Resolves ctx.auth and enforces requireAuth

Registration throws for an explicitly declared options method, a duplicate method-and-path pair, a GET or HEAD contract declaring a body, and duplicate reject keys within one chain. With authentication, it also throws for an invalid configuration, a route outcome named authenticationFailed, one named authenticationRequired behind a requireAuth guard, a route outcome named ambiguousCredentials where strict mode can return it, and middleware that provides auth. Without it, a requireAuth guard throws.

type RouteServices = {
readonly routeFile?: RequestServicesDeclaration
readonly method?: RequestServicesDeclaration
}
type RequestServicesDeclaration = {
readonly factory: RequestServicesFactory
readonly names: readonly string[]
readonly after: number
}

Each RouteServices entry pairs a request factory with its contract’s names and after, the number of middleware at the start of the route’s chain that run before the factory. Registration also throws when after falls outside the chain, when method services run before route-file services, when the application, route-file, and method services share a name, or when the contract declares services that routes[].services.method does not supply.

middlewareNames lists a name for each entry of contract.middleware, in order. The CLI runtime passes the export names routa generate read. A middleware without a name appears in messages as middleware[i].

import { createHonoApp } from "@routa-ts/core/hono";
import route from "./routes/users/route.js";
const app = createHonoApp([{ method: "post", path: "/users", contract: route.post }]);
function createApplication(
routes: readonly HonoRoute[],
options?: CreateApplicationOptions,
): Promise<RoutaApplication>

Creates one application instance. It runs the services factory once, checks the returned names, and registers the routes with the services exposed as ctx.services. routa dev and routa start call it for you.

Option Type Purpose
services.factory ApplicationServicesFactory The factory from createRouta
services.names readonly string[] The contract’s names, as generated in routaApplicationServices
Every other option CreateHonoAppOptions Same as createHonoApp

The instance has two members:

Member Type Behavior
fetch (request: Request) => Promise<Response> Handles one request. Rejects once disposal has started
dispose () => Promise<void> Stops accepting requests, waits for accepted ones, then runs cleanup once. Repeated calls share one outcome; rejects with an AggregateError when cleanup failed

dispose sets no deadline: a request or callback that never settles keeps it pending.

import { createApplication } from "@routa-ts/core/hono";
import route from "./routes/time/route.js";
const app = await createApplication([{ method: "get", path: "/time", contract: route.get }], {
services: { names: ["clock"], factory: () => ({ clock: { now: () => new Date(0) } }) },
});
const response = await app.fetch(new Request("http://localhost/time"));
await app.dispose();

It rejects with the factory’s error after running the factory’s registered cleanup, with a TypeError when the returned names differ from services.names, and with any createHonoApp registration error after releasing the services.

function createProjectApplication(
load: ProjectModuleLoader,
options: CreateProjectApplicationOptions,
): Promise<ProjectApplication>

Builds a project’s application instance from its generated metadata without listening. routa dev, routa start, and the generated createTestApp all build through it, so a test application runs the same routes, middleware chains, and services as the server.

Parameter Type Purpose
load (file: string) => Promise<unknown> Imports a module by its path from the project root, such as src/routa.ts or .routa/routes.gen.ts
options.runtimeMode "dev" | "start" Explicit mode, as in createHonoApp
options.replacements ServiceReplacements Factories that replace whole scopes before construction, in the createTestApp options shape

It loads .routa/routes.gen.ts, each route file, its filesystem middleware, and src/routa.ts, then calls createApplication with the configured logger, lifecycle headers, response validation, services, and authentication. It returns a ProjectApplication:

type ProjectApplication = {
application: RoutaApplication
config: RoutaConfig
logger: RoutaLogger | undefined
routes: readonly HonoRoute[]
}

config is the default export of src/routa.ts. logger is its configured logger, a default logger when it sets none, or undefined when it sets logger: false. routes are the routes passed to createApplication.

import { pathToFileURL } from "node:url";
import { createProjectApplication } from "@routa-ts/core/hono";
const { application } = await createProjectApplication(
(file) => import(pathToFileURL(file).href),
{ runtimeMode: "start" },
);

It rejects before any factory runs when a replacement names a path, method, or scope that declares no services, or holds a key it does not read. It rejects when a route file or src/routa.ts disagrees with the generated metadata, including authentication scheme names or a priority order that differ from routaAuthenticationSchemes and a multipleCredentials mode that differs from routaMultipleCredentials, and with the errors of createApplication.

function createTestApplication(
modules: ProjectModules,
options?: ServiceReplacements | ApplicationServicesFactory,
): Promise<TestApplication>

Exported from @routa-ts/core/testing. The generated createTestApp in .routa/testing.gen.ts calls it with the project’s module list, so you call createTestApp instead. See Testing.

Parameter Type Purpose
modules Readonly<Record<string, () => Promise<unknown>>> Imports each project module by its path from the project root
options ServiceReplacements | ApplicationServicesFactory Replacement factories by scope, or a lone application services factory

It builds the application through createProjectApplication in "dev" mode and returns a frozen test application:

Member Type Behavior
request (input: string | URL | Request, init?: RequestInit) => Promise<Response> Sends one request in memory. A path resolves against http://localhost. Settles after the request’s services are released; rejects once disposal has started
dispose () => Promise<void> Stops accepting requests, waits for accepted ones and their request cleanup, then releases application services once. Repeated and concurrent calls share one outcome; rejects with an AggregateError when cleanup failed
import { createTestApp } from "../.routa/testing.gen.js";
const app = await createTestApp();
const response = await app.request("/status");
await app.dispose();

It rejects for the reasons createProjectApplication does, when options is neither a factory nor { services, routes }, and when the generated list leaves out a module the metadata names.

ServiceReplacements is the scoped form of options, keyed by route path and lowercase method. Each services entry is a factory for that scope; the generated TestAppOptions types each one against the scope’s contract.

type ServiceReplacements = {
readonly services?: unknown
readonly routes?: Readonly<
Record<
string,
{
readonly services?: unknown
readonly methods?: Readonly<Record<string, { readonly services?: unknown }>>
}
>
>
}
import { createTestApp } from "../.routa/testing.gen.js";
const app = await createTestApp({
services: () => ({ clock: { now: () => new Date(0) } }),
routes: {
"/orders": { methods: { post: { services: () => ({ receipts: { send: () => {} } }) } } },
},
});

A routes or methods value that is not a plain object, a path no route file declares, a method the route file does not declare, or a scope without services rejects before any factory runs.

function isBodylessStatus(status: number): boolean

Returns true for 204, 205, and 304, the statuses HTTP forbids a body for. Routa rejects a schema on outcomes with those statuses. It describes the status only: an outcome without a schema is also bodyless at any other status.

import { isBodylessStatus } from "@routa-ts/core/hono";
export function responseFor(status: number, data: unknown): Response {
const body = isBodylessStatus(status) ? null : JSON.stringify(data);
return new Response(body, { status });
}
function createLogger(options?: CreateLoggerOptions): RoutaLogger
Option Type Default
enabled boolean true
level "trace" | "debug" | "info" | "warn" | "error" | "fatal" | "silent" "info"
sink (event: RoutaLogEvent) => void Console writer
now () => Date () => new Date()

enabled: false forces the level to "silent", which is how the no-op logger is built. now exists so tests can produce deterministic timestamps.

The returned RoutaLogger is structural and depends on no logging package:

Member Signature
trace, debug, info, warn, error, fatal (event: string, message: string, data?: object) => void
silent Same signature, always a no-op
log (event: RoutaLogEvent) => void
child (bindings: object) => RoutaLogger
bindings () => object
isLevelEnabled (level) => boolean

Every log event carries level, event, message, timestamp, and optional data. Child bindings are merged into data on each write.

src/routa.ts
import { createRouta } from "@routa-ts/core";
import { createLogger } from "@routa-ts/core/logger";
export default createRouta({
logger: createLogger({
level: "debug",
sink: (event) => process.stdout.write(`${JSON.stringify(event)}\n`),
}),
});

Because the contract is structural, any object with these members works — an adapter over Pino, Winston, or a hosted SDK needs no Routa-specific package.

function Sort<const TFields extends readonly [string, ...string[]]>(fields: TFields): ZodType

Builds a schema for a sort query parameter. Accepts a field name from fields, with an optional leading - for descending order, and produces { field: TFields[number]; direction: "asc" | "desc" }. Any other field is rejected.

import { Sort } from "@routa-ts/core/query/helpers";
import { z } from "zod";
const query = z.object({ sort: Sort(["name", "createdAt"]).optional() });
// ?sort=-createdAt -> { field: "createdAt", direction: "desc" }
function Fields<const TFields extends readonly [string, ...string[]]>(fields: TFields): ZodType

Builds a schema for a sparse-fieldset query parameter. Splits a comma-separated string, trims each entry, drops empties, and validates the result against fields.

import { Fields } from "@routa-ts/core/query/helpers";
import { z } from "zod";
const query = z.object({ fields: Fields(["id", "name", "email"]).optional() });
// ?fields=id, name -> ["id", "name"]
type RouteRootConfigForCtx<
TCtxByMethod extends Partial<Record<HttpMethod, unknown>>,
> = {
middleware?: readonly AnyMiddlewareContract[];
} & {
[K in HttpMethod]?: ContextualRouteContract<
K extends keyof TCtxByMethod ? TCtxByMethod[K] : unknown
>;
}

Describes the route-level middleware and HTTP method contracts accepted by a path-bound route helper. The context map can provide a distinct handler context for each method.

Field Type Purpose
middleware readonly AnyMiddlewareContract[] Middleware shared by every declared method
get, post, put, patch, delete, head ContextualRouteContract Contract typed with that method’s context
import type { RouteRootConfigForCtx } from "@routa-ts/core";
type UsersRouteConfig = RouteRootConfigForCtx<{
get: { requestId: string };
post: { requestId: string; auth: { userId: string } };
}>;
type OnCleanup = (callback: () => unknown) => void

Registers a callback that releases a resource a services factory acquired. Routa awaits the callbacks after the scope ends, one at a time, in reverse registration order, and attempts every one even when an earlier one fails. A callback may return a promise.

Parameter Type Purpose
callback () => unknown Releases one acquired resource

Returns nothing.

import type { OnCleanup } from "@routa-ts/core";
export function startHeartbeat(onCleanup: OnCleanup): void {
const timer = setInterval(() => {}, 30_000);
onCleanup(() => clearInterval(timer));
}

Errors: onCleanup throws a TypeError when callback is not a function, and throws when called after cleanup has started. A failing callback is logged as services.cleanup_failed. For application services, dispose() then rejects with an AggregateError. A request cleanup failure never changes the response.

type ApplicationServicesContext = {
readonly logger: RoutaLogger
readonly onCleanup: OnCleanup
}

What an application services factory receives.

Field Type Purpose
logger RoutaLogger The configured logger, or a no-op logger when logging is off
onCleanup OnCleanup Registers a callback that releases a resource the factory owns
import type { ApplicationServicesContext } from "@routa-ts/core";
export function createClock({ logger }: ApplicationServicesContext) {
logger.info("clock.ready", "Clock ready.");
return { now: () => new Date() };
}

Errors: none. It is a type.

type ApplicationServicesFactory<TServices extends object = object> = (
context: ApplicationServicesContext,
) => TServices | Promise<TServices>

Builds one application instance’s services. It runs once, before the application accepts requests. defineServices checks an application factory against this type.

Type parameter Meaning
TServices The application’s service contract

Returns the services, or a promise of them, with exactly the names TServices declares.

import type { ApplicationServicesFactory } from "@routa-ts/core";
export type AppServices = { clock: { now(): Date } };
export const appServices: ApplicationServicesFactory<AppServices> = () => ({
clock: { now: () => new Date() },
});

Errors: when the factory throws or returns different names, Routa runs the callbacks it registered, then fails startup with that error.

type RequestServicesContext<TCtx = Record<string, unknown>> = {
readonly ctx: Readonly<Omit<TCtx, "logger">> & { readonly logger: RoutaLogger }
readonly onCleanup: OnCleanup
}

What a route-file or method services factory receives. It carries no request or handler input.

Field Type Purpose
ctx Readonly<Omit<TCtx, "logger">> & { logger } Context the middleware before the scope provided, earlier services, and the request logger
onCleanup OnCleanup Registers a callback that Routa runs after the response is ready
import type { RequestServicesContext } from "@routa-ts/core";
export function startTimer({ ctx, onCleanup }: RequestServicesContext<{ requestId: string }>) {
const started = Date.now();
onCleanup(() => ctx.logger.info("request.timed", `${ctx.requestId}: ${Date.now() - started} ms`));
return { started };
}

Errors: none. It is a type.

type RequestServicesFactory<TServices extends object = object, TCtx = Record<string, unknown>> = (
context: RequestServicesContext<TCtx>,
) => TServices | Promise<TServices>

Builds one request’s route-file or method services. It runs once for each request the scope applies to. defineServices checks a route-file or method factory against this type.

Type parameter Meaning
TServices The scope’s service contract
TCtx The context available before the scope runs

Returns the services, or a promise of them, with exactly the names TServices declares.

import type { RequestServicesFactory } from "@routa-ts/core";
type AuditServices = { audit: { record(event: string): void } };
export const auditServices: RequestServicesFactory<AuditServices, { requestId: string }> = ({
ctx,
}) => ({
audit: { record: (event) => ctx.logger.info("audit", `${ctx.requestId}: ${event}`) },
});

To type a factory for one of your project’s scopes, use the generated ServicesFactory from .routa/testing.gen.ts. It fills in the contract and the scope’s context, so you do not repeat either. ServicesFactory accepts only scopes your project declares, so the example below needs /orders services declared as in Route-File and Method Services. Keep the file outside src/routes, where every module is a route file:

src/factories/orders.ts
import type { ServicesFactory } from "../../.routa/testing.gen.js";
export const ordersServices: ServicesFactory<"/orders"> = ({ ctx, onCleanup }) => {
onCleanup(() => ctx.logger.info("orders.released", "Orders services released."));
return {
orders: {
list: async () => [],
place: async (total) => ({ id: crypto.randomUUID(), total }),
},
};
};

Errors: when the factory throws or returns different names, Routa skips the rest of the request, releases the scopes the request started, and responds with the standard 500 problem.

type RouteOutcome = {
status: number
description?: string
schema?: ZodType
headers?: ZodObject
cookies?: readonly (AnyCookie | RequiredCookie)[]
}
type RouteResponses = Record<string, RouteOutcome>
type MiddlewareRejectsSpec = RouteResponses
type OutcomeResult<TName extends string, TOutcome> = (TOutcome extends {
readonly schema: infer TSchema extends ZodType
}
? { readonly type: TName; readonly data: SchemaOutput<TSchema> }
: { readonly type: TName; readonly data?: never })
& OutcomeHeaders<TOutcome>
& OutcomeCookies<TOutcome>
// Internal helpers, not exported
type OutcomeHeaders<TOutcome> = TOutcome extends { readonly headers: infer THeaders extends ZodType }
? {} extends SchemaOutput<THeaders>
? { readonly headers?: SchemaOutput<THeaders> }
: { readonly headers: SchemaOutput<THeaders> }
: { readonly headers?: never }
type OutcomeCookies<TOutcome> = TOutcome extends { readonly cookies: readonly (infer TEntry)[] }
? Extract<TEntry, { readonly required: true }> extends never
? { readonly cookies?: readonly CookieEffect[] }
: { readonly cookies: readonly CookieEffect[] } // must include an effect for each required cookie
: { readonly cookies?: never }
type RoutaResult<TResponses extends RouteResponses> = {
[K in keyof TResponses]: OutcomeResult<K, TResponses[K]>
}[keyof TResponses]
type RouteRunResult<TResponses extends RouteResponses> = RoutaResult<TResponses>
type InferResponse<TResponses extends RouteResponses> = RouteRunResult<TResponses>
type MiddlewareRejectResult<TRejects extends MiddlewareRejectsSpec> =
keyof TRejects extends never ? never : RoutaResult<TRejects>
type ResponseChecks<TResponses extends RouteResponses> = {
readonly [K in keyof TResponses]: OutcomeChecks<TResponses[K]>
}

A schema-less outcome forbids data, an outcome without headers forbids headers, and an outcome without cookies forbids cookies. The source uses named error types for those fields so the compiler message names the outcome; the block shows them as never.

Type Meaning
RouteOutcome One named outcome in responses or rejects
RouteResponses A route’s responses map, keyed by outcome name
MiddlewareRejectsSpec A middleware’s rejects map, with the same shape
OutcomeResult The result object that selects one outcome
RoutaResult The union of every outcome’s result
RouteRunResult What a route’s run returns
InferResponse The same union, named for use outside a route
MiddlewareRejectResult What a middleware run returns to reject, or never when it declares none
ResponseChecks Compile-time rules for declared outcomes; a valid outcome adds no constraint

Use InferResponse to type a function that chooses an outcome outside the handler:

import type { InferResponse, RouteResponses } from "@routa-ts/core";
import { z } from "zod";
export const itemResponses = {
success: { status: 200, schema: z.object({ id: z.string() }) },
notFound: { status: 404 },
} as const satisfies RouteResponses;
/** { type: "success"; data: { id: string } } | { type: "notFound" } */
export type ItemResult = InferResponse<typeof itemResponses>;
export function findItem(id: string): ItemResult {
return id === "1" ? { type: "success", data: { id } } : { type: "notFound" };
}

HttpMethod, RouteInput, RouteOutcome, RouteResponses, OutcomeResult, ResponseChecks, RouteContract, AnyRouteContract, RouteRun, RouteHandlerArgs, ResponseBuilders, RoutaResult, RouteRunResult, InferInput, InferResponse, SchemaInput, SchemaOutput, RoutaRouteContext, RoutaConfig, ResponseValidation, ApplicationServicesFactory, ApplicationServicesContext, OnCleanup, RequestServicesFactory, RequestServicesContext, ServicesHelper, MiddlewareHelper, RouteDeprecation, RouteDeprecationReplacement, RegisteredRoutePath, ExternalApiUrl, ContextualRouteContract, RouteRootConfigForCtx, MiddlewareContract, AnyMiddlewareContract, MiddlewareRun, MiddlewareRunArgs, MiddlewareNext, MiddlewareContinuation, MiddlewareProvidesSpec, MiddlewareProvidesKeys, MiddlewareProvidedCtx, MiddlewareProvides, MiddlewareRejectsSpec, MiddlewareRejectResult, MiddlewareOpenApi, InferMiddlewareCtx, CookieConfig, CookieHandle, CookieEffect, CookieSameSite, RequiredCookie, AnyCookie, AuthenticationConfig, AuthenticationResult, Authenticator, AuthenticatorContext, CredentialChallenge, BearerOptions, BearerScheme, ApiKeyOptions, ApiKeyScheme, SessionCookieOptions, SessionCookieScheme, CustomOptions, CustomScheme, CustomTransport, CustomChallenge, CustomOpenApi, CustomExtraction, ExtractedCredential, CredentialScheme, Principal, PrincipalSchema, PrincipalOf, AuthContext, AnonymousAuthContext, AuthenticatedAuthContext, RequireAuthOptions, RequireAuthMiddleware, and Register.

From @routa-ts/core/hono: HonoRoute, CreateHonoAppOptions, CreateApplicationOptions, ApplicationServicesDeclaration, RequestServicesDeclaration, RouteServices, RoutaApplication, ProjectModuleLoader, CreateProjectApplicationOptions, ProjectApplication, ServiceReplacements. From @routa-ts/core/testing: ProjectModules, TestApplication. From @routa-ts/core/logger: RoutaLogger, RoutaLogLevel, RoutaLogLevelWithSilent, RoutaLogEvent, RoutaLogData, CreateLoggerOptions.