Zod

Knowledge base from the Zod (TypeScript-first schema validation) documentation, covering Zod 4 core API, Zod Mini, Zod Core internals, JSON Schema conversion, codecs, error customization, and the Zod 3→4 migration guide. Use when defining or refining Zod schemas, choosing between Zod and Zod Mini, converting schemas to/from JSON Schema, customizing validation errors, building bidirectional codecs, or migrating a Zod 3 codebase to Zod 4.

61 capítulos

Zod

Package: zod (v4) | Chapters: 61 | Generated: 2026-08-24

How to Use This Skill

  • Without arguments — load the Core Patterns below for a working mental model of the schema API.
  • With a topic or API name — ask about discriminated unions, codecs, z.record, JSON Schema, or another indexed topic; I find and read the relevant chapter.
  • With a chapter number — ask for ch025; I load that specific chapter.
  • Browse — ask "what chapters do you have?" to see the full index below.

When you ask about something not covered in Core Patterns, I will read the relevant chapter file before answering.


Core Patterns & Conventions

Zod maps schemas one-to-one to TypeScript types: define a schema, derive its type with z.infer<typeof schema>, and validate untrusted input with .parse()/.safeParse(). The API is immutable — every modifier method (.optional(), .min(), .refine(), ...) returns a new schema instance rather than mutating the original.

Absence has four flavors: .optional() (allows undefined), .nullable() (allows null), .nullish() (both), .exactOptional() (key may be absent, but not explicitly undefined — matches exactOptionalPropertyTypes). Fallback values have three flavors too: .default(value) short-circuits on undefined input (value must match the output type), .prefault(value) substitutes on undefined but still runs the full pipeline (value must match the input type), and .catch(value) recovers from any validation failure, not just missing input.

Objects strip unknown keys by default. Use z.strictObject() to reject them, z.looseObject() to pass them through, or .catchall(schema) to validate them. Prefer object spread ({ ...A.shape, ...B.shape }) over chained .extend() when merging schemas — it's faster to type-check and behaves identically in Zod and Zod Mini. .safeExtend() is the refinement-safe version of .extend() (plain .extend() throws on schemas with .refine()).

Unions: z.union([...]) checks options in order and returns the first match. z.discriminatedUnion(key, [...]) is strictly better whenever every option is an object sharing one literal-valued key — faster and gives better errors. z.xor([...]) requires exactly one match (watch for accidental overlap between loosely-typed object options — use .strict() on the narrower one).

Transforms vs. codecs: .transform(fn)/z.transform(fn) is a one-way reshape — it makes .encode() throw anywhere it appears in a schema. z.codec(inputSchema, outputSchema, { decode, encode }) is the bidirectional alternative — use it whenever a value needs to go both directions (e.g. ISO string ↔ Date at a network boundary). Inside a transform/codec, report failure via ctx.issues.push(...) + return z.NEVER, never throw.

Refinements (.refine()) add pass/fail validation without ever changing the inferred type. They're continuable by default (all failing refinements collect into .issues); pass abort: true to stop at the first failure, and path: [...] to attach a cross-field error to a specific key (e.g. a "confirm password" mismatch).

Error customization is a five-level precedence chain, highest to lowest: check-level → schema-level ({ error: "..." } or a function) → per-parse (.parse(x, { error })) → global (z.config({ customError })) → locale (z.config(en())). Error-map functions receive the full issue (code, input, path, schema for reading .meta()) and can return undefined to defer to the next layer.

