💎 Zod 4.5 is out!  Read the announcement.

Introducing z.compile()

Colin McDonnell··3 min read

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.

This can lead to dramatic speedups, especially for container types like objects, arrays, unions, and tuples.

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 like CompiledPlayer is a Zod schema like any other. There are no special rules around compiled schemas.

  • Same methods: .parse(), .safeParse(), .extend(), .optional(), etc.
  • Same inferred input and output types
  • Same issues and error messages

Use it exactly like Player:

Player.parse({ ... });
CompiledPlayer.parse({ ... }); // ~2x faster

Zod's entire test suite runs twice—once normally and again with auto-compilation enabled globally—to ensure perfect fidelity.

How it works

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.

On invalid input the fallback runs the uncompiled schema, so the error is the uncompiled schema's error.

Compile all the things!

If you import "zod/compile" in the entry point of your application, Zod enables compile-by-default—all schemas you declare will self-compile the first time you use them. This gives you the performance boost of compilation throughout your application with one line of code.

// in your entrypoint (or before any schemas are defined)
import "zod/compile";

Then use Zod normally:

import * as z from "zod";
 
z.string().min(1).max(10).optional().parse("hello"); // compiled

Compilation is lazy, so only the schemas you actually parse with get compiled.

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   # ESM
node --require zod/compile app.cjs # CommonJS

Or set preload in bunfig.toml or nub.jsonc.

nub.jsonc
{
  "preload": ["zod/compile"]
}

If new Function() is blocked by a Content Security Policy (e.g. in Cloudflare Workers environments) default-on compilation mode gracefully stands down and becomes a no-op.

Speedups

Containers like objects and tuples benefit the most, since compilation unrolls the runtime's per-key walk into flat loop-free validation logic that can be optimized by the JS engine.

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, standard parser vs compiled — lower is better (benchmark)

The benefits scale with schema complexity. Each schema here is measured alone in a tight loop — the standard parser's best case — so the ratios run lower than in the mixed-workload chart above (benchmark).

objectspeedup
5 keys1.8x
10 keys2.2x
20 keys5.0x
50 keys10.2x
tuplespeedup
1 item2.2x
3 items2.5x
5 items3.0x
10 items3.7x

Tradeoffs

The compiler trades off performance for bundle size. The compiler is a lot of code, and invoking it via z.compile() or "zod/compile" means it will be included in your bundle. It adds about 7 KB gzipped (28 KB minified): a Zod bundle with a four-key object schema goes from 24.1 KB to 31.1 KB gzipped, and a Zod Mini bundle from 4.6 KB to 13.2 KB. A bundle that never calls z.compile() or imports zod/compile pays nothing; it will be tree-shaken completely during bundling.

Try it

npm install zod@^4.5.0

Then z.compile() any schemas on the hot path, or import "zod/compile" at the top of your entry point.