zod
4.6.7 · 12 Oct 2026MIT468.6M / weekRepositoryHomepagenpmAtom feed
4.6.7 is the newest release of 4.x.
Summary· from the note as AI read it
Security fixUpgrade: this release fixes a security issue.
Before you upgrade
- Datetimes without seconds are now rejected; union precisions if needed
- Datetimes without seconds are now rejected; union precisions if needed
- String length checks now count code points; review min/length bounds
- String length checks now count code points; review min/length bounds
- Check record key schemas and intersections; validation semantics changedTo check
- Check record key schemas and intersections; validation semantics changedTo check
- Strict objects now report more issues; check error handling expectationsTo check
- __proto__ keys are now dropped; .strict() reports them as unrecognizedTo check
Security
- Upgrade to fix exponential backtracking (ReDoS) in z.emoji()
- Upgrade to fix exponential backtracking (ReDoS) in z.emoji()
New
z.compile()— the flagship feature of Zod 4.5z.creditCard()— 12–19 digits plus Luhn checksumz.properties()— the multi-property counterpart toz.property()z.deepPartial()/.exactPartial()z.validate(): boolean— a fast-path to verify input validity without a full parse (up to 16x faster on invalid data)
In short
23 breaking2 security50 new14 faster64 fixed42 internal
- Breaking
z.iso.datetime()requires seconds - Breaking
RFC 3339 mandates seconds.
z.iso.datetime()andz.iso.datetime({ offset: true })no longer accept minute-precision input like2020-01-01T06:15Z.local: truestill admits2020-01-01T06:15, since an unqualified datetime is outside RFC 3339 either way. - Breaking
String length counts code points
- Breaking
.min(),.max(), and.length()counted UTF-16 code units, soz.string().max(5)rejected five emoji. They now count Unicode code points, which is what every non-JS consumer of a length bound does (Postgres, MySQL, Go, Python, and themaxLengththatz.toJSONSchema()emits)..max()only loosens;.min()and.length()tighten for astral input. Graphemes are unchanged — a ZWJ sequence is still several code points. - BreakingTo check
Record keys and intersections match TypeScript
- BreakingTo check
A record's key schema now governs only the keys that match it, the way TypeScript treats an index signature. Intersecting an object with a pattern-keyed record no longer rejects the object's own keys.
- BreakingTo check
Separately, an
unrecognized_keysissue no longer aborts the schema it came from, so a strict object with an extra key and a bad value now reports both issues instead of just the first. - BreakingTo check
__proto__is always stripped
Security
1 advisory affects 4.5.0; 4.6.6 fixes them
- HighZod can exhaust memory while validating oversized constrained collectionsGHSA-mrhx-c7xc-m3w5 · 1 Oct 2026Fixed in 4.6.6
Release note
Zod 4.5 is now available.
npm install zod@latest
At a glance:
z.compile()— the flagship feature of Zod 4.5z.creditCard()— 12–19 digits plus Luhn checksumz.properties()— the multi-property counterpart toz.property()z.deepPartial()/.exactPartial()z.validate(): boolean— a fast-path to verify input validity without a full parse (up to 16x faster on invalid data)New locales: Bengali (
bn), Central Kurdish (ckb), Hindi (hi), Kannada (kn), Norwegian Nynorsk (nn), Brazilian Portuguese (pt-BR), Slovak (sk), Turkmen (tk)
z.compile()
You can now pre-compile any Zod schema using z.compile(schema). This dramatically speeds up parsing performance.
import * as z from "zod";
const Player = z.object({
username: z.string(),
bio: z.string(),
xp: z.number(),
// ...20 more properties...
});
const CompiledPlayer = z.compile(Player);A compiled schema can be used exactly like an uncompiled one. There are no special rules around compiled schemas. They're just faster.
Player.parse({ ... });
CompiledPlayer.parse({ ... }); // ~9x fasterOn objects, arrays, and unions, this speeds up parsing by a factor of ~3–9. More complex schemas stand to benefit more than simpler ones.
Time per parse by schema type, standard parser vs compiled — lower is better (benchmark)
Below are the Moltar benchmark results comparing Zod (compiled and uncompiled) against the Moltar ParseSafe bench.
Throughput on the moltar benchmark fixture (parseSafe: returns a new object with unknown keys stripped) — higher is better (benchmark)
And the equivalent results for the Moltar AssertLoose bench. Tested against the new z.validate(schema, input) function (detailed later in the post).
Throughput on the moltar benchmark fixture (assertLoose: returns a boolean, unknown keys allowed) — higher is better (benchmark)
Zod's entire test suite runs twice—once normally and again with auto-compilation enabled globally—to ensure perfect fidelity.
How it works
Under the hood, z.compile() walks the entire schema once and produces a hyperoptimized snippet of flat, loop-free JavaScript that can validate inputs far faster than a standard runtime validator. This snippet can be executed via new Function() (effectively a more powerful eval) to serve as a fast-path validator. Schemas use this to "fast check" validity, falling back to the regular runtime logic on validation failure to provide granular error information.
Take this simple Point schema:
const Point = z.object({
x: z.number(),
y: z.number()
});Here is the generated snippet for it:
const isPoint = new Function("input", `
if (typeof input !== "object" || input === null) return false;
if (typeof input.x !== "number") return false;
if (typeof input.y !== "number") return false;
return true;
`);
isPoint({ x: 1, y: 2 }); // true
isPoint({ x: "1" }); // falseFor the large majority of inputs, the generated function validates the data with the fastest logic JavaScript can express: straight-line typeof checks and property reads, with no interpreter in between. When it can't handle an input, Zod falls back to the standard parser.
This is the function Zod generates for the Player schema above:
if (typeof input !== "object" || input === null || Array.isArray(input)) return INVALID;
const v0 = input["username"];
if (typeof v0 !== "string") return INVALID;
const v1 = input["bio"];
if (typeof v1 !== "string") return INVALID;
const v2 = input["xp"];
if (typeof v2 !== "number" || !Number.isFinite(v2)) return INVALID;
const v3 = { "username": v0, "bio": v1, "xp": v2 };
return v3;Armed with the power of new Function(), this happens in-process at runtime. There is no need to integrate with your build system.
The compiled schema is purely additive on top of the existing schema. It tacks on the pre-compiled fast path for checking valid inputs. When invalid data is detected, it returns the
INVALIDsymbol to signal that parsing should fall back to the uncompiled parser. This structurally prevents subtle deviations in error reporting between compiled and uncompiled variants.
import "zod/compile"
To compile every schema in an application, import zod/compile once at the top of your entry point. Every schema constructed after that import is automatically compiled the first time it's used to parse data.
import "zod/compile"; // must come before modules that define schemas
import * as z from "zod";
const schema = z.object({ name: z.string() });
schema.parse({ name: "ok" }); // compiled on first parseIt also works as a Node.js CLI flag, which guarantees it runs before any module defines a schema:
node --import zod/compile app.js
Or set preload in bunfig.toml or nub.jsonc.
{
"preload": ["zod/compile"]
}All schemas benefit to varying degrees, though complex object/tuple/array schemas benefit more than simple scalar validators.
Read the docs, or the full technical writeup: Introducing
z.compile()
z.creditCard()
A new string format: 12–19 digits, optionally separated by single spaces or hyphens, with a valid Luhn checksum.
z.creditCard().parse("4111 1111 1111 1111"); // ✅
z.creditCard().parse("4111 1111 1111 1112"); // ❌ bad checksumz.properties()
The multi-property counterpart to z.property().
const httpsUrl = z.instanceof(URL).check(
...z.properties({
protocol: z.literal("https:" as string),
hostname: z.string().regex(z.regexes.domain),
})
);
httpsUrl.parse(new URL("https://example.com")); // ✅
httpsUrl.parse(new URL("http://localhost")); // ❌ protocolz.deepPartial()
Back in functional form after being removed as a method in Zod 4.
const Post = z.object({
title: z.string(),
author: z.object({ name: z.string(), email: z.string() }),
});
const PartialPost = z.deepPartial(Post);
type PartialPost = z.output<typeof PartialPost>;
// => { title?: string; author?: { name?: string; email?: string } }
PartialPost.parse({ author: {} }); // ✅The result is still a ZodObject, so .shape and .extend() keep working.
.exactPartial()
Like .partial(), but wraps each field in z.exactOptional() instead of z.optional(): keys may be omitted, but an explicit undefined is rejected. This matches TypeScript's Partial<> under exactOptionalPropertyTypes.
const Recipe = z.object({ title: z.string(), servings: z.number() });
const PartialRecipe = Recipe.exactPartial();
PartialRecipe.parse({}); // ✅
PartialRecipe.parse({ title: undefined }); // ❌In Zod Mini it's a top-level function: z.exactPartial(Recipe).
z.validate()
Standalone boolean validation, in Zod, Zod Mini, and Zod Core. It answers "is this input valid?" without constructing a ZodError, which makes rejection cheap: on invalid input it is up to 16x faster than .safeParse().success. The return type is a guard on the schema's input type, and z.validateAsync() covers schemas with async refinements.
z.validate(z.string(), "hi"); // true z.validate(z.string(), 42); // false
z.input() / z.output()
Project a schema onto its input or output side. Useful for validating the two halves of a codec independently.
const isoDate = z.codec(z.iso.datetime(), z.date(), {
decode: (s) => new Date(s),
encode: (d) => d.toISOString(),
});
const Event = z.object({ name: z.string(), at: isoDate });
z.input(Event).parse({ name: "launch", at: "2024-01-01T00:00:00Z" }); // ✅
z.output(Event).parse({ name: "launch", at: new Date() }); // ✅This is a no-op on schemas not containing codecs/pipes.
z.toZod<T>()
A utility to define a Zod schema that agrees exactly with a static type, often one that is handwritten or externally defined.
type Player = { username: string; xp: number };
const Player = z.toZod<Player>()(
z.object({
username: z.string(),
xp: z.number(),
})
);
Player.shape.username; // ZodString — the schema is returned unchangedz.getDiscriminatedOption()
Extract a discriminated union member by discriminator value.
const Fruit = z.object({ type: z.literal("fruit"), seeds: z.boolean() });
const Veg = z.object({ type: z.literal("vegetable"), leafy: z.boolean() });
const Produce = z.discriminatedUnion("type", [Fruit, Veg]);
z.getDiscriminatedOption(Produce, "fruit"); // typeof Fruit
z.getDiscriminatedOption(Produce, "meat"); // ❌ TypeScript errorCyclical inputs
Zod recursive schemas now support cyclical data. For bundle size reasons, Zod Mini requires you to register a memoizer explicitly. (#6387, #6482)
Zod
const Category = z.object({
name: z.string(),
get subcategories() {
return z.array(Category);
},
});
const input: any = { name: "root", subcategories: [] };
input.subcategories.push(input);
const result = Category.parse(input);
result.subcategories[0] === result; // trueZod Mini
// register a memoizer before defining any schemas
z.config({ memoizer: z.memoizer() });
const result = Category.parse(input);
result.subcategories[0] === result; // true9x reduction in schema memory footprint
In Zod 4.4 a bare z.string() retained 7.5kb of heap. In Zod 4.5 it retains 784 bytes.
Retained heap per schema instance, Zod 4.4.3 vs 4.5 (benchmark)
In Zod 4.4 and earlier, all schema methods were automatically bound to the instance itself. This allowed users to pluck methods from schemas without causing issues due to this-binding.
const { parse } = z.string();
parse("some data");A consequence of this is that each bound method allocates space on the heap; method implementations are not shared across all instances via prototype, as you'd expect. Zod 4.5 implements a method memoization pattern that avoids allocating bound methods until they are actually accessed.
Read the deep dive: Reducing Zod's memory footprint by an order of magnitude
Faster failures
Zod .parse()/.safeParse() instantiates a JavaScript Error, which captures a stack trace. In the case of validation failures, this is often much slower than the parsing logic itself. When using .safeParse(), Zod no longer captures this stack trace, speeding up failure-path parses by a factor of ~7.5x. (#6316, #6450)
const result = Player.safeParse({ username: 42, bio: "hello", xp: 12 });
result.success; // false — ~7.5x faster than Zod 4.4Player schema (benchmark)
Symbol keys in z.object()
A shape can now declare a symbol key. TypeScript tracks it: a const symbol infers as unique symbol, so z.infer makes the key required and checks its value type. Undeclared symbol keys are still ignored.
const TAG = Symbol("tag");
const schema = z.object({ name: z.string(), [TAG]: z.number() });
schema.parse({ name: "alice", [TAG]: 42 }); // ✅ { name: "alice", [TAG]: 42 }
schema.safeParse({ name: "alice" }); // ❌ the symbol key is requiredBug fixes
All of these fix soundness issues, so a schema that relied on the old behavior may now reject input it used to accept.
z.iso.datetime() requires seconds
RFC 3339 mandates seconds. z.iso.datetime() and z.iso.datetime({ offset: true }) no longer accept minute-precision input like 2020-01-01T06:15Z. local: true still admits 2020-01-01T06:15, since an unqualified datetime is outside RFC 3339 either way.
z.iso.datetime().parse("2020-01-01T06:15:00Z"); // ✅
z.iso.datetime().parse("2020-01-01T06:15Z"); // ❌ was accepted in 4.4To accept both forms, union the two precisions:
z.union([z.iso.datetime(), z.iso.datetime({ precision: -1 })]);String length counts code points
.min(), .max(), and .length() counted UTF-16 code units, so z.string().max(5) rejected five emoji. They now count Unicode code points, which is what every non-JS consumer of a length bound does (Postgres, MySQL, Go, Python, and the maxLength that z.toJSONSchema() emits). .max() only loosens; .min() and .length() tighten for astral input. Graphemes are unchanged — a ZWJ sequence is still several code points.
z.string().max(5).parse("😀😀😀😀😀"); // was too_big, now passes
z.string().min(5).parse("😀😀😀"); // was fine, now too_smallCloses #3355.
Record keys and intersections match TypeScript
A record's key schema now governs only the keys that match it, the way TypeScript treats an index signature. Intersecting an object with a pattern-keyed record no longer rejects the object's own keys.
z.object({ name: z.string() })
.and(z.record(z.string().regex(/^S_/), z.string()))
.parse({ name: "a", S_a: "s" });
// 4.4: throws invalid_key on "name"
// 4.5: { name: "a", S_a: "s" }Separately, an unrecognized_keys issue no longer aborts the schema it came from, so a strict object with an extra key and a bad value now reports both issues instead of just the first. Closes #2200, #2573, #4017, #5663.
__proto__ is always stripped
Object and record parsers now drop a __proto__ key whether it comes from the input, is declared by the schema, or is produced by a record key transform. A key that a record's key schema normalizes to __proto__ is dropped too. .strict() reports an own __proto__ input key as unrecognized_keys instead of silently swallowing it. Error formatters and both JSON Schema converters use own-property writes so a toString or constructor path segment can't walk onto Object.prototype (#6213, #6367, #6346). (#6386, #6354, #6355, #6221)
Stricter string formats
z.ipv6()validated by handing the string tonew URL(), which let::@1\and::1\nthrough. It now checks the address alphabet directly (#6442).z.ulid()restricts the first character to0–7; anything higher overflows the 48-bit timestamp. A fixture that doesn't start with a real timestamp, such as one with a leading letter, is now rejected (#6095).z.httpUrl()enforces the RFC 1035 length limits on the host, matchingz.hostname()(#6035).z.emoji()no longer backtracks exponentially on a failed match (#6347).z.string().includes(sub, { position: N })emits a JSON Schema pattern that allows at least N leading characters, matchingString.prototype.includes(#6024).
Commits
Zod 4.5 rolls up 155 commits. Thanks to everyone who contributed: @dokson, @deepshekhardas, @zirkelc, @francisjohnjohnston-web, @MerlijnW70, @codinsonn, @oimo23, @JSap0914, @zelinewang, @abhishek-chaudhary2003, @spokodev, @Mohammad-Faiz-Cloud-Engineer, @hamed-bavar, @MGPOCKY, @ChiChuRita, @dinwwwh, @thristhart, @tsmartin9, @vedanshshetti, @belicam, @frastefanini, @andersk, @musaddiq-rafi, @tachmyratsaparmyradov, @arvindfroi, @KUMachine, @spidersouris, @catdalfonso, @mneetika, @gwagjiug, @MahinAnowar, @MaksZhukov, @emmayusufu, @agcty, @devareddy05, @Vish05, @yamcodes, @mattiasahlsen, @samchungy, @ozzyfromspace, @udohjeremiah, @patrickwehbe, @gajus, @Harm-Nullix, @thwbh, @IdanGonen, @irfanfandi, @JuerGenie, @marcalexiei, @itsahmedbilal, @DucMinhNe, @meliharik.
v4: Validate without building the output, and keep schemas out of dictionary mode
v4: Make z.compile() fall back instead of throwing
v4: Add z.isValid and z.isValidAsync
v4: Close the fastpass bindings into the compiled parser
v4: Stop emitting a multipleOf that JSON Schema rejects
v4: Make a tuple's items optional with .partial()
v4: Don't throw from safeParse on bigint multipleOf(0n)
v4: Let z.nanoid() take a custom length
v4: Restrict the first ULID character to [0-7]
v4: Run a wrapper's inner schema on its own payload
v4: Fold an intersection of object schemas into one object
v4: Build the catch context from the input that failed
- Breaking
v4: Distinguish number and bigint formats at the type level
v4: Keep a wrapper's stored value only on the side it belongs to
v4: Empty enums and literals match nothing
v4: Expose the function schema on .implement() results
v4: Make record input keys optional when the value can fill them
v4: Resolve z.input past a preprocess transform
v4: Accept exact decimal multiples in multipleOf
v4: Carry a pipe's own checks through z.output
v4: Let the includes(position) pattern match at or after the offset
v4: Expose stringbool truthy/falsy/case via _zod.bag
- Breaking
v4: Require seconds once a datetime carries a Z or an offset
v4: Skip the eager stack capture when building a ZodError
v4: Support declared symbol keys in z.object()
v4: Correct the date/time format keywords in both JSON Schema directions
Add z.toZod helper
v4: Stop catch resurrecting issues an optional already resolved
v4: Prefix issue paths in place in the object JIT failure path
v4: Keep a memoized node's cached issues private to the cache
resolution: Keep pnpm's own warnings out of the attw snapshot
v4: Validate the address, and return the string that was validated
Preserve callsites in parse stack traces
Compact simple anyOf unions to type array in toJSONSchema
v4: Measure string length in Unicode code points
Add properties checks for instanceof schemas
v4: An absent key on the middle rung supplies nothing
v4: Add z.getDiscriminatedOption
v4: Allow passing extra args to apply()
v4: Drop empty alternation branch from datetime pattern
v4: Infer recursive getter options in discriminatedUnion
Add shorn to Zod Utilities
v4: Stop islanding a catch callback, which diverged silently
core: Drop the exactOptional parse prototype from #6432
core: An omittable discriminator claims undefined
core: Drop the seal and the per-key WeakSet from the lazy internals
json-schema: Emit a root $ref when the root schema has an id
v4: Z.compile — ahead-of-time schema compilation
v4: Let a schema's error map cover its own checks' issues
core: Restore defineLazy semantics lost in the internals move
locales: da/nn/no/sv called an IP address a range
locales: Backfill the mac and Sizable.map gaps, and pin dictionary parity
memory: Install derived internals on a per-constructor prototype
locales: Add the credit_card key to the seven locales missing it
from-json-schema: Drop redundant inclusive bound for draft-04 exclusive ranges
v4: Refine optin into a three-rung ladder, retire the fallback payload flag
Improve Portuguese localization and add Brazilian Portuguese (pt-BR)
locales: Improve french translation
locales: Add Hindi and Kannada locale support
Locales: Added Slovak (sk) language
Preserve explicit superRefine issue input
Add .exactPartial() to ZodObject
lang: Added Bengali locale
locales: Add turkmen (tk) locale
locales: Add Norwegian Nynorsk (nn) locale
Add Central Kurdish (ckb) locale
fr: Remove hyphen in "non-optionnel"
v4: Expose the owning schema on check-originated issues
json-schema: Resolve tuple minItems past transform and catch in input mode
json-schema: Route unrepresentable default values through
unrepresentablev4: Support format: "hostname" in fromJSONSchema
v4: Parse input containing reference cycles
json-schema: Keep preprocess object properties required in input mode
v4: Strip output-typed catch values from the input JSON Schema
v4: Add z.deepPartial and runtime z.input / z.output
v4: Align record keys and intersection strictness with TypeScript
Honor loose mode for closed record key schemas
v4: Stop the object JIT fastpass keeping a swallowed issue's value
json-schema: Make toJSONSchema(registry) linear in registry size
v4: Make fromJSONSchema propertyNames compose with the other object keywords
mini: Make merge() take an object schema, matching classic
v4: Use exact flag in English locale too_small/too_big messages
json-schema: Unescape JSON Pointer tokens when resolving $ref
v4: Give z.xor() a distinct error when multiple options match
v4: Make fromJSONSchema tuples open-ended by default
v4: Make prefixItems/draft-7 items respect minItems in fromJSONSchema
v4: Let bundlers tree-shake locales out of the default import
toJSONSchema: Constrain closed tuple length
v4: Escape non-string enum values in template literal patterns
- Deprecated
Surface @deprecated on re-exported compat aliases
v4: Report date origin for numeric min/max bounds
Escape JSON Pointer reserved characters in toJSONSchema $ref (closes #6027)
v4: Enforce RFC 1035 length limits in regexes.domain
v4: Respect additionalProperties:false with patternProperties in fromJSONSchema
v4: Clarify infinite number errors
json-schema: Accept RFC 3339 numeric offsets in date-time format
v4: Add z.creditCard() string format
json-schema: Accept a function for
unrepresentablev4: Preserve z.preprocess input narrowing
v4: Cut per-schema memory ~90% by moving methods to the prototype
json-schema: Run
overridebefore the unrepresentable errorv4: Preserve default English locale across tree-shaken bundles
Shill oxlint
Consistently strip proto from parsed objects
v4: Lazy ZodError construction
docs-v3: Serve the docsify SPA fallback on Vercel
v4: Complete reserved-key hardening
v4: Let three dead declarations tree-shake under esbuild
v4: formatError and treeifyError handle inherited-name path elements
v4: Report own proto key under .strict()
v4: re-check the record key after the key schema runs
v4: Write a declared proto key as an own property
Remove exponential backtracking from the emoji regex
json-schema: Keep proto keys as own properties in schema conversion
errors: Use own-property semantics in every error-tree walker
docs-v3: Rename README.md to home.md so Vercel serves it
v4: cidrv6 JSON schema pattern matches runtime
v4: Break circular import between classic schemas and iso
v4: Allow dynamic
.catch()underunrepresentable: "any"
A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.