Zod Simplifies TypeScript API Validation

Zod is the best thing to happen to TypeScript APIs since TypeScript itself. I spent 3 years writing manual validation logic in Node.js APIs. Checking if req.body.email is a string. Checking if it's actually an email. Checking if req.body.age is a number and not negative. Writing the error message manually. Remembering to do this on every route. Then I found Zod. I genuinely don't know how I shipped APIs without it. WHAT ZOD DOES Zod lets you define a schema once. That schema does three things: 1. Validates the data at runtime 2. Infers the TypeScript type automatically 3. Produces clean, structured error messages // One schema. Three things at once. import { z } from 'zod' const CreateOrderSchema = z.object({ userId: z.string().uuid(), items: z.array(z.object({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(100) })).min(1, 'Order must have at least one item'), deliveryDate: z.string().datetime().optional(), promoCode: z.string().toUpperCase().optional() }) // TypeScript type — inferred automatically, no duplication type CreateOrder = z.infer USING IT IN AN EXPRESS / NESTJS API const result = CreateOrderSchema.safeParse(req.body) if (!result.success) { return res.status(422).json({ errors: result.error.flatten().fieldErrors }) // Returns exactly which field failed and why // { items: ['Order must have at least one item'] } } // result.data is now fully typed — no casting, no assertions const order = await orderService.create(result.data) 3 ZOD PATTERNS I USE ON EVERY PROJECT 1. .transform() — sanitise on parse, not separately z.string().trim().toLowerCase().email() 2. .refine() — custom logic type-safety can't express z.string().refine(s => isValidIBAN(s), 'Invalid IBAN') 3. Shared schemas between frontend and backend One package, one source of truth, zero API contract drift Zod replaced about 400 lines of manual validation in the last codebase I cleaned up. 400 lines that were inconsistent, untested, and spread across 30 files. One Zod schema file. Consistent everywhere. #TypeScript #NodeJS #WebDevelopment #BackendDevelopment #SoftwareEngineering

  • text

Muhammad Mubeen Yasin Do you reuse the same Zod schemas on client and server, or keep them separate? What major drawbacks have you faced?

To view or add a comment, sign in

Explore content categories