Course contentsShow
← TypeScript
Lesson 1296 of 1,79630. Type-Safe APIsFree lesson

Integrating Validators with API Routes

Validate request bodies in Express, Hono, or tRPC by parsing incoming JSON before business logic.

Integrating Validators with API Routes

What you'll learn: How to validate incoming request data in your API routes before it reaches your business logic, ensuring type safety at runtime.

The Runtime Safety Layer

You've learned how to define schemas with Zod and infer TypeScript types from them. Now it's time to put those validators to work where they matter most: at the entry point of your API.

When a client sends JSON to your Express, Hono, or tRPC endpoint, TypeScript can't help you—the compiler has no idea what's actually in that HTTP request body. Validators bridge this gap by parsing and checking the data before your typed business logic ever sees it.

The Pattern: Parse Before Processing

Think of validators as a security checkpoint. Before letting unknown data into your type-safe world, you verify it matches your schema:

import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email(),
  age: z.number().min(18)
});

type CreateUserInput = z.infer<typeof CreateUserSchema>;

// Express example
app.post('/users', (req, res) => {
  const result = CreateUserSchema.safeParse(req.body);
  
  if (!result.success) {
    return res.status(400).json({ errors: result.error });
  }
  
  // Now result.data is typed as CreateUserInput
  const user = createUser(result.data);
  res.json(user);
});

After parsing succeeds, result.data has the correct TypeScript type, and you know the runtime values match. Your createUser function receives guaranteed-valid data.

Key Takeaway: Always parse incoming JSON with your validator before passing data to business logic—this creates a trusted boundary where TypeScript types and runtime values align.