Development Playbook

Upgrade to Zod 4 and prove what changed: record the old behaviour, let the agent migrate, review the diff

Zod 4 compiles fine and still changes what your API accepts. A baseline recorded on 3.x, a test that replays it on 4.x and a two-file rule for the agent turn the upgrade into a short list of decisions. About 30 minutes on one project.

Two identical brass dials side by side on a dark workbench, their needles a few degrees apart, with pink halftone dots glowing in the gap between them

A Zod upgrade is the kind of change that goes green and still breaks production. The types line up, the build passes, and the 4.x schema quietly accepts a payload the 3.x one rejected, or rejects one it used to wave through. Nobody notices until a client sends a UUID from a legacy system or a mobile build omits a key, and a request that worked yesterday returns a 400.

Zod 4 documents its breaking changes in one long page, and an agent will read it and apply the renames confidently. What it can’t do is know which of those changes your callers depend on. That knowledge lives in the behaviour of your schemas on real inputs, and the cheapest way to capture it is to run the old version first and write down what it did.

This Playbook builds that gate in about 30 minutes. The same unmodified schema file runs under 3.x and under 4.x, a Vitest test compares the two, and every difference becomes a decision a person makes: restore the old behaviour, or accept the new one on the record. The agent does the edits. The comparison decides what the edits mean. It works with any agent that can read files and run a shell, because the whole check is npx vitest run.

What you need

A TypeScript project that validates input with Zod 3.x (3.25 or later), Vitest, and Node. The example below uses Vitest 5.1.0, TypeScript 7.0.2, Node 22.23.4, zod 3.25.76 and zod 4.6.7. Nothing depends on those exact versions apart from Zod itself.

The trick is that npm can install two copies of one package under different names. Keep the old major as a dev dependency under an alias, then move the real dependency forward:

npm i -D zod3@npm:zod@3.25.76
npm i zod@^4

Application code keeps importing zod. Only the test configuration decides which copy answers. Zod 3.25.x ships its 3.x API at the package root, so zod3 behaves exactly like the version you’re leaving.

Commit before you start. Everything below is easier to review as a diff against a clean tree.

The schemas under test

Take the schema file that guards your API edge. Here’s a small one with nine schemas, each chosen because the changelog says it moves:

// src/schemas.ts (as it stands on Zod 3)
import { z } from "zod";
export const schemas = {
  orderId: z.string().uuid(),
  quantity: z.number().int(),
  unitPrice: z.number(),
  label: z.string().transform((v) => v.length).default("tuna" as never),
  coupon: z.object({ code: z.string().default("NONE").optional() }),
  payload: z.object({ body: z.unknown() }),
  paging: z.object({ page: z.coerce.number() }),
  name: z.object({ name: z.string({ required_error: "name is required" }) }),
  flags: z.record(z.enum(["a", "b"]), z.number()),
};

In a real project these are your request schemas, and they’re spread across files. Point the test at whichever modules export them. The test only needs a name and a schema to run.

Step 1: list the inputs, not the answers

The cases file holds inputs and a one-line note. It never holds expected results, because expected results come from running the old version.

// src/cases.ts
export type Case = { schema: string; input: unknown; note: string };

export const cases: Case[] = [
  { schema: "orderId", input: "123e4567-e89b-12d3-a456-426614174000", note: "textbook v1 UUID" },
  { schema: "orderId", input: "00000000-0000-0000-0000-000000000000", note: "nil UUID" },
  { schema: "orderId", input: "123e4567-e89b-12d3-c456-426614174000", note: "variant bits not 10" },
  { schema: "quantity", input: 3, note: "ordinary integer" },
  { schema: "quantity", input: 2 ** 60, note: "integer beyond safe range" },
  { schema: "unitPrice", input: Infinity, note: "infinite price" },
  { schema: "label", input: undefined, note: "missing, default plus transform" },
  { schema: "label", input: "abcd", note: "present, transform runs" },
  { schema: "coupon", input: {}, note: "default inside optional, key absent" },
  { schema: "payload", input: {}, note: "z.unknown() key absent" },
  { schema: "paging", input: {}, note: "z.coerce.number() key absent" },
  { schema: "paging", input: { page: "2" }, note: "coerce from string" },
  { schema: "name", input: {}, note: "required_error message" },
  { schema: "flags", input: { a: 1 }, note: "record with enum keys, b missing" },
];

