Migrate Response Contracts
The Advanced response contract makes each named outcome one declaration for its status, body
or bodylessness, headers, cookies, and OpenAPI response, and ordinary body outcomes keep their
source. Source that no longer fits reports a TypeScript error or a routa check diagnostic.
This guide shows the fix for each one, and the changes no command reports: stricter response
validation at runtime and OpenAPI metadata that openapi check does not compare.
Before You Start
Section titled “Before You Start”- A committed working tree, so the migration is the only diff.
- A passing
routa openapi checkon the version you are leaving, so drift the upgrade introduces is not mixed with drift you already had.
-
Upgrade Routa and Zod. Routa requires Zod
^4.6.7, and new projects declare that range.Terminal window npm install @routa-ts/core@latest @routa-ts/cli@latest zod@^4.6.7Terminal window pnpm add @routa-ts/core@latest @routa-ts/cli@latest zod@^4.6.7Terminal window yarn add @routa-ts/core@latest @routa-ts/cli@latest zod@^4.6.7Terminal window bun add @routa-ts/core@latest @routa-ts/cli@latest zod@^4.6.7 -
Run the check. Routa validates the route graph first and runs TypeScript once that passes, so expect more than one round.
Terminal window npx routa checkTerminal window pnpm exec routa checkTerminal window yarn exec routa checkTerminal window bunx routa check -
Fix each reported code or compiler error with the matching section under What Changed, then run the check again until it passes.
-
Run your tests, or exercise your routes under
routa dev. Development response validation now fails a value the response schema would change, including an extra key it would strip, instead of sending the changed value. -
Compare the generated OpenAPI document with your baseline.
Terminal window npx routa openapi checkTerminal window pnpm exec routa openapi checkTerminal window yarn exec routa openapi checkTerminal window bunx routa openapi check -
Review each reported difference against OpenAPI Comes From Source, then accept the new contract and commit the baseline.
Terminal window npx routa openapi breaking --update-baselineTerminal window pnpm exec routa openapi breaking --update-baselineTerminal window yarn exec routa openapi breaking --update-baselineTerminal window bunx routa openapi breaking --update-baselineOpenAPI baseline updated.
Verify
Section titled “Verify”Both commands pass:
Routa validation passed for 5 route file(s).Running TypeScript check: tsc -p tsconfig.json --noEmitTypeScript check passed.Routa check passed.OpenAPI check passed. No drift detected.What Changed
Section titled “What Changed”Bodyless Outcomes Have No Schema
Section titled “Bodyless Outcomes Have No Schema”204, 205, and 304 outcomes, and every outcome of a HEAD route, cannot declare a
schema or return data. Routa used to require both and then discard the data.
deleted: { status: 204, schema: z.null() },// ...return { type: "deleted", data: null };import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";
const route = createRouteRoot("/users/:userId");
export default route({ delete: createRoute({ input: { params: z.object({ userId: z.string() }), }, responses: { deleted: { status: 204 }, }, run: () => { return { type: "deleted" }; }, }),});The same applies to a middleware reject that can end a HEAD route: remove its schema.
routa check reports ROUTA_RESPONSE_BODYLESS_SCHEMA, and TypeScript reports
Status 204 responses have no body, so the outcome cannot declare a schema. Returning
data from an outcome without a schema reports
Outcome deleted declares no schema, so it cannot return data. A 304 outcome is valid
only on GET and HEAD routes (ROUTA_RESPONSE_NOT_MODIFIED_METHOD), and a 1xx status
cannot be an outcome (ROUTA_RESPONSE_INFORMATIONAL_STATUS).
Response Schemas Validate Without Changing Values
Section titled “Response Schemas Validate Without Changing Values”A response schema describes the JSON your handler already produced. Move transforms,
defaults, catches, coercion, and value-rewriting checks such as .trim() into the handler.
export const User = z.object({ name: z.string().trim(), plan: z.string().default("free"),});// ...return { type: "success", data: user };import { z } from "zod";
export const User = z.object({ name: z.string(), plan: z.string(),});import { createRoute, createRouteRoot } from "@routa-ts/core";import { User } from "./schemas.js";
const route = createRouteRoot("/me");
const stored: { name: string; plan?: string } = { name: " Ada Lovelace " };
export default route({ get: createRoute({ responses: { success: { status: 200, schema: User }, }, run: () => { return { type: "success", data: { name: stored.name.trim(), plan: stored.plan ?? "free" } }; }, }),});routa check reports ROUTA_RESPONSE_SCHEMA_MUTATION and names the construct. For
transforms, defaults, catches, and coercion, TypeScript also reports
Response schemas describe wire-ready JSON and must not change values. Input schemas are
unaffected: they may still transform, coerce, and default.
Response Data Matches Its Schema Exactly
Section titled “Response Data Matches Its Schema Exactly”When Routa validates response data, in routa dev by default and everywhere with
responseValidation: "always", it compares the parsed value with what the handler returned
and sends the handler’s value. Any difference is a 500 Invalid handler output. A plain
z.object() strips unknown keys, so an object with extra keys used to be trimmed in
development. Now it fails there. Production skips validation by default and sends the value
as returned, so drop the fields in the handler instead of relying on the schema.
const row = await db.users.find(id); // includes passwordHashreturn { type: "success", data: row };import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";
const route = createRouteRoot("/users/:userId");
const rows = new Map([["usr_1", { id: "usr_1", name: "Ada", passwordHash: "$2b$10$..." }]]);
export default route({ get: createRoute({ input: { params: z.object({ userId: z.string() }), }, responses: { success: { status: 200, schema: z.object({ id: z.string(), name: z.string() }) }, notFound: { status: 404, schema: z.object({ message: z.string() }) }, }, run: ({ input }) => { const row = rows.get(input.params.userId);
if (!row) { return { type: "notFound", data: { message: "User not found." } }; }
return { type: "success", data: { id: row.id, name: row.name } }; }, }),});Dates Are ISO Strings
Section titled “Dates Are ISO Strings”z.date() has no JSON form. Declare the string the client receives and return it.
createdAt: z.date(),// ...data: { createdAt: row.createdAt },import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";
const route = createRouteRoot("/status");
const startedAt = new Date();
export default route({ get: createRoute({ responses: { success: { status: 200, schema: z.object({ startedAt: z.iso.datetime() }) }, }, run: () => { return { type: "success", data: { startedAt: startedAt.toISOString() } }; }, }),});routa check reports ROUTA_SCHEMA_UNSUPPORTED with the suggestion to use
z.iso.datetime().
Schemas Come From Source Routa Can Read
Section titled “Schemas Come From Source Routa Can Read”Routa reads schemas from source without running it, so it no longer fills in a schema from
the baseline. A schema can be declared in the route file, its sibling schemas.ts, or the
file that declares a middleware, or exported with export const from a module those files
import by name through a relative path. Routa follows aliases and
export { ... } from or export * from re-exports to the declaration. It does not resolve
package imports or tsconfig path aliases, which report ROUTA_SCHEMA_UNRESOLVED, or a
schema returned by your own function, which reports ROUTA_SCHEMA_UNSUPPORTED. A route
input built from a spread or a shared variable also reports ROUTA_SCHEMA_UNSUPPORTED.
import { User } from "@/schemas/user.js";import { z } from "zod";
export const User = z.object({ id: z.string(), name: z.string() });import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";import { User } from "../../schemas/user.js";
const route = createRouteRoot("/users");
export default route({ get: createRoute({ responses: { success: { status: 200, schema: z.object({ users: z.array(User) }) }, }, run: () => { return { type: "success", data: { users: [{ id: "usr_1", name: "Ada" }] } }; }, }),});Every route that imports User shares one User component in OpenAPI. Two routes may also
each declare an identical User, and they share the component too. If two declarations
named User differ, Routa reports ROUTA_SCHEMA_COMPONENT_COLLISION instead of picking
one.
Handler Results Name a Declared Outcome
Section titled “Handler Results Name a Declared Outcome”A result’s type must be one of the route’s outcome names. A type read from a string
variable no longer type-checks, even when its data matches an outcome.
const type: string = found ? "success" : "notFound";return { type, data };import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";
const route = createRouteRoot("/users/:userId");
const users = new Map([["usr_1", { id: "usr_1", name: "Ada" }]]);
export default route({ get: createRoute({ input: { params: z.object({ userId: z.string() }), }, responses: { success: { status: 200, schema: z.object({ id: z.string(), name: z.string() }) }, notFound: { status: 404, schema: z.object({ message: z.string() }) }, }, run: ({ input, response }) => { const user = users.get(input.params.userId);
return user ? response.success(user) : response.notFound({ message: "User not found." }); }, }),});TypeScript reports that type string is not assignable to the outcome names.
Outcomes That Share a Status Need a Discriminator
Section titled “Outcomes That Share a Status Need a Discriminator”OpenAPI used to keep whichever schema was written last for a status. Now outcomes that share
a status compose into one response, and each body outcome needs a required property with a
different literal value. Otherwise, give each outcome its own status. Middleware rejects take
part too: a route 403 outcome next to a middleware’s 403 reject needs the same
discriminator in both.
created: { status: 201, schema: z.object({ id: z.string() }) },queued: { status: 201, schema: z.object({ ticket: z.string() }) },import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";
const route = createRouteRoot("/jobs");
export default route({ post: createRoute({ input: { body: z.object({ background: z.boolean() }), }, responses: { created: { status: 201, schema: z.object({ kind: z.literal("created"), id: z.string() }) }, queued: { status: 201, schema: z.object({ kind: z.literal("queued"), ticket: z.string() }) }, }, run: ({ input, response }) => { return input.body.background ? response.queued({ kind: "queued", ticket: "tkt_1" }) : response.created({ kind: "created", id: "job_1" }); }, }),});routa check reports ROUTA_RESPONSE_STATUS_AMBIGUOUS, which also covers a body and a
bodyless outcome under one status and two bodyless outcomes under one status. See
Outcomes That Share a Status.
Outcome Names Are Unique Across the Chain
Section titled “Outcome Names Are Unique Across the Chain”A route outcome cannot reuse the name of a reject from any middleware in its chain, and two rejects cannot share a name. Remove the route outcome: the reject is already part of the operation and its OpenAPI document.
responses: { success: { status: 200, schema: Report }, unauthorized: { status: 401, schema: z.object({ message: z.string() }) },},import { createMiddleware } from "@routa-ts/core";import { z } from "zod";
export const requireAuth = createMiddleware({ input: { headers: z.object({ authorization: z.string().optional() }), }, rejects: { unauthorized: { status: 401, schema: z.object({ message: z.string() }) }, }, run: ({ input, next }) => { if (!input.headers.authorization) { return { type: "unauthorized", data: { message: "Authentication required" } }; }
return next(); },});import { createRoute, createRouteRoot } from "@routa-ts/core";import { z } from "zod";import { requireAuth } from "../../middleware/auth.js";
const route = createRouteRoot("/reports");
export default route({ get: createRoute({ middleware: [requireAuth], responses: { success: { status: 200, schema: z.object({ total: z.number() }) }, }, run: () => { return { type: "success", data: { total: 42 } }; }, }),});routa check reports ROUTA_OUTCOME_NAME_COLLISION, and the app fails at startup with
Outcome "unauthorized" on GET /reports is declared by … and by …. Give each outcome its own name. For a reject of the
route’s own middleware, TypeScript also reports
Outcome "unauthorized" is also a reject of this route's middleware. Give each outcome its own name.
Middleware Returns next() Unchanged
Section titled “Middleware Returns next() Unchanged”next() resolves to an opaque value: the outcome the rest of the chain selected. A
continuing middleware must return it as is. It cannot read the outcome, copy it, or add to
it. Make response decisions in the handler, or in a reject the middleware returns before
calling next().
run: async ({ next }) => { const result = await next(); console.info(`audit: ${result.type}`); return result;},import { createMiddleware } from "@routa-ts/core";import { z } from "zod";
export const audit = createMiddleware({ input: { headers: z.object({ "x-actor": z.string().optional() }), }, run: ({ input, next }) => { console.info(`audit: ${input.headers["x-actor"] ?? "anonymous"}`); return next(); },});Routa already logs every request’s method, path, status, and duration as http.request.
TypeScript reports Return the value next() resolved to, unchanged. for a changed value,
and Routa answers 500 Invalid handler output for anything else returned after next().
MiddlewareNext and MiddlewareRunArgs lost their unused reject type parameter, so drop
the last argument from explicit references such as MiddlewareNext<Provides, Rejects>.
OpenAPI Comes From Source
Section titled “OpenAPI Comes From Source”The generated document no longer copies anything from .routa/openapi-baseline.json. Your
first openapi check after upgrading reports these differences:
- Statuses and
securitythat existed only in the baseline disappear. - Schemas change where Routa now reads them correctly: metadata from
.describe()and.meta()appears, query helpers such asSort()are documented as the strings clients send, and schema-less outcomes have nocontent. Exported schemas a route uses becomecomponents.schemasentries named after their exports; a$refand an equal inline schema are not drift.
openapi check ignores operationId, info, servers, and prose descriptions, so these
changes appear only in the baseline diff that --update-baseline writes:
- Every
operationIdis the method plus the PascalCase path, sogetUseronGET /users/{userId}becomesgetUsersUserId. Tell client generators and other consumers that key on operation IDs. infois alwaysRouta APIat version0.0.0, andserversis no longer emitted.- A response description is the outcome’s
descriptionor its humanized name, such as “Not found”, instead of “Generated by Routa”.
The generated Set-Cookie header description is the exception: it lists cookie names and
attributes, which are contract facts, so openapi check compares it. Two routes whose paths
generate the same operationId report ROUTA_DUPLICATE_OPERATION_ID.
Other Diagnostics
Section titled “Other Diagnostics”routa check now fails on schemas it used to skip or document as {}. Each code has its
cause and fix in Diagnostics.
| Code | Fix |
|---|---|
ROUTA_SCHEMA_UNSUPPORTED |
Rewrite the schema with a construct Routa reads, such as z.object |
ROUTA_SCHEMA_META_STRUCTURAL |
Remove keys such as type or default from .meta() |
ROUTA_SCHEMA_META_PLACEMENT |
Move route keys such as operationId out of .meta() |
ROUTA_SCHEMA_META_COMPUTED |
Write metadata values as literals |
ROUTA_SCHEMA_REGISTRY |
Replace z.globalRegistry and .register() with .meta() |
ROUTA_SCHEMA_OPAQUE_INPUT (warning) |
Parse with a declarative schema before .transform(), or accept the warning |
A createMiddleware config built with a spread that could hide its rejects also reports
ROUTA_SCHEMA_UNSUPPORTED. Write rejects in the createMiddleware call.
Troubleshooting
Section titled “Troubleshooting”| Problem | Fix |
|---|---|
500 Invalid handler output in routa dev from a route that used to work |
The response data has extra keys or a value the schema would change. Return exactly the declared shape. |
The package manager warns about the zod peer |
Install zod@^4.6.7. |
openapi check reports drift on routes you did not touch |
Expected once: the document now comes from source. Review it and run openapi breaking --update-baseline. |
| A generated client lost its method names | Operation IDs were renamed once from the method and path. Regenerate the client and update call sites. |