Course contentsShow
← TypeScript
Lesson 1557 of 1,79636. tRPC and End-to-End Type SafetyFree lesson

Input Validation with Zod Integration

How tRPC pairs runtime validation libraries with TypeScript to guarantee type safety at boundaries.

Input Validation with Zod Integration

What you'll learn: How tRPC pairs runtime validation libraries with TypeScript to guarantee type safety at boundaries.

The Bridge Between Compile Time and Runtime

TypeScript gives you static types that vanish at runtime. Your frontend thinks it's receiving a User object, but what if the backend sends corrupted data? What if a malicious client sends the wrong shape to your mutation? TypeScript can't help once JavaScript is running.

This is where Zod bridges the gap.

How tRPC + Zod Creates Dual Safety

tRPC procedures accept an .input() method that takes a Zod schema. This schema does two critical things:

  1. Runtime validation — Every incoming request is validated against the schema before your procedure runs
  2. Compile-time types — TypeScript infers the input type from the schema automatically
import { z } from 'zod';
import { router, publicProcedure } from './trpc';

const userSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional()
});

export const appRouter = router({
  createUser: publicProcedure
    .input(userSchema)
    .mutation(({ input }) => {
      // input is typed as { name: string; email: string; age?: number }
      // AND it's been validated at runtime!
      return { id: 1, ...input };
    })
});

Your client code automatically gets these types. No manual synchronization. If you change the schema, TypeScript errors appear in your frontend before you even compile.

The Single Source of Truth

The Zod schema becomes your contract: it defines both what TypeScript expects and what actually gets validated. They can't drift apart because they're the same definition. This is tRPC's superpower — type safety that actually protects you at runtime.

Key Takeaway: By integrating Zod schemas as input validators, tRPC ensures that TypeScript's static types and runtime validation stay perfectly synchronized, eliminating the gap where type assertions usually lie.