Where do the inputs come from? Three sources, in order of value. Real payloads from fixtures or a sanitised sample of logs, because those are what callers send. The boundary values from the changelog (the cases above). And the agent, asked to write more inputs. That last use is safe precisely because it writes questions and never answers.

A prompt that works with any agent:

Read src/schemas.ts. For each schema, append cases to src/cases.ts: valid
inputs, inputs that are just invalid, missing keys, null, empty strings,
very large numbers, and any value a client in a different language might
plausibly send. Write inputs and a one-line note only. Do not write
expected results, do not touch any other file, and do not run the tests.

Keep the list to what you’d defend in review. Thirty to fifty cases per schema file is plenty. The changelog hints are a starting point, not a ceiling: every .refine, every transform and every place a schema is composed from another deserves a case.

Step 2: the test that records and replays

One test file does both jobs. With BASELINE=1 it runs against the old major and writes baseline.json. Without it, it runs against whatever zod resolves to and compares each case with the baseline, unless a person has accepted the difference.

// src/behaviour.test.ts
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { cases } from "./cases.ts";
import { schemas } from "./schemas.ts";

const file = "baseline.json";
const key = (c: { schema: string; note: string }) => `${c.schema} / ${c.note}`;

function outcome(schema: any, input: unknown) {
  const r = schema.safeParse(input);
  const out = r.success
    ? { ok: true, data: r.data }
    : { ok: false, issues: r.error.issues.map((i: any) => `${i.path.join(".") || "(root)"}: ${i.message}`) };
  return JSON.parse(JSON.stringify(out, (_, v) => (v === Infinity ? "Infinity" : v === undefined ? "undefined" : v)));
}

const actual = Object.fromEntries(cases.map((c) => [key(c), outcome((schemas as any)[c.schema], c.input)]));

describe("schema behaviour", () => {
  if (process.env.BASELINE) {
    it("records the baseline", () => {
      writeFileSync(file, JSON.stringify(actual, null, 2) + "\n");
      expect(Object.keys(actual)).toHaveLength(cases.length);
    });
    return;
  }
  const baseline = JSON.parse(readFileSync(file, "utf8"));
  // Differences a person has read and accepted: { "<case>": { reason, now } }
  const accepted = existsSync("accepted.json") ? JSON.parse(readFileSync("accepted.json", "utf8")) : {};
  it.each(cases.map(key))("%s", (k) => {
    expect(actual[k]).toEqual(accepted[k]?.now ?? baseline[k]);
  });
});

The outcome records the parsed data, or the list of issues as path: message strings. It uses issues because that property exists in both majors. .errors was dropped in 4.x, so a test that read it would fail for the wrong reason.

The configuration that swaps the copy:

// vitest.config.mts
import { defineConfig } from "vitest/config";

// BASELINE=1 points "zod" at the old major, so the same unmodified source runs on both.
export default defineConfig({
  resolve: { alias: process.env.BASELINE ? { zod: "zod3" } : {} },
});

Record the baseline while the schemas are still untouched:

BASELINE=1 npx vitest run
git add baseline.json src/cases.ts src/behaviour.test.ts vitest.config.mts package.json
git commit -m "Record Zod 3 behaviour baseline"

On PowerShell, set the variable first with $env:BASELINE = "1". Commit the baseline before anything else changes. It’s the ground truth, and from here on nobody edits it by hand.

Step 3: run it on 4.x and read what changed

Run the suite on the new major without touching the schemas at all:

npx vitest run

Nine of the fourteen cases fail:

     × orderId / variant bits not 10 6ms
     × quantity / integer beyond safe range 1ms
     × unitPrice / infinite price 1ms
     × label / missing, default plus transform 1ms
     × coupon / default inside optional, key absent 1ms
     × payload / z.unknown() key absent 1ms
     × paging / z.coerce.number() key absent 1ms
     × name / required_error message 0ms
     × flags / record with enum keys, b missing 1ms
 Tests  9 failed | 5 passed (14)

Each failure carries the old and new outcome. For the default-plus-transform case it reads expected { ok: true, data: 'tuna' } to deeply equal { ok: true, data: 4 }: the 3.x schema fed the default through the transform and returned its length, and the 4.x one short-circuits and returns the default itself. The type checker would never flag that, because the schema still compiles.

Here’s the same information as a table, with what the changelog says about each:

