Validating untrusted input with Zod
Look at the bookstore JSON for one second and you will find empty titles, negative page counts, and IDs that are strings instead of numbers. If you load that into your database, search will break, listings will look broken, and the company will lose revenue. The fix is to validate at the door.
You could, and for one or two fields it would even work. But the moment you have a real domain object with nested fields, optional values, and arrays, the if statements become the bug. You forget a check, you copy-paste, you drift. Schemas let you describe the shape once and trust the rest of your code.
import { z } from 'zod';
const BookSchema = z.object({
id: z.number().int().positive(),
title: z.string().min(1, 'Title cannot be empty'),
author: z.string().min(1, 'Author cannot be empty'),
pages: z.number().int().positive(),
published: z.string(),
});
const InventorySchema = z.array(BookSchema);A Zod schema is a single declarative description of what valid data looks like.
Read that schema like a contract. Every book has an id that is a positive integer. A title and author that are non-empty strings. A page count that is a positive integer. A published date as a string. The full inventory is an array of those. One declaration replaces dozens of checks.
const result = InventorySchema.safeParse(parsedJson);
if (!result.success) {
// result.error gives you a detailed report of every field that failed
console.error('Validation failed:', result.error.format());
throw new Error('Invalid data format');
}
// From here on, result.data is fully typed and safe to use
const cleanBooks = result.data;safeParse returns a result object so you decide what to do on failure.
Zod gives you two ways to validate: parse and safeParse. parse throws an error on failure. safeParse returns an object with success, data, and error. We almost always want safeParse because it puts the error handling decision in your hands instead of crashing the program for you.
Quiz: Quiz
Loading practiceโฆ
Validation checklist: Try the workshop module locally
Loading practiceโฆ