Metadata lives in registries. .meta({...}) is shorthand for registering in z.globalRegistry; metadata is tied to the exact schema instance (derived schemas from .refine()/.extend() don't inherit it) and flows directly into z.toJSONSchema() output, where it can override generated keywords.

Two packages, one core. zod (method-chained, most ergonomic, default choice) and zod/mini (function-based, tree-shakable, ~60-70% smaller bundles) both implement zod/v4/core. Library code that must support both should depend only on "zod/v4/core" types — never "zod/v4" or "zod/v4/mini" directly.

Coming from Zod 3? The biggest behavior changes: .default() now short-circuits instead of re-parsing (use the new .prefault() for old behavior), defaults now apply inside optional object fields, z.record() requires two arguments and is exhaustive by default on enum keys (z.partialRecord() for the old partial behavior), and string formats moved to top-level functions (z.email() instead of z.string().email()).


Chapter Index

Introduction & Basic Usage

#TitleKey Concepts
ch001Introduction & Installationschema-first validation, immutable API, tsconfig strict
ch034Basic Usage — Define, Parse, Handle Errors, Infer.parse, .safeParse, z.infer, z.input/z.output
ch035Matching an Existing Typez.toZod<T>(), exact type equality

Defining Schemas — Primitives & Formats

#TitleKey Concepts
ch002Primitives & Coercionz.string/number/boolean, z.coerce.*
ch003Literalsz.literal, multi-value literals
ch004Strings — Validation & Transforms.min/.max/.regex, .trim/.toLowerCase
ch005String Formats — Identifiers, URLs & Contact Infoz.email, z.uuid, z.url, z.e164, z.jwt
ch006String Formats — ISO Dates, Network & Hashesz.iso.datetime, z.ipv4, z.hash, z.stringFormat
ch007Template Literalsz.templateLiteral
ch008Numbersz.number, .gt/.lt/.multipleOf, z.nan
ch009Integers, BigInts & Booleansz.int, z.int32, z.bigint, z.boolean
ch010Datesz.date, .min/.max
ch011Enumsz.enum, .exclude/.extract
ch012Stringboolsz.stringbool

Defining Schemas — Modifiers & Composition

#TitleKey Concepts
ch013Optional, Exact Optional, Nullable & Nullish.optional, .exactOptional, .nullable, .nullish
ch014Unknown, Any & Neverz.any, z.unknown, z.never
ch015Objects — Definition, Strictness & Shapez.object, z.strictObject, .catchall, .keyof
ch016Objects — Extending & Deriving.extend, .safeExtend, .pick/.omit, .partial
ch017Recursive Objectsgetter-based recursion, mutual recursion
ch018Arrays & Tuplesz.array, z.tuple, variadic rest
ch019Unions & Exclusive Unions (XOR)z.union, z.xor
ch020Discriminated Unions & Intersectionsz.discriminatedUnion, z.intersection
ch021Recordsz.record, z.partialRecord, z.looseRecord
ch022Maps & Setsz.map, z.set
ch023Filesz.file, .mime
ch024Instanceofz.instanceof, z.property
ch031JSONz.json, recursive union
ch032Functionsz.function, .implement
ch033Custom & Applyz.custom, .apply

Defining Schemas — Refinement, Transformation & Fallbacks

#TitleKey Concepts
ch025Refinements.refine, abort, path
ch026Codecs — Basicsz.codec, decode/encode
ch027Pipes.pipe, z.input/z.output
ch028Transforms & Preprocessz.transform, z.preprocess, ctx.issues
ch029Defaults, Prefaults & Catch.default, .prefault, .catch
ch030Branded Types & Readonly.brand, .readonly

Codecs Deep Dive

#TitleKey Concepts
ch036Codecs — Encode/Decode Mechanicsz.invertCodec, type-safe inputs, async/safe variants
ch037How Encoding Interacts With Other Schema Featuresrefinements, defaults, catch, stringbool, transforms
ch038Useful Codecs ReferencestringToNumber, isoDatetimeToDate, jsonCodec, base64/hex↔bytes

Performance

#TitleKey Concepts
ch039AOT Compilationz.compile, import "zod/compile"

Ecosystem

#TitleKey Concepts
ch040Ecosystem & Community ResourcestRPC, React Hook Form, zshy

Error Handling

#TitleKey Concepts
ch041The error Param & Schema-Level Customizationerror param, error map, iss.schema
ch042Global Error Customization, Internationalization & Precedencez.config, locales, precedence chain
ch043Per-Parse Error Customization.parse options, reportInput
ch044Formatting Errorsz.treeifyError, z.prettifyError, z.flattenError

JSON Schema

#TitleKey Concepts
ch045JSON Schema — Conversion Functionsz.toJSONSchema, z.fromJSONSchema, unrepresentable
ch046JSON Schema — Type-by-Type Conversion Detailsformat, pattern, additionalProperties
ch047JSON Schema — Registries & Multi-Schema Outputz.globalRegistry, $ref

For Library Authors & Internals

#TitleKey Concepts
ch048For Library Authors — Peer Dependencies & SubpathsStandard Schema, zod/v4/core
ch049For Library Authors — Accepting User-Defined Schemasgeneric constraints, z4.parse
ch050Metadata & Registriesz.registry, .register, .meta, .describe
ch051Zod Core — Schema Classes & Internals$ZodType, _zod.def
ch052Zod Core — Checks, Errors & Issues$ZodCheck, $ZodError, $ZodIssue
ch053Zod Mini — Overview & When to Use Ittree-shaking, bundle size
ch054Zod Mini — API Reference.check(), check function catalog
ch055The Zod Package — Method OverviewZodType methods

Migration Guide (Zod 3 → 4)

#TitleKey Concepts
ch056Migration — Number, String, Coercion & Defaults.prefault, coercion input type
ch057Migration — Objects, Enums, Arrays, Functions & Refinedefaults in optional fields, z.function factory
ch058Migration — Refine, Record & Intersection Changesctx.path removal, z.record arity
ch059Migration — Internal & Architectural Changesgenerics, _zod.def, ZodEffects removal

Release Notes & Versioning

#TitleKey Concepts
ch060Zod 4 Release Notes — Performance & Rationalebenchmarks, tsc instantiations, bundle size
ch061Versioning Policysubpath versioning, peer dependencies

Topic Index

  • AOT compilation → ch039
  • Branding → ch030
  • Codecs → ch026, ch036, ch037, ch038
  • Coercion → ch002, ch056
  • Discriminated unions → ch020
  • Enums → ch011, ch021 (record keys), ch057 (nativeEnum migration)
  • Error customization → ch041, ch042, ch043
  • Error formatting → ch044
  • JSON Schema → ch045, ch046, ch047
  • Library authoring → ch048, ch049
  • Metadata / registries → ch050
  • Migration (Zod 3→4) → ch056, ch057, ch058, ch059
  • Objects → ch015, ch016, ch017, ch057
  • Pipes / transforms → ch027, ch028
  • Records → ch021, ch058
  • Recursive schemas → ch017, ch031, ch047
  • Refinements / checks → ch025, ch052
  • String formats → ch005, ch006, ch046, ch056
  • Unions → ch019, ch020
  • Zod Core internals → ch051, ch052
  • Zod Mini → ch053, ch054

Supporting Files

Scope & Limits

This skill covers the Zod v4 documentation (zod.dev/llms-full.txt, fetched 2026-08-23) — the schema API, Zod Mini, Zod Core internals, JSON Schema conversion, codecs, error customization, and the Zod 3→4 migration guide. It does not cover Zod 3-specific APIs beyond what's documented in the migration guide, nor third-party ecosystem library internals (tRPC, React Hook Form, etc.) beyond what's mentioned in the Ecosystem chapter. For implementation details specific to your codebase, combine with project-specific tools.