CaseZod 3Zod 4Changelog
UUID with variant bits cacceptedrejected.uuid() enforces RFC 9562 variant bits, z.guid() is the loose form
2 ** 60 as .int()acceptedrejected.int() accepts safe integers only
Infinity as a numberacceptedrejectedinfinities are no longer valid numbers
missing key, default plus transform4"tuna"default short-circuits, .prefault() keeps the old order
{} for a default inside .optional(){}{ code: "NONE" }defaults apply inside optional keys
{} for z.unknown() keyacceptedrejectedkey no longer optional (from 4.4.0)
missing coerce keyerror, “nan”error, “NaN”message text only
required_errorcustom messagedefault messagerequired_error dropped, use error
enum-keyed record missing bacceptedrejectedrecord is exhaustive, use z.partialRecord()

Two cases deserve a second look. The coerce case fails on the same key in both versions, so a caller sees a 400 either way and only the message text moved. That’s a difference nobody needs to fight over, but the test still reports it, and that’s the point: the list of differences is complete and a person decides which ones matter.

The z.unknown() row depends on the 4.x release you land on. The changelog says versions 4.0 to 4.3 accepted a missing key and 4.4.0 onwards rejects it. A baseline test run on 4.3 would have hidden that one. Pin the new version in the run, not a range, until the suite is green.

Step 4: give the agent a narrow job

Now the migration itself. The risk with “upgrade Zod and make the tests pass” is the cheapest fix: edit the baseline, loosen a case, delete one that fails. The rule that prevents it is a list of what the agent may touch.

Upgrade the project from Zod 3 to Zod 4. The baseline is the contract.

You may edit: src/schemas.ts and any other non-test file that imports zod.
You may not edit: baseline.json, src/behaviour.test.ts, vitest.config.mts,
src/cases.ts, accepted.json.

Run `npx vitest run` after each change. For every failing case, decide:
- Restore: change the schema (not the test) so Zod 4 gives the baseline
  result. Prefer the replacement the Zod 4 changelog names.
- Propose: if the new behaviour looks right, do NOT edit anything. Add the
  case name, the old and new result and one sentence of reasoning to a list
  at the end of your reply.

Do not silence a failure with `as any`, a try/catch or a looser schema than
the baseline had.

The two verbs matter. Restoring is a code change the suite verifies. Proposing leaves the decision with a person. An agent that can’t mark a difference as acceptable can’t quietly turn a regression into a feature.

Do check that the rule held. A short gate script makes the check mechanical, and it runs in CI too:

#!/usr/bin/env bash
# gate.sh: the contract files must be exactly what was committed
set -euo pipefail
git diff --exit-code HEAD -- baseline.json src/behaviour.test.ts vitest.config.mts
npx vitest run

The git diff --exit-code line exits non-zero if the agent touched a protected file. Add src/cases.ts to the list once the case list is final.

Step 5: what the migration looks like

What the agent should produce, given the failures above, is a handful of one-line edits. Run it against a real project and expect something close to this:

// src/schemas.ts (after)
import { z } from "zod";
export const schemas = {
  orderId: z.guid(),
  quantity: z.number().int(),
  unitPrice: z.number(),
  label: z.string().transform((v) => v.length).prefault("tuna"),
  coupon: z.object({ code: z.string().default("NONE").optional() }),
  payload: z.object({ body: z.unknown().optional() }),
  paging: z.object({ page: z.coerce.number() }),
  name: z.object({ name: z.string({ error: (iss) => (iss.input === undefined ? "name is required" : undefined) }) }),
  flags: z.partialRecord(z.enum(["a", "b"]), z.number()),
};

Each edit comes from a changelog entry: z.guid() for the loose UUID pattern, .prefault() for the input-side default, .optional() on the unknown key, the error function (returning undefined hands control to the default message) and z.partialRecord(). The suite now fails four cases, not nine:

     × quantity / integer beyond safe range 6ms
     × unitPrice / infinite price 1ms
     × coupon / default inside optional, key absent 1ms
     × paging / z.coerce.number() key absent 1ms
 Tests  4 failed | 10 passed (14)

Those four are the ones where restoring the old behaviour is either impossible or a bad idea. Above Number.MAX_SAFE_INTEGER neighbouring integers collapse into the same JavaScript number, so a schema that accepted 2 ** 60 was accepting a value that may already have been altered on the way in. An infinite price was never legitimate. The two others are judgement calls, and they’re the reason the process has a human step.

