💎 Zod 4.5 is out!  Read the announcement.

Zod 4.5

Colin McDonnell··14 min read

Zod 4.5 is now available.

npm install zod@latest

At a glance:

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()
});
 
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({ ... }); // ~2x faster

On objects, arrays, and unions, this speeds up parsing by a factor of ~3–7. More complex schemas stand to benefit more than simpler ones.

Time per parse on a shared nanosecond axis, standard parser as a gray bar with the compiled time as a blue bar inside it: an array of 10 objects 377 ns to 68 ns (5.5x), a 20-key object 301 ns to 38 ns (7.8x), an array of 10 strings 241 ns to 33 ns (7.3x), a union of 3 objects 190 ns to 36 ns (5.3x), a 3-element tuple 119 ns to 33 ns (3.6x), a 5-key strict object 117 ns to 32 ns (3.7x), a discriminated union 92 ns to 27 ns (3.4x), a 5-key object 76 ns to 28 ns (2.8x); up to 7.8x faster when compiled
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.

Bar chart of operations per second on the moltar benchmark fixture, parseSafe category: Zod 4 compiled 47.5M, typia 45.3M, Zod 4 11.6M, valibot 1.8M, effect 1.7M, Zod 3 1.2M, arktype 152k, yup 121k
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).

Bar chart of operations per second on the moltar benchmark fixture, assertLoose category: typia 74.9M, arktype 66.2M, Zod 4 compiled 60.6M, Zod 4 6.5M, valibot 1.9M, effect 1.7M, Zod 3 1.2M, yup 124k
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.

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 parse

It 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.

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. (#5931)

z.creditCard().parse("4111 1111 1111 1111"); // ✅
z.creditCard().parse("4111 1111 1111 1112"); // ❌ bad checksum

z.properties()

The multi-property counterpart to z.property(). (#5912)

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")); // ❌ protocol

z.deepPartial()

Back in functional form after being removed as a method in Zod 4. (#5928)

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. (#6065)

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. (#6471)

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. (#5928)

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. (#5913)

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 unchanged

z.getDiscriminatedOption()

Extract a discriminated union member by discriminator value. (#5947)

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 error

Cyclical inputs

Zod recursive schemas now support cyclical data. For bundle size reasons, Zod Mini requires you to register a memoizer explicitly. (#6387, #6482)

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; // true
// register a memoizer before defining any schemas
z.config({ memoizer: z.memoizer() });
 
const result = Category.parse(input);
result.subcategories[0] === result; // true

9x 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.

Bar chart of heap retained by one schema instance, zod 4.4.3 versus 4.5: a 10-key object 82.0kb to 11.0kb, a union 17.5kb to 2.13kb, z.string().min(1) 16.7kb to 3.37kb, a record 16.4kb to 2.64kb, z.string().optional() 12.6kb to 1.50kb, an array of strings 11.2kb to 1.93kb, z.string() 7.53kb to 784b, z.number() 4.44kb to 706b. Up to 9.8x smaller than 4.4.3.
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.

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.4
Bar chart of time per failing safeParse: zod 4.4 at 6.3 microseconds, zod 4.5 at 840 nanoseconds — 7.6x faster
Player 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. (#6448)

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 required

Bug 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. (#6457)

z.iso.datetime().parse("2020-01-01T06:15:00Z"); // ✅
z.iso.datetime().parse("2020-01-01T06:15Z");    // ❌ was accepted in 4.4

To 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. (#6441)

z.string().max(5).parse("😀😀😀😀😀"); // was too_big, now passes
z.string().min(5).parse("😀😀😀");     // was fine, now too_small

Closes #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. (#6412)

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 to new URL(), which let ::@1\ and ::1\n through. It now checks the address alphabet directly (#6442).
  • z.ulid() restricts the first character to 07; 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, matching z.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, matching String.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.