tRPC Input and Output Validation with Zod
On this page
Types don't protect you at run time
On Day 2 the client couldn't send { nam: 'Ada' } because TypeScript stopped it. But TypeScript only checks code you compile. Anyone can send any JSON to your server with curl, an old client version, or a script. If a procedure trusted its types, a request with title: 42 would sail straight into your database.
That's why tRPC procedures take a validator. It does two jobs at once: it checks the input at run time, and its type becomes the procedure's input type for the client. One definition, no drift.
Write input schemas with Zod
Here's the TaskBoard create procedure with a realistic schema:
import { z } from 'zod';
const CreateTask = z.object({
title: z.string().trim().min(1, 'Title is required').max(100),
priority: z.enum(['low', 'normal', 'high']).default('normal'),
due: z.iso.date().optional(), // "2026-11-30"
tags: z.array(z.string()).max(5).default([]),
});
export const taskRouter = router({
create: publicProcedure
.input(CreateTask)
.mutation(({ input }) => {
// input.priority is 'low' | 'normal' | 'high', never undefined
// input.title has already been trimmed
return saveTask(input);
}),
});A few things are happening here:
.trim()changes the value, so' Plan sprint 'reaches your code as'Plan sprint'..default('normal')makespriorityoptional for the caller but always present inside the procedure.- The custom message
'Title is required'is what the client will show.
tRPC infers *two* types from the schema. The client sees the input type, where priority and tags are optional. Your procedure sees the output type of the schema, where defaults are filled in. You get both for free.
What a validation failure looks like
When validation fails, tRPC rejects the call with the error code BAD_REQUEST (HTTP 400) before your code runs. The original ZodError is kept as the error's cause:
try {
await caller.create({ title: ' ', priority: 'urgent' });
} catch (e) {
console.log(e.code); // BAD_REQUEST
console.log(z.flattenError(e.cause).fieldErrors);
}
// {
// title: [ 'Title is required' ],
// priority: [ 'Invalid option: expected one of "low"|"normal"|"high"' ]
// }z.flattenError is Zod 4's helper for turning issues into a field-to-messages map, which is exactly what a form needs. On Day 5 you'll send that map to the client in a clean shape.
Validate output too, when it matters
You can also attach an output schema. tRPC checks the return value against it, and removes any keys the schema doesn't list:
const TaskView = z.object({ id: z.string(), title: z.string(), priority: z.enum(['low', 'normal', 'high']) });
const create = publicProcedure
.input(CreateTask)
.output(TaskView)
.mutation(({ input }) => ({ id: 't1', ...input, secretNote: 'internal' }));
// result: { id: 't1', title: 'Plan sprint', priority: 'normal' }The secretNote field never leaves the server, and tags is gone too. This makes output schemas a useful safety net when a procedure returns database rows that may contain columns the client should never see, like password hashes or internal notes.
If your code returns something that *doesn't* match the output schema, the client gets INTERNAL_SERVER_ERROR with the message Output validation failed. That's correct: it's a server bug, not a client mistake.
Output validation costs a little CPU on every call, so you don't need it everywhere. Use it on procedures that return data from storage or from other services, where a surprise field could leak.
Inputs without objects
Inputs don't have to be objects. z.string() or z.number() work fine. But objects are easier to extend later without breaking clients, so prefer { id } over a bare id.
For a procedure where the whole input is optional, give the object a default so callers can skip it entirely:
const list = publicProcedure
.input(z.object({ limit: z.number().int().min(1).max(50).default(10) }).default({ limit: 10 }))
.query(({ input }) => input.limit);
await caller.list(); // 10
await caller.list({ limit: 3 }); // 3Always set a maximum on lists and page sizes. Without .max(50) a single caller can ask for a million rows.
Not just Zod: Standard Schema
tRPC 11 accepts any validator that implements Standard Schema, a shared interface supported by Zod, Valibot, ArkType and others. Valibot, which produces smaller browser bundles, works the same way:
import * as v from 'valibot';
const double = publicProcedure
.input(v.object({ n: v.pipe(v.number(), v.minValue(1)) }))
.query(({ input }) => input.n * 2);This course uses Zod because it's the most common choice, but nothing ties you to it.
Read types out of the router
Sometimes you need a procedure's types outside a call, for a form's props or a helper function. tRPC exports two helpers:
import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
import type { AppRouter } from './router';
type RouterInput = inferRouterInputs<AppRouter>;
type RouterOutput = inferRouterOutputs<AppRouter>;
type CreateTaskInput = RouterInput['task']['create']; // priority optional
type TaskView = RouterOutput['task']['create']; // no secretNotePrefer these over writing types by hand. They update automatically when the server changes.
schemas.ts file. The server uses them in .input(), and the client can import the same schema to validate a form before it ever sends a request.Check yourself
Types only check code you compile. Real requests can come from old clients, scripts or attackers, so the server must check the data at run time.
It's optional for the caller, but inside the procedure it's always set, because Zod fills in the default before your code runs.
Add an output schema with .output(...) that lists only the safe fields. tRPC validates the return value against it and strips every key the schema doesn't include, so passwordHash never leaves the server. If the row is missing a required field, the client gets Output validation failed as an internal error, which correctly points at a server bug.
'Plan sprint'. Zod transforms run during validation, so the procedure sees the trimmed value, and a title made only of spaces fails .min(1) with your custom message. Schema transforms are a good place for this kind of normalization because every caller gets it.
The UI isn't the only caller. Anyone can send { limit: 1000000 } straight to the endpoint, and without a maximum one request could load a huge result set and slow the database for everyone. A schema maximum is a cheap guard that applies to every client, old or new.