Step 6: accept differences on the record

Accepted differences live in accepted.json, one entry per case, with the new outcome and the reason. A person writes it, or approves the agent’s proposals line by line:

{
  "quantity / integer beyond safe range": {
    "reason": "Unsafe integers lose precision before they reach the schema; rejecting them is the safer contract.",
    "now": { "ok": false, "issues": ["(root): Too big: expected int to be <=9007199254740991"] }
  },
  "unitPrice / infinite price": {
    "reason": "Infinity was never a valid price. Rejecting it is a fix.",
    "now": { "ok": false, "issues": ["(root): Invalid input: expected number, received Infinity"] }
  },
  "coupon / default inside optional, key absent": {
    "reason": "Defaults now apply inside optional keys. Checked: nothing downstream reads an absent code.",
    "now": { "ok": true, "data": { "code": "NONE" } }
  },
  "paging / z.coerce.number() key absent": {
    "reason": "Still a failure on the same key. Only the message text changed; no client matches on it.",
    "now": { "ok": false, "issues": ["page: Invalid input: expected number, received NaN"] }
  }
}

Run the suite again and it passes, 14 of 14. The upgrade pull request now carries a reviewable artefact that no changelog summary gives you: four entries in a JSON file, each with the old behaviour (in baseline.json), the new behaviour and a reason. A reviewer who disagrees with the coupon entry has something concrete to argue with.

The coupon case is the one to read hardest. The change is legitimate, but it alters the shape of the parsed object: where {} came out before, { code: "NONE" } comes out now. A reason like “checked that nothing downstream reads an absent code” is only worth writing if someone searched for it. If a handler distinguishes “no coupon sent” from “default coupon”, this entry is a bug the suite has helpfully labelled.

Prove the gate bites. Change z.guid() back to z.uuid() and run the suite: orderId / variant bits not 10 fails, 13 pass. Put it back and the suite returns to green. A gate you haven’t seen fail is a gate you’re taking on trust.

Make it yours

Different schemas, same method. A few adjustments for other setups:

  • Zod inside a larger framework (tRPC, a form library, an OpenAPI generator). Test the schemas, then add a handful of end-to-end cases through the framework. Those libraries pin their own Zod range, and the baseline can’t see a peer dependency that stays on 3.x.
  • Many schema files. Export them from one barrel file for the test and keep the cases next to the schemas they exercise. The record-and-replay harness doesn’t change.
  • Other libraries. Nothing here is Zod-specific. A date library, an ORM, a serialiser or a markdown renderer has the same shape: a deterministic function that returns data. Alias the old major, record, upgrade, compare. The harder the library is to run on plain inputs (it needs a database, a network), the less the approach fits.
  • CI. Commit baseline.json and run gate.sh on every pull request until the old major is removed. After that, delete zod3, keep the baseline as a regression suite and let it grow.

What goes wrong

The baseline only knows the cases you wrote. A behaviour change on an input you didn’t list is invisible, so a green run proves “no differences on these inputs”, not “no differences”. Production fixtures and the agent’s extra cases widen the net. A mutation-testing run with StrykerJS over the schema file is a decent way to find schemas where no case would notice a change.

The test compares parsed data and issue messages. It says nothing about types. A schema whose inferred type changed (the coerce input type is now unknown) can still behave identically at runtime and fail to compile somewhere else, so keep tsc in the gate beside Vitest.

Messages are part of the baseline. That’s deliberate, since clients sometimes match on them, but it also means every wording change in a new Zod release is a failure to read and accept. If nobody consumes the text, compare issue codes and paths instead and delete the message from outcome.

Pinning matters. The z.unknown() behaviour changed within the 4.x line, so a floating ^4 can move the baseline under you. Pin the exact version while you review, and move the pin deliberately.

Don’t bother if the project validates five fields at one endpoint. Read the changelog, write three tests by hand and move on. The harness pays for itself when a schema layer is wide enough that nobody can hold it in their head.

The first 15 minutes

Install the old major under its alias and the new one beside it, add vitest.config.mts and the test file, and list the ten inputs you’d least like to see change behaviour: one real payload per endpoint, then the edge values from the changelog. Record the baseline with BASELINE=1 npx vitest run, commit it, run the suite on the new major and read the list of failures before the agent touches a line.