Course contentsShow
← React
Lesson 1817 of 2,39642. Data Fetching LibrariesFree lesson

Input Validation with Zod Schemas

Defining procedure inputs with .input(z.object({...})); getting automatic type safety and runtime validation on the server.

Input Validation with Zod Schemas

You'll learn how defining procedure inputs with .input(z.object({...})) gives you automatic type safety and runtime validation on the server.

The Type Safety + Runtime Safety Combo

When you create a tRPC procedure, you can specify exactly what data shape you expect by attaching a Zod schema with .input(). This does two magical things at once: TypeScript knows the exact shape of your input (compile-time safety), and tRPC validates incoming data against that schema at runtime (runtime safety). If a client sends invalid data, the procedure won't even execute—tRPC throws an error automatically.

How It Works

On your server router, you define a procedure like this:

import { z } from 'zod';
import { router, publicProcedure } from './trpc';

export const appRouter = router({
  createPost: publicProcedure
    .input(z.object({
      title: z.string().min(1).max(100),
      content: z.string(),
      published: z.boolean().optional(),
    }))
    .mutation(({ input }) => {
      // input is fully typed: { title: string; content: string; published?: boolean }
      // AND validated: if client sent { title: 123 }, this never runs
      return db.posts.create(input);
    }),
});

On the client, when you call createPost.mutate({ title, content }), TypeScript enforces the correct shape, and the server validates it before executing your logic. Wrong types? TypeScript error. Wrong values at runtime? tRPC error. No manual validation code needed.

The Developer Experience Win

This pattern means you write the schema once, and both your client and server stay in sync with zero boilerplate. No more if (!title || typeof title !== 'string') checks scattered everywhere.

Key Takeaway: Using .input(z.object({...})) in tRPC procedures gives you compile-time type safety and automatic runtime validation, eliminating manual input checking and keeping client-server contracts bulletproof.