TypeScript-first schema declaration and validation library with static type inference
Zod is a TypeScript-first schema validation library that validates data at runtime while automatically inferring static types. With over 85 million weekly downloads, it has become the go-to solution for validating unknown inputs entering your application—whether from API requests, user forms, environment variables, or external data sources. The library eliminates the traditional duplication between TypeScript types and validation logic by letting you define schemas once and derive both runtime validation and compile-time types.
The library excels at boundary validation: checking data where your application meets the outside world. Rather than trusting that API responses match their documentation or that users submit correctly-formatted data, Zod validates inputs and provides detailed error messages when validation fails. This approach catches data integrity issues before they propagate through your application, reducing bugs and improving reliability.
Zod ships with zero external dependencies and a minimal 2kb gzipped bundle for standard usage. Version 4 introduced significant improvements including a 50% bundle size reduction, enhanced discriminated unions that support complex compositions, and a metadata system for attaching type-safe custom data to schemas. The library works across Node.js and browsers, with both TypeScript and plain JavaScript support, though TypeScript users gain the most benefit from automatic type inference.
Major frameworks and libraries have adopted Zod as their validation layer. tRPC uses it for end-to-end type-safe APIs, React Hook Form integrates it for form validation, and countless libraries expose Zod schemas as their configuration interface. This ecosystem adoption reflects Zod's balance of developer experience, performance, and flexibility in handling everything from simple string validation to complex nested object structures.
import { z } from 'zod';
const UserRegistrationSchema = z.object({
username: z.string().min(3).max(20).regex(/^[a-zA-Z0-9_]+$/),
email: z.string().email(),
age: z.number().int().min(18).max(120),
role: z.enum(['user', 'admin', 'moderator']).default('user'),
preferences: z.object({
newsletter: z.boolean(),
notifications: z.enum(['all', 'mentions', 'none'])
}),
website: z.string().url().optional()
});
type UserRegistration = z.infer<typeof UserRegistrationSchema>;
function handleRegistration(data: unknown) {
const result = UserRegistrationSchema.safeParse(data);
if (!result.success) {
console.error('Validation failed:', result.error.format());
return { success: false, errors: result.error.flatten() };
}
const validUser: UserRegistration = result.data;
console.log('Valid user:', validUser);
return { success: true, user: validUser };
}
const testData = {
username: 'john_doe',
email: 'john@example.com',
age: 25,
preferences: {
newsletter: true,
notifications: 'mentions'
}
};
handleRegistration(testData);
handleRegistration({ username: 'ab', email: 'invalid' });API Request/Response Validation: Validate incoming HTTP requests in Express, Next.js API routes, or serverless functions to ensure request bodies, query parameters, and headers match expected schemas before processing. Similarly, validate third-party API responses to catch breaking changes or unexpected data structures.
Form Validation: Integrate with form libraries like React Hook Form or use standalone to validate user input in registration forms, checkout flows, or admin panels. Zod's detailed error messages map directly to field-level validation feedback.
Environment Variable Parsing: Validate and parse environment variables at application startup to fail fast if required configuration is missing or malformed. Transform string values into proper types (numbers, booleans, URLs) with built-in coercion.
CLI Argument Parsing: Validate command-line arguments and options in Node.js scripts or CLI tools, ensuring required flags are present and values conform to expected types before executing business logic.
Data Migration and ETL: Validate data during migrations, imports, or ETL pipelines to identify malformed records before database insertion. Use Zod to enforce data contracts when moving data between systems with different schemas.
npm install zodpnpm add zodbun add zod