How-To Guide

How to Implement Type-Safe RPC with tRPC

Share types between a TypeScript server and client with tRPC: routers and procedures, input validation, context and error handling.

On this page

  1. Introduction
  2. Types Inferred, Not Declared
  3. Procedures and Routers
  4. Input Validation and Output Types
  5. Context and Middleware
  6. Error Handling
  7. Batching and Transports
  8. Common Pitfalls and Conclusion

Introduction

A REST or GraphQL API describes its shape in a document or a schema that can drift from the implementation, so the client learns about a mismatch at runtime. tRPC takes a different approach: the server’s procedures are TypeScript functions, and the client’s types are inferred from them, so a call to a renamed or changed procedure is a compile error rather than a production bug. It works because client and server share the code in a TypeScript monorepo, which is exactly the case where the benefit is largest.

Types Inferred, Not Declared

With tRPC, the client does not import a generated API type or a schema; it imports the server’s router type, and TypeScript infers the input and output of every procedure from the server code. Rename a procedure or change an input’s shape and the client’s build fails, which catches the mismatch at compile time.

This removes the drift that a hand-written client type or a schema document allows: there is one source of truth, the server implementation, and the client’s types are derived from it. The cost is that the client must be able to import the server’s type, which means a shared codebase or a published type package.

The inference also flows through generics and middleware, so a procedure that narrows its context type (for example, a protected procedure whose user is non-null) gives the handler and the client a more precise type rather than a broad one. That precision is what makes the compiler catch mistakes a looser type would allow.

// server: the router is the source of truth
import { initTRPC } from '@trpc/server';
import { z } from 'zod';

const t = initTRPC.context<Context>().create();
export const appRouter = t.router({
  getOrder: t.procedure
    .input(z.object({ id: z.string() }))
    .query(({ input }) => db.findOrder(input.id)),   // output type inferred
});
export type AppRouter = typeof appRouter;             // imported by the client

Procedures and Routers

A procedure is a typed function with an input schema; a router groups procedures under namespaces. Queries read, mutations write, and subscriptions stream. The client calls them through the typed proxy, and the input is validated against the schema on the server, so a malformed request is rejected before the handler runs.

Nesting routers into namespaces keeps the API organised: orders.get, orders.create, orders.cancel. The client’s autocomplete and type-checking follow the nesting, so the API is discoverable from the editor without a document to read.

const ordersRouter = t.router({
  get: t.procedure.input(z.object({ id: z.string() })).query(/* ... */),
  create: t.procedure.input(z.object({ items: z.array(z.string()) })).mutation(/* ... */),
});
export const appRouter = t.router({
  orders: ordersRouter,                       // namespaced: client.orders.get(...)
  users: usersRouter,
});
// the client sees orders.get / orders.create with typed inputs and outputs

Input Validation and Output Types

Every procedure declares an input schema, and tRPC validates the request against it before calling the handler, so the handler works with a validated, typed input. The output can also be validated, or left to be inferred; validating the output catches a handler that returns an unexpected shape before it reaches the client.

Input validation is the security and correctness boundary: it rejects malformed or malicious input at the edge of the procedure. Use a schema library (Zod, Valibot) so the same schema gives runtime validation and compile-time types, avoiding a separate type declaration that could drift.

const createOrder = t.procedure
  .input(z.object({
    items: z.array(z.object({ sku: z.string(), qty: z.number().int().positive() })).min(1),
  }))
  .output(z.object({ id: z.string(), totalCents: z.number() }))   // validates output
  .mutation(async ({ input, ctx }) => {
    return ctx.orders.create(input.items);   // input is validated + typed
  });

Context and Middleware

Context carries per-request data such as the authenticated user, the database handle and the request id, injected into every procedure. Middleware wraps procedures for cross-cutting concerns: authentication, logging, rate limiting, so a procedure opts in with .use() rather than repeating the logic.

Authentication as middleware is the common pattern: a middleware that verifies the session and throws if absent, and procedures that require it extend a protected procedure. This centralises the check, so a new procedure is protected by construction rather than by remembering to add the check.

const isAuthed = t.middleware(({ ctx, next }) => {
  if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
  return next({ ctx: { ...ctx, user: ctx.user } });           // narrowed ctx
});
const protectedProcedure = t.procedure.use(isAuthed);         // reusable
// a procedure using protectedProcedure has ctx.user typed as non-null

Error Handling

tRPC uses typed error codes (UNAUTHORIZED, NOT_FOUND, BAD_REQUEST, etc.) with optional data, so the client can branch on the code rather than parse an error message. Throwing a TRPCError with the right code gives the client a structured error it can handle and display correctly.

Validation failures are BAD_REQUEST with the schema issues attached, so the client can show field-level errors without a separate validation pass. This keeps the error path typed end to end, matching the success path.

throw new TRPCError({
  code: 'NOT_FOUND',
  message: 'Order not found',
  cause: { orderId: input.id },           // optional structured data
});
// client:
try { await client.orders.get.query({ id }); }
catch (e) {
  if (e.data?.code === 'NOT_FOUND') showNotFound();   // branch on the code
}

Batching and Transports

tRPC can batch several calls made in the same tick into one HTTP request, which reduces round trips for a page that loads several pieces of data. It runs over HTTP or over a WebSocket for subscriptions, and adapters exist for many frameworks and runtimes, so the transport is configurable.

Because it is a thin RPC layer, not a query language, it does not replace a public API for third parties who do not share the TypeScript code. Use tRPC for your own front end in a monorepo, and a conventional REST or GraphQL API where an unknown client must consume it.

# transports and scope
HTTP        -> queries and mutations (with request batching)
WebSocket   -> subscriptions (streaming)
adapters    -> Next.js, Express, Fastify, fetch, serverless
# scope: tRPC for YOUR TypeScript client in a shared codebase;
# for third-party consumers, expose REST/GraphQL instead

Common Pitfalls and Conclusion

Do not expose tRPC to clients that do not share your TypeScript types; they cannot use it. Do not skip input validation, which is the boundary. Do not repeat auth logic in every procedure; put it in middleware. And do not assume the types replace runtime validation, because the types vanish at runtime.

tRPC gives a TypeScript server and client a shared, inferred API contract so a mismatch is a compile error rather than a runtime bug. Define routers and procedures with validated inputs, carry context and middleware for cross-cutting concerns, use typed errors, batch calls over HTTP or stream over WebSocket, and use it where the client shares the code. Then the API cannot drift from its implementation.

Sources: tRPC: Documentation, tRPC: Procedures, Zod: Schema validation.

FAQ

When is tRPC the wrong choice?
When the client does not share your TypeScript code, such as a third-party consumer or a mobile app in another language. They cannot import the router type, so a REST or GraphQL API with a published schema is the right fit there.
Do the inferred types replace runtime validation?
No. Types vanish at runtime, so a request from over the network could be anything. The input schema is the runtime validation that rejects malformed input; the inferred type is a compile-time convenience on top of it.

Related Examples