Input Validation with Zod Schemas
What you'll learn: How to use Zod schemas to automatically generate TypeScript types AND validate runtime data in tRPC procedures, guaranteeing type safety from client to server.
The Double Safety Problem
You've seen how tRPC gives you type-safe procedures, but there's still a critical gap: how do you ensure the runtime data coming from clients actually matches the types? TypeScript types disappear at runtime—someone could send malformed JSON, wrong data types, or malicious input.
Zod schemas solve this by acting as a single source of truth: they validate the actual data at runtime AND generate the TypeScript types automatically.
Zod Schemas as Input Guards
When defining a tRPC procedure, you use .input() with a Zod schema:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const userInputSchema = z.object({
email: z.string().email(),
age: z.number().min(18),
});
const createUser = publicProcedure
.input(userInputSchema)
.mutation(({ input }) => {
// input is automatically typed as:
// { email: string; age: number; }
// AND validated at runtime!
return { id: 1, ...input };
});
What Happens Under the Hood
-
Runtime validation: When a client calls this procedure, Zod checks the actual data matches the schema. If not, tRPC throws an error before your code runs.
-
Automatic typing: TypeScript infers the
inputparameter's type from the schema usingz.infer<typeof userInputSchema>. You never write the type twice. -
Client-side types: The tRPC client automatically knows what shape of data to send, with full autocomplete.
The Single Source of Truth Advantage
Instead of maintaining separate runtime validators and TypeScript types, the Zod schema defines both. Change the schema once, and both type-checking and validation update together—no drift, no duplication.
Key Takeaway: Zod schemas in tRPC procedures bridge the gap between compile-time types and runtime validation, ensuring data correctness at the boundary where client meets server through a single, unified definition.