Validate untrusted data and infer types automatically
Use this tool when handling data of unknown origin, such as API responses or user input, and you want to verify its shape against predefined rules. Write a schema once, and it validates data at runtime while automatically generating static types for TypeScript. This eliminates the need to write separate code for data validation and type declaration.
Schema definition and type extraction
Describe the type of each object field using methods like z.object. When parsing data with this schema, invalid values are filtered out, and valid values are returned with guaranteed types. The z.infer utility extracts the derived type from the schema without requiring a separate type declaration. If you use transformation logic where input and output types differ, you can independently retrieve each type using z.input and z.output. This structure ensures that data validation logic and the type system always remain consistent.
Improving validation speed with compilation
In paths where data is validated very frequently, use z.compile to improve performance. This method pre-compiles the schema to enhance validation speed, showing a 2.4x speedup in median benchmarks across 55 schemas. It can be up to 9 times faster for high-throughput cases like arrays of objects or objects with many keys, but there is no speed difference for low-throughput tasks like simple string validation. Compiled schemas follow a fast path for valid inputs, but invalid inputs fall back to the existing parser, so error reporting remains the same. However, schemas containing asynchronous refinement or transformation cannot be compiled; in these cases, the existing parser is used as is.
Error handling and installation
If validation fails, a ZodError is thrown, providing detailed information on which field failed and why. If you want to avoid try/catch blocks, use safeParse to receive the success status and data in a single result object. This tool has no external dependencies and works in Node.js and all modern browsers. The compressed core bundle size is 2kb. Installation is done simply by running the npm install zod command, and it can be used in both TypeScript and standard JavaScript projects.
Considerations when using compilation
Enabling z.compile globally uses new Function, so in environments with strict Content Security Policies (CSP), you should set the jitless option or avoid direct compilation calls. Additionally, deriving a new schema from a compiled schema un-compiles it, so it is recommended to compile after defining the final schema. Schemas containing asynchronous logic are excluded from compilation, so if you need these features, design your application assuming the use of the existing parser.