Zod: TypeScript Schema Validation
You've typed your request body as CreateUserDto, the code compiles, and then production logs show Cannot read properties of undefined (reading 'toLowerCase') because a mobile client sent user_email instead of email. TypeScript didn't warn you because it never saw that request. Types are erased at compile time, so anything crossing a boundary (a network request, a form post, an env variable) is just trusted.
Zod fixes this by letting you write one schema that does both jobs: it validates data at runtime and gives you the TypeScript type for free. Below I cover the core schema types, refinements and transforms, React Hook Form, API validation, env vars, and a couple of gotchas that bite people in production.
Zod is one of the most downloaded validation libraries on npm. tRPC uses it in most of its examples, and React Hook Form supports it through @hookform/resolvers. If you work on a full-stack TypeScript codebase, there's a good chance it's already in your package.json.
The Problem Zod Solves
Here's a typical Express handler. You define an interface for the request body, but what actually arrives from the network is unknown. The compiler accepts your type assertion because it has no other option, and the data can still be completely wrong:
interface CreateUserDto {
name: string;
email: string;
age: number;
}
// This compiles fine but crashes at runtime if body is malformed
app.post('/users', (req, res) => {
const body = req.body as CreateUserDto; // ← blind trust
const user = db.createUser(body.name, body.email, body.age);
res.json(user);
});
The underlying issue is that you end up with two sources of truth: the interface and whatever runtime checks you wrote by hand (if any). They drift apart the first time someone adds a field to one and forgets the other. With Zod you write the schema once and infer the type from it.
One schema produces both the compile-time type and the runtime check
Installation and First Steps
Install Zod
Zod requires TypeScript 4.5+ with strict mode enabled in your tsconfig.json.
# npm
npm install zod
# pnpm
pnpm add zod
# yarn
yarn add zod
Enable strict mode in tsconfig.json
Zod's type inference works best with TypeScript strict mode. Add "strict": true to your compilerOptions.
Define your first schema
Import z from zod and start building schemas. Use z.infer to get the TypeScript type, so you don't write a separate interface.
import { z } from 'zod';
// Define the schema
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().min(0).max(150),
});
// Extract the TypeScript type from the schema (no duplicate interface)
type User = z.infer<typeof UserSchema>;
// Equivalent to: { name: string; email: string; age: number }
// parse() throws a ZodError if validation fails
const user = UserSchema.parse({
name: 'Alice',
email: 'alice@example.com',
age: 30,
});
// safeParse() never throws; it returns a discriminated union
const result = UserSchema.safeParse({ name: 'Bob', email: 'not-an-email', age: -1 });
if (!result.success) {
console.log(result.error.issues);
// [{ code: 'invalid_string', message: 'Invalid email', path: ['email'] },
// { code: 'too_small', message: 'Number must be >= 0', path: ['age'] }]
}
Use .parse() when you want to throw on invalid data (middleware, server startup). Use .safeParse() when you want to send errors back to a client. It returns { success: true, data } | { success: false, error } and never throws.
Core Schema Types
Zod has a schema for pretty much every TypeScript type. These are the ones I reach for most:
import { z } from 'zod';
// Strings
z.string()
z.string().min(3).max(100)
z.string().email()
z.string().url()
z.string().uuid()
z.string().regex(/^[a-z]+$/)
z.string().trim() // strips whitespace before validation
z.string().toLowerCase() // transform: to lowercase
// Numbers
z.number()
z.number().int()
z.number().positive()
z.number().min(0).max(100)
z.number().finite()
z.number().multipleOf(5)
// Other primitives
z.boolean()
z.date()
z.bigint()
z.symbol()
z.undefined()
z.null()
z.void()
z.any()
z.unknown()
z.never()
import { z } from 'zod';
// Objects
const ProductSchema = z.object({
id: z.string().uuid(),
name: z.string(),
price: z.number().positive(),
tags: z.array(z.string()),
});
// Nested objects
const OrderSchema = z.object({
product: ProductSchema,
quantity: z.number().int().positive(),
});
// Arrays
z.array(z.string()) // string[]
z.array(z.number()).min(1).max(5) // 1 to 5 numbers
z.string().array() // shorthand
// Tuples: fixed length, typed per position
const PointSchema = z.tuple([z.number(), z.number()]);
type Point = z.infer<typeof PointSchema>; // [number, number]
// Records: like a TypeScript Record<K, V>
const ScoresSchema = z.record(z.string(), z.number());
type Scores = z.infer<typeof ScoresSchema>; // Record<string, number>
// Maps and Sets
z.map(z.string(), z.number())
z.set(z.string())
import { z } from 'zod';
// Enums
const StatusSchema = z.enum(['active', 'inactive', 'pending']);
type Status = z.infer<typeof StatusSchema>; // 'active' | 'inactive' | 'pending'
// Native TypeScript enums
enum Direction { Up, Down, Left, Right }
const DirectionSchema = z.nativeEnum(Direction);
// Unions
const StringOrNumber = z.union([z.string(), z.number()]);
// Discriminated unions: faster, better errors
const ResultSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('success'), data: z.string() }),
z.object({ status: z.literal('error'), message: z.string() }),
]);
// Intersections
const WithTimestamps = z.object({
createdAt: z.date(),
updatedAt: z.date(),
});
const UserWithTimestamps = UserSchema.and(WithTimestamps);
// Literals
z.literal('hello')
z.literal(42)
z.literal(true)
import { z } from 'zod';
const BaseSchema = z.object({
id: z.string().uuid(),
name: z.string(),
bio: z.string(),
});
// Optional: adds | undefined
z.string().optional() // string | undefined
// Nullable: adds | null
z.string().nullable() // string | null
// Nullish: adds | null | undefined
z.string().nullish()
// Default: provides a fallback value
z.string().default('anonymous')
z.boolean().default(false)
// Object modifiers
const UpdateSchema = BaseSchema.partial(); // All fields optional
const RequiredSchema = BaseSchema.required(); // All fields required
const PickedSchema = BaseSchema.pick({ name: true }); // { name }
const OmittedSchema = BaseSchema.omit({ bio: true }); // { id, name }
const ExtendedSchema = BaseSchema.extend({
email: z.string().email(),
});
// Passthrough: allow extra keys (stripped by default)
BaseSchema.passthrough()
BaseSchema.strict() // throw on extra keys
BaseSchema.strip() // default: silently remove extra keys
Refinements and Transformations
Type checks only get you so far. Real forms need rules like "passwords must match" or "this string should become a number". .refine() adds custom validation, and .transform() reshapes data as part of parsing.
import { z } from 'zod';
// .refine(): custom validation predicate
const PasswordSchema = z.string()
.min(8, 'Password must be at least 8 characters')
.refine(
(val) => /[A-Z]/.test(val),
{ message: 'Password must contain at least one uppercase letter' }
)
.refine(
(val) => /[0-9]/.test(val),
{ message: 'Password must contain at least one number' }
);
// Cross-field validation with .superRefine()
const SignupSchema = z.object({
password: z.string().min(8),
confirmPassword: z.string(),
}).superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Passwords do not match',
path: ['confirmPassword'],
});
}
});
// .transform(): parse and reshape data
const StringToNumber = z.string().transform((val) => parseInt(val, 10));
type StringToNumber = z.infer<typeof StringToNumber>; // number (output type)
// Chaining transforms
const TrimmedEmail = z.string()
.trim()
.toLowerCase()
.email();
// Pipe: compose schemas
const CoercedDate = z.string()
.pipe(z.coerce.date()); // parse string → Date object
// z.coerce: automatic type coercion (handy for query params)
z.coerce.number() // "42" → 42
z.coerce.boolean() // "true" → true, "1" → true, but "false" → true too!
z.coerce.date() // "2026-01-01" → Date object
When you use .transform(), z.infer gives you the output type, not the input. If you need both, use z.input<typeof Schema> for the input type and z.output<typeof Schema> for the output type. This matters for API request vs response schemas.
Form Validation with React Hook Form
React Hook Form accepts a Zod schema through the @hookform/resolvers package. You skip the hand-written validate functions, and the same schema drives both the error messages in the UI and the type of your submit handler's data.
npm install @hookform/resolvers react-hook-form
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
const RegistrationSchema = z.object({
username: z.string()
.min(3, 'Username must be at least 3 characters')
.max(20, 'Username cannot exceed 20 characters')
.regex(/^[a-zA-Z0-9_]+$/, 'Only letters, numbers, and underscores'),
email: z.string().email('Please enter a valid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
confirmPassword: z.string(),
acceptTerms: z.literal(true, {
errorMap: () => ({ message: 'You must accept the terms' }),
}),
}).superRefine((data, ctx) => {
if (data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Passwords do not match',
path: ['confirmPassword'],
});
}
});
type RegistrationFormData = z.infer<typeof RegistrationSchema>;
export function RegistrationForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<RegistrationFormData>({
resolver: zodResolver(RegistrationSchema),
});
const onSubmit = async (data: RegistrationFormData) => {
// data is fully typed: TypeScript knows every field's type
await registerUser(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<input {...register('username')} placeholder="Username" />
{errors.username && <p>{errors.username.message}</p>}
</div>
<div>
<input {...register('email')} type="email" placeholder="Email" />
{errors.email && <p>{errors.email.message}</p>}
</div>
<div>
<input {...register('password')} type="password" placeholder="Password" />
{errors.password && <p>{errors.password.message}</p>}
</div>
<div>
<input {...register('confirmPassword')} type="password" placeholder="Confirm" />
{errors.confirmPassword && <p>{errors.confirmPassword.message}</p>}
</div>
<div>
<input {...register('acceptTerms')} type="checkbox" />
<label>I accept the terms and conditions</label>
{errors.acceptTerms && <p>{errors.acceptTerms.message}</p>}
</div>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Registering...' : 'Register'}
</button>
</form>
);
}
The Zod schema drives both TypeScript types and React Hook Form validation
In Zod 3, a .superRefine() on the object is skipped when any field fails with a hard error such as a missing value, a wrong type, or a failed z.literal. In the form above, if the terms box is unchecked (false instead of true), the "Passwords do not match" message won't appear until the box is ticked. Also make sure path points at a field you actually render. An issue with no path isn't attached to any input, so nothing on screen shows it.
API Input Validation
This is where I get the most value from Zod. Any handler that accepts user-controlled data is both a security boundary and a place where bad data sneaks into your database. A small middleware validates it once and hands typed data to the route.
Express Middleware
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject, ZodError } from 'zod';
// Generic validation middleware factory
export const validate = (schema: AnyZodObject) =>
async (req: Request, res: Response, next: NextFunction) => {
const result = await schema.safeParseAsync({
body: req.body,
query: req.query,
params: req.params,
});
if (!result.success) {
return res.status(400).json({
error: 'Validation failed',
issues: result.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
})),
});
}
// Attach validated/transformed data back to req
req.body = result.data.body;
next();
};
// Usage in routes
import { z } from 'zod';
const CreatePostSchema = z.object({
body: z.object({
title: z.string().min(5).max(200),
content: z.string().min(50),
tags: z.array(z.string()).max(10).default([]),
published: z.boolean().default(false),
}),
});
router.post('/posts', validate(CreatePostSchema), async (req, res) => {
// req.body is fully typed and validated here
const post = await Post.create(req.body);
res.status(201).json(post);
});
Next.js API Routes
import { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';
const ContactSchema = z.object({
name: z.string().min(2).max(100),
email: z.string().email(),
subject: z.string().min(5).max(200),
message: z.string().min(20).max(2000),
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method Not Allowed' });
}
const result = ContactSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: 'Invalid request',
details: result.error.flatten().fieldErrors,
});
}
// result.data is typed as { name: string; email: string; ... }
await sendContactEmail(result.data);
res.status(200).json({ success: true });
}
Advanced Patterns
A few patterns that come up once Zod is in more than one or two files.
Environment Variable Validation
If I could only use Zod in one place, it'd be here. Validating process.env at startup means a missing DATABASE_URL crashes the process on boot with a readable message, instead of failing on the first request an hour after deploy.
import { z } from 'zod';
const EnvSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']),
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32, 'JWT_SECRET must be at least 32 characters'),
PORT: z.coerce.number().int().min(1024).max(65535).default(3000),
REDIS_URL: z.string().url().optional(),
ALLOWED_ORIGINS: z.string()
.transform((val) => val.split(',').map((s) => s.trim())),
});
// Parse once at startup; throws with a clear error if misconfigured
const env = EnvSchema.parse(process.env);
// Export typed env: all fields have their correct TypeScript types
export default env;
// Usage:
// import env from './env';
// env.PORT // number
// env.DATABASE_URL // string (URL-validated)
// env.ALLOWED_ORIGINS // string[] (transformed)
Recursive Schemas
import { z } from 'zod';
// Recursive type for a tree structure (e.g., nested comments, menu items)
type Category = {
id: string;
name: string;
children: Category[];
};
const CategorySchema: z.ZodType<Category> = z.lazy(() =>
z.object({
id: z.string().uuid(),
name: z.string(),
children: z.array(CategorySchema),
})
);
// Branded types: add type-level uniqueness
const UserId = z.string().uuid().brand<'UserId'>();
const PostId = z.string().uuid().brand<'PostId'>();
type UserId = z.infer<typeof UserId>;
type PostId = z.infer<typeof PostId>;
function getUser(id: UserId) { /* ... */ }
const postId = PostId.parse('some-uuid');
// getUser(postId); // TypeScript error! PostId is not assignable to UserId
Comparison: Zod vs Alternatives
| Feature | Zod | Yup | Joi | io-ts |
|---|---|---|---|---|
| TypeScript-first | ✅ Yes | ⚠️ Partial | ⚠️ Partial | ✅ Yes |
| Type inference | ✅ Automatic | ❌ Manual | ❌ Manual | ✅ Automatic |
| Bundle size | Moderate | Moderate | Large (built for Node) | Small (needs fp-ts) |
| Transformations | ✅ Built-in | ✅ Built-in | ✅ Built-in | ⚠️ Verbose |
| Error messages | ✅ Excellent | ✅ Good | ✅ Good | ⚠️ Terse |
| tRPC integration | ✅ Native | ⚠️ Via adapter | ⚠️ Via adapter | ⚠️ Via adapter |
| Learning curve | Low | Low | Medium | High |
Real-World Example: Full API Contract
Here's how I'd lay out shared schemas for a blog post resource, so the frontend and backend import the same file. This is the same idea tRPC is built on:
import { z } from 'zod';
// Base shape: shared validation rules
const PostBase = z.object({
title: z.string().min(5, 'Title too short').max(200, 'Title too long'),
content: z.string().min(50, 'Post must have at least 50 characters'),
excerpt: z.string().max(300).optional(),
tags: z.array(z.string().toLowerCase().trim()).max(10).default([]),
published: z.boolean().default(false),
publishAt: z.coerce.date().optional(),
});
// Create: what the client sends
export const CreatePostSchema = PostBase;
export type CreatePostInput = z.infer<typeof CreatePostSchema>;
// Update: all fields optional except id
export const UpdatePostSchema = PostBase.partial().extend({
id: z.string().uuid(),
});
export type UpdatePostInput = z.infer<typeof UpdatePostSchema>;
// Response: what the server returns (adds generated fields)
export const PostResponseSchema = PostBase.extend({
id: z.string().uuid(),
slug: z.string(),
authorId: z.string().uuid(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
viewCount: z.number().int().min(0),
});
export type PostResponse = z.infer<typeof PostResponseSchema>;
// List query params
export const ListPostsQuerySchema = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
tag: z.string().optional(),
published: z.coerce.boolean().optional(),
search: z.string().max(200).optional(),
});
export type ListPostsQuery = z.infer<typeof ListPostsQuerySchema>;
// In the API route:
// const query = ListPostsQuerySchema.parse(req.query);
// query.page → number (coerced from string query param)
// query.limit → number
// query.published → boolean | undefined
?published=false Bugz.coerce.boolean() just calls Boolean(value), so any non-empty string, including "false" and "0", becomes true. In the schema above, ?published=false returns published posts. For query strings, use something explicit like z.enum(['true', 'false']).transform((v) => v === 'true') instead.
ZodError: Understanding Error Structure
There are three ways to shape the errors, depending on who's reading them:
const result = CreatePostSchema.safeParse({
title: 'Hi', // too short
content: 'Short', // too short
tags: ['JS', 'JS'], // duplicates (if you add a refine)
});
if (!result.success) {
// .issues: full detail array
result.error.issues;
// [
// { code: 'too_small', path: ['title'], message: 'Title too short' },
// { code: 'too_small', path: ['content'], message: 'Post must have...' }
// ]
// .format(): nested object matching input shape
result.error.format();
// { title: { _errors: ['Title too short'] }, content: { _errors: [...] } }
// .flatten(): flat field → messages map (good for APIs)
result.error.flatten();
// {
// formErrors: [],
// fieldErrors: { title: ['Title too short'], content: ['Post must have...'] }
// }
}
When I'd Use Zod (and When I Wouldn't)
Trade-offs worth knowing
- Use it at the edges: request bodies, query params, env vars, webhook payloads,
localStoragereads, and responses from third-party APIs you don't control. That's where data is genuinelyunknown. - Don't re-validate internal data: once a value has been parsed at the boundary, passing it through five functions that each call
.parse()again just costs CPU. Trust the inferred type inside your own code. - Watch hot paths: parsing large arrays of deeply nested objects on every request isn't free. If you're validating thousands of rows from your own database, you probably don't need Zod there at all.
- Check your Zod version: the examples here use the Zod 3 API. Zod 4 changes some of it (for example
errorMapbecomeserror, and.format()/.flatten()are deprecated in favour ofz.treeifyError()andz.flattenError()), so read the migration guide before upgrading. - Consider alternatives for tiny bundles: on a small client-side widget where every kilobyte counts, a lighter, tree-shakable library like Valibot may suit you better.
If you're adding Zod to an existing project, I'd start with the env file and your most-used POST endpoint. Those two catch the most bugs for the least work, and you'll get a feel for whether you want it everywhere else.