Runtime Validation with Zod
Validate untrusted data at every boundary (forms, API bodies, environment variables) and infer TypeScript types from the same schema.
Intermediate · about 4 hours · difficulty 2/5
Learn first: TypeScript Fundamentals
TypeScript checks your code; it cannot check data coming from users, other services or environment files. Schema validation closes that gap.
Why Zod
Zod lets you define a schema once and get both a runtime validator and a TypeScript type from it. Alternatives like Valibot and Yup follow the same idea; the skill transfers.
Where to validate
- API request bodies, params and query strings before they reach your business logic.
- Form input on the client for fast feedback, and again on the server because client checks can be bypassed.
- Environment variables at startup, so a missing DATABASE_URL fails loudly at boot instead of at the first request.
- Third-party API responses you depend on.
Patterns
- Use safeParse to get either data or a structured error, and return a 400 with field-level messages.
- Share one schema between a React form and the API route.
- Transform and coerce carefully, for example turning "5" from a query string into the number 5.
Pitfalls
- Validating only on the client.
- Writing a type and a schema separately so they drift. Infer the type from the schema.
- Leaking raw validation internals to users instead of friendly messages.
You are ready to move on when the same Zod schema validates your signup form in the browser and the signup endpoint on the server, and the server rejects bad input with clear 400 errors.
Key concepts
- Schemas and inferred types
- parse vs safeParse
- Validating request bodies
- Validating environment variables
- Shared client and server schemas
- Coercion and transforms
- Valibot or Yup
Mini project
Write Zod schemas for a student signup (name, college email, phone with Indian format, graduation year) and an env schema for your app. Infer the types and use them in a small Node.js script that validates sample inputs.
Check yourself
Your frontend already validates the email field. Why must the API validate it again?
Free resources
- Zod documentation (Zod)
- Valibot (Valibot)
- OWASP Input Validation Cheat Sheet (OWASP)