Schema Validation with Zod

Define data shapes once with Zod to validate forms and API responses at runtime and infer TypeScript types from the same schema.

Intermediate · about 3 hours · difficulty 2/5

Learn first: Forms in React with React Hook Form, TypeScript Fundamentals

TypeScript types vanish at runtime, so they cannot protect you from a user typing nonsense or an API returning an unexpected shape. A schema library checks real data at runtime, and with Zod you also infer the static type from the schema so the two never drift apart.

Zod basics

const Signup = z.object({ email: z.email(), age: z.number().int().min(18), plan: z.enum(["free", "pro"]) });
type Signup = z.infer<typeof Signup>;
  • schema.parse(data) returns typed data or throws; safeParse returns a result object you can branch on.
  • Refinements (.refine, .superRefine) for cross-field rules like "passwords match".
  • Transforms and coercion (z.coerce.number()) to turn form strings into numbers or dates.
  • Compose schemas with .extend, .pick, .omit and .partial just like utility types.

Where to use it

  • Forms: plug the schema into React Hook Form with zodResolver; error messages come from the schema.
  • API boundaries: validate responses in your API client so bad data fails loudly in one place.
  • Environment variables: validate import.meta.env at startup.
  • Shared contracts: in full-stack TypeScript apps, the same schema validates on the server (Server Actions, API routes) and the client.

Alternatives with similar ideas include Valibot (smaller bundles), ArkType and Yup (common in older code).

Pitfalls

Client-side validation is for UX only; the server must validate again. Keep error messages human, and avoid huge schemas in the client bundle when a smaller library would do.

Good enough to move on

You can write a schema with refinements and transforms, infer its type, use it in a form and in an API client, and explain why the server still validates.

Key concepts

  • Defining object schemas
  • parse vs safeParse
  • Inferring types with z.infer
  • Refinements for cross-field rules
  • Coercion and transforms
  • zodResolver with React Hook Form
  • Validating API responses and env vars
  • Valibot and Yup

Mini project

Create one Zod schema for a job application (with a password-confirm refinement and coerced numeric fields), use it for the form, reuse it to validate a mock API's response, and validate your app's env vars on startup.

Check yourself

If the frontend validates a form with Zod, why must the backend validate the same data again?

Free resources