What is Zod
Zod is a TypeScript-first schema declaration and validation library. The term "schema" is used to broadly refer to any data type, from a simple string
to complex nested objects.
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 simple types into complex data structures.
Key Features
- Zero dependencies
- Works in Node.js and all modern browsers
- Tiny: 8kb minified
- Immutable: methods (like
.optional()
) return a new instance - Concise, chainable interface
- Functional approach: Parse, don't validate
- Works with plain JavaScript! You don't need to use TypeScript.
Installation
bash
npm install zod
Basic Usage
ts
import { z } from "zod";
// Create 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 }