Skip to content

Zod – TypeScript-first schema declaration and validation library

NPM Last Update NPM Downloads NPM Version

Zod is a TypeScript-first schema validation library designed to be type-safe and declarative. It allows you to define data schemas, validate inputs, and automatically generate TypeScript types. Zod is especially useful for validating data from APIs, forms, or configurations.


Install Zod via npm or yarn:

Terminal window
npm install zod
# or
yarn add zod

import { z } from "zod";
// Define a schema for a "User" object
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(2),
age: z.number().int().positive(),
email: z.string().email(),
});
const userData = {
id: "550e8400-e29b-41d4-a716-446655440000",
name: "Alice",
age: 30,
email: "alice@example.com",
};
const result = UserSchema.safeParse(userData);
if (result.success) {
console.log("Validation successful:", result.data);
} else {
console.error("Validation error:", result.error);
}

const AddressSchema = z.object({
street: z.string(),
city: z.string(),
zipCode: z.string().regex(/^\d{5}$/),
});
const UserWithAddressSchema = UserSchema.extend({
address: AddressSchema,
});
const UserArraySchema = z.array(UserSchema);
const OptionalUserSchema = UserSchema.optional();
const NullableUserSchema = UserSchema.nullable();
const UserWithFullNameSchema = UserSchema.extend({
fullName: z.string(),
}).transform((user) => ({
...user,
fullName: `${user.name} (${user.email})`,
}));

Zod is ideal for validating API responses:

const ApiResponseSchema = z.object({
status: z.literal("success"),
data: z.array(UserSchema),
});
const apiResponse = {
status: "success",
data: [
{
id: "550e8400-e29b-41d4-a716-446655440000",
name: "Alice",
age: 30,
email: "alice@example.com",
},
],
};
const parsedResponse = ApiResponseSchema.parse(apiResponse);

  • Reuse your schemas: Define base schemas and extend them.
  • Use safeParse: To handle validation errors gracefully.
  • Document your schemas: Add descriptions to clarify their usage.

For more details, check out the official Zod documentation.


Here’s a complete example of using Zod in a TypeScript project:

import { z } from "zod";
// 1. Define a schema
const ProductSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
price: z.number().positive(),
inStock: z.boolean(),
});
// 2. Validate user input
const userInput = {
id: "550e8400-e29b-41d4-a716-446655440000",
name: "Laptop",
price: 999.99,
inStock: true,
};
const product = ProductSchema.parse(userInput);
console.log(product); // { id: "...", name: "Laptop", price: 999.99, inStock: true }