zod npmjs
zod
✨ https://zod.dev ✨
TypeScript-first schema validation with static type inference
These docs have been translated into Chinese.
- Table of contents
- Introduction
- Installation
- Basic usage
- Primitives
- Coercion for primitives
- Literals
- Strings
- Numbers
- BigInts
- NaNs
- Booleans
- Dates
- Zod enums
- Native enums
- Optionals
- Nullables
- Objects
- Arrays
- Tuples
- Unions
- Discriminated unions
- Records
- Maps
- Sets
- Intersections
- Recursive types
- Promises
- Instanceof
- Functions
- Preprocess
- Custom schemas
- Schema methods
- Guides and concepts
- Comparison
- Changelog
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple string
to a complex nested object.
Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.
Some other great aspects:
- Zero dependencies
- Works in Node.js and all modern browsers
- Tiny: 8kb minified + zipped
- Immutable: methods (e.g.
.optional()
) return a new instance - Concise, chainable interface
- Functional approach: parse, don't validate
- Works with plain JavaScript too! You don't need to use TypeScript.
Sponsorship at any level is appreciated and encouraged. If you built a paid product using Zod, consider one of the corporate tiers.
|
|
|
|
|
PropelAuth |
Cerbos |
Scalar |
Trigger.dev |
Transloadit |
Infisical |
Whop |
CryptoJobsList |
Plain. |
Inngest |
Storyblok |
Mux |
Brandon Bayer | Jiří Brabec | Alex Johansson | Fungible Systems |
Adaptable | Avana Wallet | Jason Lengstorf | Global Illumination, Inc. |
MasterBorn | Ryan Palmer | Michael Sweeney | Nextbase |
Remotion | Connor Sinnott | Mohammad-Ali A'râbi | Supatool |
There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it on Twitter or start a Discussion. I'll add it below and tweet it out.
- Total TypeScript Zod Tutorial by @mattpocockuk
- Fixing TypeScript's Blindspot: Runtime Typechecking by @jherr
tRPC
: Build end-to-end typesafe APIs without GraphQL.@anatine/zod-nestjs
: Helper methods for using Zod in a NestJS project.zod-endpoints
: Contract-first strictly typed endpoints with Zod. OpenAPI compatible.zhttp
: An OpenAPI compatible, strictly typed http library with Zod input and response validation.domain-functions
: Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas.@zodios/core
: A typescript API client with runtime and compile time validation backed by axios and zod.express-zod-api
: Build Express-based APIs with I/O schema validation and custom middlewares.tapiduck
: End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler.koa-zod-router
: Create typesafe routes in Koa with I/O validation using Zod.zod-sockets
: Zod-powered Socket.IO microframework with I/O validation and built-in AsyncAPI specsoas-tszod-gen
: Client SDK code generator to convert OpenApi v3 specifications into TS endpoint caller functions with Zod types.
react-hook-form
: A first-party Zod resolver for React Hook Form.zod-validation-error
: Generate user-friendly error messages fromZodError
s.zod-formik-adapter
: A community-maintained Formik adapter for Zod.react-zorm
: Standalone<form>
generation and validation for React using Zod.zodix
: Zod utilities for FormData and URLSearchParams in Remix loaders and actions.conform
: A typesafe form validation library for progressive enhancement of HTML forms. Works with Remix and Next.js.remix-params-helper
: Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps.formik-validator-zod
: Formik-compliant validator library that simplifies using Zod with Formik.zod-i18n-map
: Useful for translating Zod error messages.@modular-forms/solid
: Modular form library for SolidJS that supports Zod for validation.houseform
: A React form library that uses Zod for validation.sveltekit-superforms
: Supercharged form library for SvelteKit with Zod validation.mobx-zod-form
: Data-first form builder based on MobX & Zod.@vee-validate/zod
: Form library for Vue.js with Zod schema validation.zod-form-renderer
: Auto-infer form fields from zod schema and render them with react-hook-form with E2E type safety.antd-zod
: Zod adapter for Ant Design form fields validation.frrm
: Tiny 0.5kb Zod-based, HTML form abstraction that goes brr.
zod-to-ts
: Generate TypeScript definitions from Zod schemas.zod-to-json-schema
: Convert your Zod schemas into JSON Schemas.@anatine/zod-openapi
: Converts a Zod schema to an OpenAPI v3.xSchemaObject
.zod-fast-check
: Generatefast-check
arbitraries from Zod schemas.zod-dto
: Generate Nest.js DTOs from a Zod schema.fastify-type-provider-zod
: Create Fastify type providers from Zod schemas.zod-to-openapi
: Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters.nestjs-graphql-zod
: Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas.zod-openapi
: Create full OpenAPI v3.x documentation from Zod schemas.fastify-zod-openapi
: Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas.typeschema
: Universal adapter for schema validation.zodex
: (De)serialization for zod schemas
ts-to-zod
: Convert TypeScript definitions into Zod schemas.@runtyping/zod
: Generate Zod from static types & JSON schema.json-schema-to-zod
: Convert your JSON Schemas into Zod schemas. Live demo.json-to-zod
: Convert JSON objects into Zod schemas. Live demo.graphql-codegen-typescript-validation-schema
: GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema.zod-prisma
: Generate Zod schemas from your Prisma schema.Supervillain
: Generate Zod schemas from your Go structs.prisma-zod-generator
: Emit Zod schemas from your Prisma schema.drizzle-zod
: Emit Zod schemas from your Drizzle schema.prisma-trpc-generator
: Emit fully implemented tRPC routers and their validation schemas using Zod.zod-prisma-types
Create Zod types from your Prisma models.quicktype
: Convert JSON objects and JSON schemas into Zod schemas.@sanity-typed/zod
: Generate Zod Schemas from Sanity Schemas.java-to-zod
: Convert POJOs to Zod schemasOrval
: Generate Zod schemas from OpenAPI schemasKubb
: Generate SDKs and Zod schemas from your OpenAPI schemas
@anatine/zod-mock
: Generate mock data from a Zod schema. Powered by faker.js.zod-mocking
: Generate mock data from your Zod schemas.zod-fixture
: Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way.zocker
: Generate plausible mock-data from your schemas.zodock
Generate mock data based on Zod schemas.zod-schema-faker
Generates mock data from Zod schemas. Powered by @faker-js/faker and randexp.js
freerstore
: Firestore cost optimizer.slonik
: Node.js Postgres client with strong Zod integration.schemql
: Enhances your SQL workflow by combining raw SQL with targeted type safety and schema validation.soly
: Create CLI applications with zod.pastel
: Create CLI applications with react, zod, and ink.zod-xlsx
: A xlsx based resource validator using Zod schemas.znv
: Type-safe environment parsing and validation for Node.js with Zod schemas.zod-config
: Load configurations across multiple sources with flexible adapters, ensuring type safety with Zod.unplugin-environment
: A plugin for loading enviroment variables safely with schema validation, simple with virtual module, type-safe with intellisense, and better DX 🔥 🚀 👷. Powered by Zod.
zod_utilz
: Framework agnostic utilities for Zod.zod-playground
: A tool for learning and testing Zod schema validation functionalities. Link.zod-sandbox
: Controlled environment for testing zod schemas. Live demo.zod-dev
: Conditionally disables Zod runtime parsing in production.zod-accelerator
: Accelerates Zod's throughput up to ~100x.
-
TypeScript 4.5+!
-
You must enable
strict
mode in yourtsconfig.json
. This is a best practice for all TypeScript projects.// tsconfig.json { // ... "compilerOptions": { // ... "strict": true } }
npm install zod # npm
deno add npm:zod # deno
yarn add zod # yarn
bun add zod # bun
pnpm add zod # pnpm
Zod also publishes a canary version on every commit. To install the canary:
npm install zod@canary # npm
deno add npm:zod@canary # deno
yarn add zod@canary # yarn
bun add zod@canary # bun
pnpm add zod@canary # pnpm
The rest of this README assumes you are using npm and importing directly from the
"zod"
package.
Creating a simple string schema
import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }
Creating an object schema
import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }
import { z } from "zod";
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// catch-all types
// allows any value
z.any();
z.unknown();
// never type
// allows no values
z.never();
Zod now provides a more convenient way to coerce primitive values.
const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
During the parsing step, the input is passed through the String()
function, which is a JavaScript built-in for coercing data into strings.
schema.parse(12); // => "12"
schema.parse(true); // => "true"
schema.parse(undefined); // => "undefined"
schema.parse(null); // => "null"
The returned schema is a normal ZodString
instance so you can use all string methods.
z.coerce.string().email().min(5);
How coercion works
All primitive types support coercion. Zod coerces all inputs using the built-in constructors: String(input)
, Number(input)
, new Date(input)
, etc.
z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)
Note — Boolean coercion with z.coerce.boolean()
may not work how you expect. Any truthy value is coerced to true
, and any falsy value is coerced to false
.
const schema = z.coerce.boolean(); // Boolean(input)
schema.parse("tuna"); // => true
schema.parse("true"); // => true
schema.parse("false"); // => true
schema.parse(1); // => true
schema.parse([]); // => true
schema.parse(0); // => false
schema.parse(""); // => false
schema.parse(undefined); // => false
schema.parse(null); // => false
For more control over coercion logic, consider using z.preprocess
or z.pipe()
.
Literal schemas represent a literal type, like "hello world"
or 5
.
const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n); // bigint literal
const tru = z.literal(true);
const terrificSymbol = Symbol("terrific");
const terrific = z.literal(terrificSymbol);
// retrieve literal value
tuna.value; // "tuna"
Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.
Zod includes a handful of string-specific validations.
// validations
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().email();
z.string().url();
z.string().emoji();
z.string().uuid();
z.string().nanoid();
z.string().cuid();
z.string().cuid2();
z.string().ulid();
z.string().regex(regex);
z.string().includes(string);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().datetime(); // ISO 8601; by default only `Z` timezone allowed
z.string().ip(); // defaults to allow both IPv4 and IPv6
z.string().cidr(); // defaults to allow both IPv4 and IPv6
// transforms
z.string().trim(); // trim whitespace
z.string().toLowerCase(); // toLowerCase
z.string().toUpperCase(); // toUpperCase
// added in Zod 3.23
z.string().date(); // ISO date format (YYYY-MM-DD)
z.string()