tRPC

On this page 7

tRPC is an open-source TypeScript framework for building end-to-end type-safe APIs, in which a client calls server functions, called procedures, and receives their input and output types directly from the server code. Among APIs in programming, it stands out because it needs no schema language, no code generation step and no separate contract file: the TypeScript compiler itself enforces the contract between client and server.

The name stands for TypeScript Remote Procedure Call. tRPC is most popular in full-stack projects where frontend and backend share one codebase, typically a monorepo built with React, Next.js or a similar framework, and it is usually compared with REST API designs, GraphQL and gRPC.

How tRPC shares types between server and client

On the server, developers define a router that groups named procedures. Each procedure declares an input validator, most often a Zod schema, and a resolver function that returns data. The router’s TypeScript type is then exported as a type only, so no server code ships to the browser.

The client imports that type and creates a proxy client that mirrors the router structure. A call such as trpc.user.byId.query({ id: 42 }) is checked at compile time: a misspelled procedure name, a missing field or a wrong argument type produces an editor error before the code runs. At runtime, the proxy translates the call into an ordinary HTTP request.

The table below lists the building blocks that appear in almost every tRPC application.

Building blockPurposeTypical example
RouterGroups related proceduresA user router with profile operations
ProcedureA single callable server functionA user lookup by identifier
Input validatorChecks and types incoming dataA Zod object schema
ContextPer-request data for every procedureSession, database client, headers
MiddlewareRuns logic before proceduresAuthentication or logging
AdapterConnects tRPC to a server runtimeNext.js, Express, Fastify, Fetch API
Core building blocks of tRPC

Procedure types and the transport layer

tRPC distinguishes three kinds of procedures. Queries read data and map to HTTP GET requests, mutations change data and map to HTTP POST requests, and subscriptions deliver a stream of events over WebSockets or server-sent events. This split lets caching layers treat reads and writes differently.

The wire format is plain JSON over HTTP, optionally extended with a transformer such as SuperJSON so that dates, maps and sets survive serialization. Client-side links form a chain that decides how requests travel, including batching several calls into one HTTP request.

Procedure typePurposeDefault transport
QueryRead data without side effectsHTTP GET
MutationCreate, update or delete dataHTTP POST
SubscriptionPush real-time events to the clientWebSocket or server-sent events
tRPC procedure types

Because the wire protocol is not a published standard like JSON-RPC, third parties can call tRPC endpoints only by reproducing its URL and payload conventions. The protocol is simple, but it is an internal convention rather than a public contract.

tRPC compared with REST, GraphQL and gRPC

tRPC solves the same problem as other API styles, which is moving typed data between client and server, but it makes different trade-offs about language coupling. REST and GraphQL are language-neutral; tRPC deliberately assumes that both ends are written in TypeScript.

CriteriontRPCREST APIGraphQLgRPC
Contract sourceTypeScript typesOpenAPI document (optional)GraphQL schemaProtocol Buffers file
Code generationNoneOptionalUsually required for typesRequired
Client languagesTypeScript onlyAnyAnyMany
Wire formatJSON over HTTPUsually JSONJSONBinary over HTTP/2
Best fitFull-stack TypeScript appsPublic APIsFlexible client queriesService-to-service calls
API styles compared

In short, tRPC gives the fastest feedback loop when one team owns both ends of the connection. GraphQL is stronger when many clients need to shape their own queries, and gRPC is stronger for high-throughput internal services written in different languages.

When to choose tRPC and when to avoid it

tRPC is the right choice when the frontend and backend live in the same repository and are written in TypeScript. Renaming a field on the server immediately marks every affected client call as an error, which removes a whole category of integration bugs and makes refactoring safe.

SituationRecommendationReason
Full-stack TypeScript monorepoUse tRPCShared types with zero tooling
Public API for external developersPrefer REST or GraphQLClients need a language-neutral contract
Native mobile apps in Swift or KotlinAvoid tRPCClients cannot consume TypeScript types
Polyglot microservicesPrefer gRPCGenerated clients in many languages
Small team prototyping quicklyUse tRPCMinimal setup and fast iteration
Decision guide for tRPC

A common middle path is to keep tRPC for the internal web client and expose a separate REST layer for partners. Community packages can generate an OpenAPI document from tRPC routers, but this adds maintenance and partly cancels the zero-tooling advantage.

Limitations and common mistakes

The central limitation is tight coupling. Because the client depends on server types, the two must usually be deployed together, and API versioning is not built in. A mobile app already installed on phones may call an older procedure signature, so breaking changes need the same care as in any other API.

  • Skipping runtime validation: TypeScript types disappear at runtime, so every procedure still needs an input validator to reject malformed requests.
  • Leaking server code: importing the router as a value instead of a type can pull server modules into the browser bundle.
  • Oversized routers: a single router with hundreds of procedures slows the TypeScript compiler and editor feedback.
  • Ignoring authorization: procedures are public HTTP endpoints, so protected procedures need middleware that checks the session.

The type safety of tRPC is therefore a development-time guarantee, not a security boundary. Validation, authentication and rate limiting remain the responsibility of the server, exactly as with any HTTP API.

The simple explanation

tRPC lets the part of an app that runs in the browser call functions on the server as if they were local. The developer writes a function on the server, and the browser code can use it right away.

The clever part is that the code editor already knows what each function expects and returns. If someone changes the server function, the editor points out every place that now breaks, long before a user sees an error. It works best when the same team writes both sides in the same language.

How it is used in practice

A three-person team builds an internal booking tool for a chain of physiotherapy clinics with Next.js and a PostgreSQL database. They define about 40 tRPC procedures, such as listing free appointment slots, creating a booking and canceling it, each validated with a Zod schema and protected by an authentication middleware.

Midway through the project, the clinics ask to store appointment duration in minutes instead of as a start and end time. A developer changes the server procedure, and the TypeScript compiler immediately flags 17 client call sites that need updating. All of them are fixed in one afternoon, and the change ships without a single runtime integration bug, something that previously required manual testing against a REST API.