TRPC Zod Procedure Input Validation

Define typed RPC procedures with tRPC and Zod input schemas, sharing inferred types end to end without a schema registry or codegen step.

TypescriptData Fetching

Code

typescriptsnippet
40 lines
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
import { createHTTPContext } from './context';

const t = initTRPC.context<typeof createHTTPContext>().create();

const publicProcedure = t.procedure;
const router = t.router;

const postRouter = router({
  byId: publicProcedure
    .input(z.object({ id: z.string().uuid() }))
    .query(async ({ input, ctx }) => {
      return ctx.db.posts.find((p) => p.id === input.id) ?? null;
    }),

  list: publicProcedure
    .input(z.object({
      page: z.number().int().min(1).default(1),
      limit: z.number().int().min(1).max(50).default(20),
    }))
    .query(async ({ input, ctx }) => {
      const start = (input.page - 1) * input.limit;
      return ctx.db.posts.slice(start, start + input.limit);
    }),

  create: publicProcedure
    .input(z.object({
      title: z.string().min(3).max(120),
      body: z.string().min(1),
    }))
    .mutation(async ({ input, ctx }) => {
      const post = { id: crypto.randomUUID(), ...input };
      ctx.db.posts.push(post);
      return post;
    }),
});

export const appRouter = router({ posts: postRouter });
export type AppRouter = typeof appRouter;

How it works

The working surface is the function start — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. initTRPC, z, createHTTPContext are the only symbols borrowed from @trpc/server — the coupling is explicit and narrow.

What to watch for

  • Dependency check: @trpc/server and zod — not built-in, must be present in the project.
  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

Entry signature: export const appRouter =

The surface worth importing is appRouter; the helpers around it are private to the snippet.

Core lines

return ctx.db.posts.find((p) => p.id === input.id) ?? null;
return ctx.db.posts.slice(start, start + input.limit);
.mutation(async ({ input, ctx }) => {
const post = { id: crypto.randomUUID(), ...input };
ctx.db.posts.push(post);
return post;
}),

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`@trpc/server` and `zod` — install them with the package manager before running.