Zod Schema Integration for Runtime Validation
What you'll learn: How to use Zod schemas in tRPC input validation and let TypeScript automatically infer types from those schemas, eliminating duplication between runtime checks and compile-time types.
The Single Source of Truth Principle
In tRPC, Zod schemas serve a dual purpose: they validate data at runtime and generate TypeScript types at compile time. This means you write your data structure once (as a Zod schema), and both your runtime validation and your TypeScript types flow from that single definition.
import { z } from 'zod';
// Define the schema once
const userInputSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().optional(),
});
// TypeScript automatically infers this type:
type UserInput = z.infer<typeof userInputSchema>;
// Equivalent to:
// type UserInput = {
// name: string;
// email: string;
// age?: number | undefined;
// }
How tRPC Uses Zod Schemas
When you define a tRPC procedure with .input(), you pass a Zod schema. tRPC uses this schema to validate incoming data at runtime, and TypeScript infers the types for your procedure's context:
import { router, publicProcedure } from './trpc';
import { z } from 'zod';
const appRouter = router({
createUser: publicProcedure
.input(z.object({
name: z.string(),
email: z.string().email(),
}))
.mutation((opts) => {
// opts.input is automatically typed as { name: string; email: string }
const { name, email } = opts.input;
// Runtime validation already happened - invalid data never reaches here
return { id: 1, name, email };
}),
});
From Schema to Type: The Inference Flow
The magic happens through z.infer<typeof schema>. TypeScript reads the Zod schema's structure and builds a matching type:
const productSchema = z.object({
id: z.number(),
title: z.string(),
inStock: z.boolean(),
tags: z.array(z.string()),
});
// TypeScript infers:
type Product = z.infer<typeof productSchema>;
// {
// id: number;
// title: string;
// inStock: boolean;
// tags: string[];
// }
This inference respects all Zod modifiers: .optional() makes properties optional, .nullable() adds | null, .default() makes properties optional with a fallback, and so on.
Why This Matters in tRPC
Without Zod integration, you'd write types manually and add runtime validation separately. With Zod, tRPC knows both the expected type and how to validate it from a single schema. When the schema changes, both your types and validation update automatically—no duplication, no drift between compile-time and runtime behavior.
Key Takeaway: Zod schemas in tRPC provide runtime validation while TypeScript automatically infers static types from those same schemas using z.infer, creating a single source of truth for both compile-time and runtime data guarantees.