github colinhacks/zod v4.5.0

latest release: v4.5.1
5 hours ago

Zod 4.5 is now available.

npm install zod@latest

At a glance:

  • z.compile() — the flagship feature of Zod 4.5
  • z.creditCard() — 12–19 digits plus Luhn checksum
  • z.properties() — the multi-property counterpart to z.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)
  • 9x reduction in memory footprint
  • 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()
});

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 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" });     // false

For 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 INVALID symbol 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 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.

{
  "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)

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; // true

Zod Mini

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

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

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.

Don't miss a new zod release

NewReleases is sending notifications on new releases.