Menu

Runtime Validation with Zod

Lesson 3: Runtime Validation with Zod

Why validate at runtime?

TypeScript types are erased, so they cannot check data arriving at runtime. A schema library checks the data and gives you the matching type.

Approach Checks at runtime? Gives a TypeScript type? Single source of truth?
Type annotation only No Yes –
Hand-written type guard Yes Yes No: type and guard can drift apart
Schema library (Zod, Valibot, ArkType) Yes Yes, inferred Yes

Example

import { z } from 'zod';

export const CreateOrderSchema = z.object({
  customerId: z.string().min(1),
  items: z
    .array(z.object({ productId: z.string(), quantity: z.number().int().positive() }))
    .min(1, 'Add at least one item'),
  paymentMethod: z.enum(['UPI', 'Card', 'COD']),
  deliverySlot: z.enum(['morning', 'afternoon', 'evening']).default('morning'),
  couponCode: z.string().optional(),
});

// Type inferred from the schema – no duplicate interface
export type CreateOrderInput = z.infer<typeof CreateOrderSchema>;

// In an Express route
app.post('/orders', (req, res) => {
  const result = CreateOrderSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ errors: result.error.issues });
  }
  const order: CreateOrderInput = result.data; // Validated and typed
  res.status(201).json(createOrder(order));
});

// Validating environment variables
const EnvSchema = z.object({
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
});
export const env = EnvSchema.parse(process.env);

> Note: Validation libraries such as Zod update their APIs between major versions, so some method names and error formats may differ from the code above. Always follow the library's official documentation for the version you install.

How it works

  • safeParse returns { success: true, data } or { success: false, error }, a discriminated union you already know how to narrow.
  • parse throws instead, which suits startup checks where failing fast is correct.
  • z.infer turns the schema into a type, so adding a field to the schema updates the type everywhere.
  • Validate at boundaries: HTTP requests, API responses, form submissions, local storage, files, and environment variables. Inside your app, trust the types.

Common mistakes

Mistake Effect Fix
Writing an interface and a schema separately They drift apart Infer the type from the schema
Validating deep inside business logic Repeated checks, scattered errors Validate once at the boundary
Returning raw validation errors to users Confusing messages Map issues to friendly field messages

Key takeaways

  • Types do not exist at runtime; schemas do.
  • Define a schema once, validate at the boundary, and infer the type with z.infer.

Try it: Write a Zod schema for a delivery address (pincode must be 6 digits), infer its type, and validate three sample objects with safeParse.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details