Zod 32 🛡️ Migrating from v3 to v4 — Breaking changes and the codemod
Zod v4 is a major release with breaking changes concentrated in three areas: error customization, string format validators, and object schema behavior. The migration is not a version bump; it is a set of code edits that the compiler and the test suite will catch, and a community codemod that automates the mechanical parts. The official migration guide is the reference, and the zod-v3-to-v4 package is the tool that rewrites the common patterns .
This chapter covers the breaking changes that require attention, the codemod that handles the mechanical renames, and the manual steps that remain after the codemod runs. The sections that follow walk through the error API unification, the string format moves, and the object schema changes that are the most likely to break existing code.
Key point: Zod v4 unifies error customization under a single error parameter, moves string formats to top-level functions, and changes object defaults and number validation; the zod-v3-to-v4 codemod handles the mechanical renames, but the error API changes and the stricter UUID validation require manual review.
a. The error customization unification
The largest cluster of breaking changes is the error API. Zod v3 had four separate options for customizing a message: message, invalid_type_error, required_error, and errorMap. Zod v4 replaces all of them with a single error parameter that accepts a string or a function .
// Zod 3
z.string().min(5, { message: "Too short." });
z.string({
required_error: "This field is required",
invalid_type_error: "Not a string",
});
// Zod 4
z.string().min(5, { error: "Too short." });
z.string({
error: (issue) =>
issue.input === undefined
? "This field is required"
: "Not a string",
});
The function form receives the issue context, which includes input and code, so a single schema can return different messages for missing input and wrong type. The message parameter is still supported but deprecated, and invalid_type_error, required_error, and errorMap are removed . A codebase that still uses the old options will not produce the intended messages, and the failure is silent because the schema still parses.
b. String formats and number validation
The string format validators moved from chained methods to top-level functions. z.string().email() becomes z.email(), z.string().uuid() becomes z.uuid(), and z.string().url() becomes z.url() . The method forms still work in v4 but are deprecated and slated for removal.
The z.uuid() function is stricter than its v3 predecessor. It validates the RFC 9562/4122 variant bits, and a string that passed the loose v3 pattern may fail the v4 check. For a more permissive validator, z.guid() accepts UUID-like strings . The z.string().ip() method is split into z.ipv4() and z.ipv6(), and z.string().cidr() into z.cidrv4() and z.cidrv6().
Number validation also changed. z.number() no longer accepts Infinity or -Infinity. z.number().int() accepts only safe integers, rejecting values outside the Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER range. The .safe() method now behaves identically to .int(), which means it no longer accepts floats .
// Zod 3: accepted
z.number().parse(Infinity);
z.number().int().parse(9007199254740992);
// Zod 4: rejects both
c. Object schema and other breaking changes
The object schema methods .strict() and .passthrough() are deprecated in favor of z.strictObject() and z.looseObject(). The .strip() method is removed (it was the default behavior), and .nonstrict() and .deepPartial() are removed entirely .
The default behavior within optional fields also changed. In v3, a default inside an optional field was not applied when the key was present as undefined. In v4, the default is applied even within optional fields, which aligns with expectations but may break code that relies on key existence .
The ZodError formatting methods changed. .format() and .flatten() are deprecated in favor of z.treeifyError() and z.flattenError(). The .formErrors property is removed. The .addIssue() and .addIssues() methods are deprecated in favor of pushing directly to err.issues .
The z.coerce schemas now infer unknown as their input type, and a missing key on an object with a z.coerce field now errors instead of coercing undefined. The .default() behavior changed: it short-circuits when the input is undefined and returns the default, and the default must be assignable to the output type. The old behavior is available as .prefault() .
Complete Example Session
# ============================================
# PART 1: UPGRADE THE DEPENDENCY
# ============================================
npm install --save-exact zod@^4
# ============================================
# PART 2: RUN THE CODEMOD
# ============================================
# Interactive: prompts for tsconfig path
npx zod-v3-to-v4
# Non-interactive: path as argument
npx zod-v3-to-v4 path/to/tsconfig.json
# With -y for CI (auto-confirm prompts)
npx zod-v3-to-v4 path/to/tsconfig.json -y
// ============================================
// PART 3: WHAT THE CODEMOD CHANGES
// ============================================
// .nonstrict() → .passthrough()
// .or() / .and() chains → z.union() / z.intersection()
// .describe() → .meta({ description })
// z.string().email() → z.email()
// Import paths updated
// ============================================
// PART 4: MANUAL STEPS AFTER THE CODEMOD
// ============================================
// 1. Replace message/invalid_type_error/required_error with error
// 2. Replace .strict() / .passthrough() with z.strictObject / z.looseObject
// 3. Replace .flatten() / .format() with z.flattenError / z.treeifyError
// 4. Audit UUID validation (stricter)
// 5. Audit number validation (Infinity, unsafe integers)
// 6. Audit object defaults within optional fields
// 7. Run tsc --noEmit and the test suite
The parts covered the dependency upgrade, the codemod invocation, the automated changes, and the manual review steps.
Quick Reference
Breaking Changes
| v3 | v4 | Action |
|---|---|---|
message / invalid_type_error / required_error | error | Replace manually |
z.string().email() | z.email() | Codemod or manual |
z.string().uuid() | z.uuid() (stricter) | Audit failures |
z.string().ip() | z.ipv4() / z.ipv6() | Split manually |
.strict() / .passthrough() | z.strictObject() / z.looseObject() | Replace manually |
.flatten() / .format() | z.flattenError() / z.treeifyError() | Replace manually |
z.nativeEnum() | z.enum() | Replace manually |
.deepPartial() | Removed | Build manually |
Codemod
| Command | Purpose |
|---|---|
npx zod-v3-to-v4 | Interactive migration |
npx zod-v3-to-v4 tsconfig.json | Non-interactive |
npx zod-v3-to-v4 tsconfig.json -y | CI auto-confirm |
Number Changes
| Value | v3 | v4 |
|---|---|---|
Infinity | Accepted | Rejected |
| Unsafe integer | Accepted | Rejected |
Float with .safe() | Accepted | Rejected |
Best Practices
✅ Do This:
// Use the unified error parameter
z.string({ error: "Required" }) // ✅
// Use top-level string formats
z.email() // ✅
// Use the object constructors
z.strictObject({ ... }) // ✅
// Audit UUID validation after migration
// (stricter in v4) // ✅
❌ Don’t Do This:
// Use removed error options
z.string({ required_error: "Required" }) // ❌
// Rely on .flatten()
error.flatten() // ❌
// Assume UUIDs that passed v3 pass v4
// (variant bits are checked) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Custom messages not appearing | Used message instead of error | Replace with error |
| UUID validation fails | v4 is stricter | Regenerate or use z.guid() |
| Number validation fails | Infinity or unsafe integer | Adjust schema or data |
| Default not applied | v3 behavior expected | v4 applies defaults in optional fields |
| Import path errors | zod/v4 vs zod | Root exports v4 after 4.0.0 |
Real-World Examples
1. Error parameter
z.string({ error: "Required" })
2. Function error
z.email({ error: (iss) => iss.input === undefined ? "Required" : "Invalid" })
3. Top-level email
z.email()
4. Stricter UUID
z.uuid() // RFC 9562/4122 variant bits checked
5. GUID fallback
z.guid() // permissive UUID-like
6. Split IP
z.ipv4() // or z.ipv6()
7. Strict object
z.strictObject({ name: z.string() })
8. Loose object
z.looseObject({ name: z.string() })
9. Treeify errors
z.treeifyError(result.error)
10. Codemod run
npx zod-v3-to-v4 tsconfig.json
Visual
The Error API Migration
┌─────────────────────────────────────────────────────────┐
│ ZOD 3 │
│ message / invalid_type_error / required_error / errorMap│
│ │ │
│ ▼ │
│ ZOD 4 │
│ error: "..." or error: (issue) => "..." │
│ │
│ One parameter, two forms │
└─────────────────────────────────────────────────────────┘
String Format Migration
┌─────────────────────────────────────────────────────────┐
│ ZOD 3 ZOD 4 │
│ z.string().email() z.email() │
│ z.string().uuid() z.uuid() (stricter) │
│ z.string().url() z.url() │
│ z.string().ip() z.ipv4() / z.ipv6() │
│ │
│ Method forms deprecated, top-level canonical │
└─────────────────────────────────────────────────────────┘
Codemod vs Manual
┌─────────────────────────────────────────────────────────┐
│ CODEMOD MANUAL │
│ ┌──────────────────────┐ ┌──────────────────────┐ │
│ │ .nonstrict() │ │ error parameter │ │
│ │ .or() / .and() │ │ UUID strictness │ │
│ │ .describe() │ │ number validation │ │
│ │ string formats │ │ object defaults │ │
│ └──────────────────────┘ └──────────────────────┘ │
│ │
│ Mechanical renames Behavioral decisions │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Error API | error replaces four v3 options |
| String formats | Top-level functions |
| UUID | Stricter, RFC 9562/4122 |
| Object modes | z.strictObject() / z.looseObject() |
| Error formatting | z.treeifyError() / z.flattenError() |
| Codemod | zod-v3-to-v4 |
| Number | No Infinity, safe integers only |
Key takeaways:
- The error API is the largest breaking change. Zod v4 replaces
message,invalid_type_error,required_error, anderrorMapwith a singleerrorparameter that accepts a string or a function. A codebase that still uses the old options will not produce the intended messages . - String formats moved to top-level functions.
z.email(),z.uuid(), andz.url()replace the chained methods, which are deprecated. Thez.uuid()function is stricter, and data that passed v3 may fail v4 . - The codemod handles the mechanical parts.
npx zod-v3-to-v4rewrites the string formats, the union/intersection chains, and the import paths. It does not rewrite the error API or resolve the stricter validation failures . - The manual review is where the work is. Replacing the error options, auditing UUID validation, checking number validation, and verifying the object default behavior are decisions the codemod cannot make .
- Run
tsc --noEmitand the test suite after the migration. The type checker catches the API removals, and the tests catch the behavioral changes that the compiler cannot see.
Remember: The v3-to-v4 migration is two phases. The codemod rewrites the syntax it can recognize, and the manual review handles the error API and the behavioral changes. Start with the dependency upgrade, run the codemod, then work through the error options and the stricter validators. The compiler and the test suite are the feedback loop; the migration guide is the reference. Do not assume a file that compiles is a file that behaves the same.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!