Schemas
Routa uses Zod for everything that crosses a boundary: route inputs, middleware inputs, context values middleware provides, and response payloads. A schema is simultaneously the runtime validator, the TypeScript type, and the OpenAPI definition.
import { z } from "zod";
export const CreateUserSchema = z.object({ email: z.email(), name: z.string().min(1),});
export const UserSchema = z.object({ id: z.string(), email: z.email(), name: z.string(),});createRoute({ input: { body: CreateUserSchema, }, responses: { success: { status: 201, schema: UserSchema, }, }, run: async ({ input }) => { return { type: "success", data: await users.create(input.body) }; },});How It Works
Section titled “How It Works”Routa parses each declared input source with schema.parse() before the handler runs, so
input.body is the schema’s output type, not its input type. A schema with a
transform or a default gives the handler the transformed value.
On the way out, Routa always checks the result shape, looks up its type in the declared
responses, and checks that data is present for an outcome with a schema and absent for
one without. By default, it parses data against the matching response schema in
routa dev and compares the parsed value with the value your handler returned. Invalid data,
or any change the schema would make, produces a generic 500 problem response before it
reaches a client. Production parsing and comparison are opt-in with
responseValidation: "always".
Declared response headers and cookies follow the same policy (see Response Headers and Response Cookies).
Write response schemas to describe wire-ready JSON: they should validate a value, not
change it. routa check reports ROUTA_RESPONSE_SCHEMA_MUTATION for response schemas that
use .transform(), z.preprocess(), .default(), .catch(), z.coerce.*, codecs such
as z.stringbool(), URL normalization with z.url({ normalize: true }), or value-rewriting
checks such as .trim(), .toLowerCase(), .toUpperCase(), .normalize(), .slugify(),
and .overwrite(). The same applies inside .pipe() targets, record keys, and
.check() arguments, including checks declared in the same file such as
const tidy = z.trim(). A .check() argument or URL options that Routa cannot read fail
with ROUTA_SCHEMA_UNSUPPORTED. Return the final value from the handler instead.
TypeScript rejects schemas whose input and output types differ, and known transformer
wrappers such as .transform(), .default(), and z.coerce.*, when you declare the
outcome. Same-type rewrites such as .trim() are visible only to routa check, and
z.url() trims surrounding whitespace without any marker in source. Runtime validation
catches those: when Routa validates response data, it never sends the parsed value. A
value the schema would change, including an unknown key it would strip, fails as invalid
handler output.
Routa does not parse response data when validation is disabled, so the handler value is
sent as returned. Middleware provides schemas remain active in both modes because their
parsed values become downstream context. See
Configuration for the full policy.
How Schemas Become OpenAPI
Section titled “How Schemas Become OpenAPI”Routa reads schemas statically from source. It never imports or runs your modules to
generate OpenAPI. A schema can live in the route’s sibling schemas.ts, in the route file
itself, in the file that declares a middleware, or in any module those files import by
name through a relative path. Routa follows named imports, aliases, and
export { ... } from or export * from re-exports to the const that declares the
schema, then reads it in that file. A schema imported from a package or through a
tsconfig path alias, or one returned by your own function, fails routa check with
ROUTA_SCHEMA_UNRESOLVED or ROUTA_SCHEMA_UNSUPPORTED.
Composition follows Zod’s meaning, not a fixed keyword:
| Zod | OpenAPI 3.1 |
|---|---|
z.union([...]), .or() |
anyOf |
z.discriminatedUnion("kind", [...]) |
oneOf with discriminator.propertyName: "kind" |
z.intersection(a, b), .and() |
allOf, or one object when both sides are objects |
z.record(key, value) |
additionalProperties, with key rules in propertyNames |
.nullable() |
anyOf with { type: "null" } |
.optional(), .nullish() |
The property leaves required |
Like Zod, an intersection rejects unknown keys only when every member is strict. A strict
member that stays in allOf is documented open, so the combined object stays possible.
Intersected object schemas in params, query, headers, or cookies split into
parameters, even when the members are exported or described.
Input schemas describe what a client sends. A property with .default() or .catch() is
optional, z.coerce.number() is a number, and .transform() or .pipe() after a readable
schema documents that readable schema. z.stringbool() is a boolean parameter, following
the OpenAPI convention for "true" and "false" strings, and a string property in a JSON
body. z.preprocess() and a leading z.transform() run a
function before any schema Routa can read, so routa check prints a
ROUTA_SCHEMA_OPAQUE_INPUT warning and OpenAPI documents the schema that follows. The
route still runs.
Response Headers
Section titled “Response Headers”An outcome can declare the headers it sends. headers is a Zod object keyed by lowercase
header names, and its values are strings, numbers, or booleans (or literals and enums of
them), optionally wrapped with .optional(), .readonly(), or .nonoptional(), combined
with z.union() or z.intersection(), or piped into another scalar schema such as
z.string().pipe(z.email()). A required header becomes a required property of the handler
result’s headers, an optional one becomes optional, and an outcome that declares none
forbids headers.
import { createRoute } from "@routa-ts/core";import { z } from "zod";
createRoute({ responses: { created: { status: 201, schema: z.object({ id: z.string() }), headers: z.object({ location: z.string().describe("Where the new user lives"), "x-request-cost": z.number().optional(), }), }, accepted: { status: 202, headers: z.object({ "retry-after": z.number() }), }, }, run: ({ response }) => response.created({ id: "1" }, { location: "/users/1" }),});A body outcome’s builder takes its data and then its headers, and a bodyless outcome’s
builder takes only its headers. A handler can also return { type, data, headers }
directly. Routa serializes a string as is, a finite number with String(), and a boolean as
true or false, so one value always produces one header string.
Header identity is case-insensitive and has one owner. Routa owns content-type,
content-length, transfer-encoding, connection, and set-cookie, and it never gives a
bodyless outcome a content header. When lifecycleHeaders is on, Routa also owns
deprecation, sunset, and the successor link on routes that declare deprecation.
A declaration that claims one of those names fails, and so does a result that writes an
undeclared header, writes the same header in two cases, or omits a required one. Nothing
merges or overwrites. Header schemas follow the response-schema rules above: they describe
wire-ready values and must not change them.
Routa checks declared names, required headers, and safe field values (no line breaks, no
control characters other than tab, no surrounding whitespace) in every mode. It parses header values with
their Zod schemas and compares the result with the value you returned under the same
responseValidation policy as the body. Routa has no multi-value header support, and
Set-Cookie is not a header you can declare: use Response Cookies.
Response Cookies
Section titled “Response Cookies”An outcome can set or clear cookies. createCookie declares a cookie once, with its name, a
value schema, and static attributes, and returns a handle. An outcome lists the handles it
may emit in cookies, and the handler returns effects from handle.set(value) and
handle.clear(). The effects are plain descriptions: nothing touches a response until Routa
validates and serializes them.
import { createCookie } from "@routa-ts/core";import { z } from "zod";
export const session = createCookie({ name: "session", schema: z.string(), httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 3600,});import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";import { session } from "../../cookies.js";
export default createRouteRoot("/session")({ post: createRoute({ responses: { created: { status: 201, schema: z.object({ ok: z.boolean() }), cookies: [session] }, }, run: () => ({ type: "created", data: { ok: true }, cookies: [session.set("abc123")] }), }),});httpOnly, secure, sameSite, and path are required. domain, maxAge, expires, and
partitioned are optional. expires is an ISO 8601 date-time string, such as
"2030-01-01T00:00:00Z". Routa reads the name and every attribute from source without
running it, so write each one as a literal. A computed attribute fails routa check.
Handles are shared: import one from any module, through relative imports and re-exports,
and list it in every outcome that may emit it. Routa follows export const, a name exported
later with export { session } or export { session as auth }, export { session } from,
and export * from, all through relative modules. It does not follow package imports.
A bare handle in cookies is optional: the outcome sends the effects it returns. To require
an effect, write the entry as a literal { handle, required: true }:
cookies: [{ handle: session, required: true }, theme],Every required handle needs a set or clear effect in the result. TypeScript rejects a
result that leaves one out, including an empty cookies array, and Routa fails the response
in every validation mode if it still happens. An outcome with a required cookie has no
builder, so return the result object. The cookies result field is forbidden when the
outcome declares none, and an effect from a handle the outcome does not list fails
TypeScript. Builders (response.created(...)) do not take cookies; return the result object.
A cookie handle has these rules:
sameSite: "none"andpartitioned: truerequiresecure: true.- A
__Secure-name requiressecure: true. A__Host-name requiressecure: true,path: "/", and nodomain. The prefixes match without regard to case. - The name is an RFC 6265 token. The path starts with
/, uses printable ASCII without;, and has no trailing space: write non-ASCII characters percent-encoded, such as"/caf%C3%A9". Routa sends the path exactly as written, so the identity you declare is the scope a browser applies.maxAgeis a non-negative whole number of seconds. - The value schema accepts a string, number, or boolean (or a literal or enum of them) and must not change values, like any response schema.
Routa encodes a value with encodeURIComponent (numbers and booleans with String()), so only
cookie octets reach the wire and the request-side cookies parser reads the value back.
Attributes always appear in the order Domain, Path, Expires, Max-Age, HttpOnly, Secure,
SameSite, Partitioned. clear() keeps the name, domain, path, and security attributes, drops
the original maxAge and expires, and adds Max-Age=0 and an epoch Expires.
Cookie identity is the name, domain, and path. One producer owns an identity in a response:
returning the same handle twice, or declaring two handles with one identity in an outcome,
fails instead of choosing one. Two cookies that share a name but differ in domain or path are
allowed, and Routa warns about them in routa check and at startup. Routa sends each cookie
as its own Set-Cookie field, never joined with commas. Terminal middleware rejects accept
headers and cookies and follow every rule on this page: TypeScript, routa check,
startup, runtime validation, and OpenAPI treat them like route outcomes.
Routa checks declared handles, required effects, one effect per identity, and safe encoding in every mode. It
parses a set value with the handle’s schema and compares the result with the value you
returned under the same responseValidation policy as the body. A raw Set-Cookie header is
not declarable.
Documentation Metadata
Section titled “Documentation Metadata”Zod’s .describe() and .meta() are the documentation interface. Routa copies literal
title, description, deprecated, example, examples, readOnly, writeOnly,
externalDocs, and x- extension keys onto the Schema Object wherever the schema
appears: at the root of a body or response, on a nested property, or in a component.
import { z } from "zod";
export const Address = z .object({ city: z.string().describe("City name") }) .meta({ id: "PostalAddress", title: "Address", examples: [{ city: "Lima" }] });
export const UserSchema = z.object({ id: z.string().meta({ description: "User id", readOnly: true }), address: Address,});Metadata must be a literal Routa can read without running code. Routa reports
ROUTA_SCHEMA_META_STRUCTURAL for keys that would override the schema itself, such as
type or default, ROUTA_SCHEMA_META_PLACEMENT for keys that belong to the route, such
as in or operationId, ROUTA_SCHEMA_META_COMPUTED for values computed at runtime, and
ROUTA_SCHEMA_REGISTRY for z.globalRegistry or .register().
Where Schemas Live
Section titled “Where Schemas Live”Route-local schemas in a sibling schemas.ts are the default, and scaffolding generates
them that way. When an OpenAPI document declares reusable components.schemas, scaffolding
writes each one into the schemas.ts of every route that uses it. Equal copies share one
component, so you can keep them or move a shared schema into one module and import it.
Exported schema names must be unique within a schemas.ts file. Routa reports
ROUTA_DUPLICATE_SCHEMA_NAME for repeats. Prefer contract-purpose names like
CreateUserResponse over generic ones like Response.
An exported schema that a route uses becomes an OpenAPI component named after its export.
.meta({ id: "PostalAddress" }) names the component explicitly, and an alias such as
export const GetUserResponse = User reuses User’s component. Schemas declared inline
without an id stay inline. Two route directories may each declare an identical User
and share one component. If the two declarations differ, or two different declarations
claim the same id, Routa reports ROUTA_SCHEMA_COMPONENT_COLLISION instead of renaming
either one.
Query Helpers
Section titled “Query Helpers”Query strings arrive as strings, so common list parameters need a parse step. Routa ships two helpers for the two most common cases:
import { Fields, Sort } from "@routa-ts/core/query/helpers";import { z } from "zod";
export const ListUsersQuery = z.object({ sort: Sort(["name", "createdAt"]).optional(), fields: Fields(["id", "name", "email"]).optional(),});Sort accepts a field name with an optional - prefix and produces
{ field, direction }. A request for ?sort=-createdAt gives the handler
{ field: "createdAt", direction: "desc" }, and any field outside the allowed list is
rejected. Fields splits a comma-separated list into a validated array, so
?fields=id,name becomes ["id", "name"]. OpenAPI documents both parameters as the
strings clients send.
- Validate at the boundary only. A schema describes what the HTTP contract accepts, not what your domain considers valid; keep business rules in services.
- Keep response schemas narrow. Anything the schema permits is something a client may receive and OpenAPI will advertise.
- Use
responseValidation: "always"when you need production drift detection. - Keep response schemas validation-only. Shape the value in the handler.
Limits
Section titled “Limits”Zod is the only supported schema library in v0, and Routa requires Zod ^4.6.7. Routa
reads primitives, string formats, z.literal, z.enum with inline values, z.object,
z.array, z.record, unions, intersections, wrappers such as .optional() and
.nullable(), checks such as .min() and .refine(), and metadata. Any other construct,
such as z.tuple(), .extend(), or a schema built by your own function, fails
routa check with ROUTA_SCHEMA_UNSUPPORTED instead of producing a guessed or empty
OpenAPI schema. Checks such as .min() validate at runtime but are not yet documented as
OpenAPI keywords.