About this project
Zod is a TypeScript-first validation library. You define a schema, parse data with it, and receive a strongly typed, validated result. It works in Node.js and modern browsers, has zero external dependencies, and ships a small core bundle (about 2kb gzipped). The API is immutable: methods return a new instance rather than mutating the existing schema. It can be used from TypeScript or plain JavaScript and includes built-in JSON Schema conversion.
Basic usage starts with defining a schema, for example an object with a string and a number field. Calling `.parse` on the schema validates the input and returns a strongly typed deep clone. If the schema uses asynchronous refinements or transforms, `.parseAsync()` is required instead. When validation fails, `.parse()` throws a `ZodError` containing granular issue information such as the expected type, an error code, the path to the offending field, and a message. To avoid try/catch, `.safeParse()` returns a discriminated union with either the parsed data or the error; `.safeParseAsync()` covers asynchronous schemas.
Types can be inferred from schemas using `z.infer<>`. When input and output types diverge, for example through `.transform()`, `z.input<>` and `z.output<>` extract them independently.
A notable feature is ahead-of-time compilation. `z.compile(schema)` returns a schema clone with a compiled fast path for valid inputs, while invalid inputs fall back to the regular parser so error reporting stays identical. The README reports a median speedup of 2.4x across a 55-schema benchmark, scaling with schema complexity (large arrays of objects and 20-key objects around 9x, nested objects around 4.5x, while a bare string schema gains nothing). Compilation can also be enabled globally by importing `zod/compile` before modules that define schemas. Compilation uses `new Function`, and global mode is automatically disabled when `z.config({ jitless: true })` is set, such as in CSP environments; calling `z.compile()` directly is an explicit opt-in. Schemas with async refinements or transforms, and a few other constructs, cannot be compiled; in that case `z.compile()` returns the schema unchanged and it keeps using the regular parser, unless `{ strict: true }` is passed to throw specific errors. On invalid input, refinements and transforms may run twice. Deriving a new schema from a compiled one returns an uncompiled schema, so the final schema should be compiled.
Installation is via `npm install zod`. The project links to documentation at zod.dev, a Discord community, and social channels. It is MIT licensed.
Comments
0 Rating appears after 10 ratings
Sign in to join the discussion.