If you prefer to jump into some complete example projects, check out the Example Apps.
⚠️ Requirements: tRPC requires TypeScript > 4.1 as it relies on Template Literal Types.
npm install @trpc/server
For implementing tRPC endpoints and routers. Install in your server codebase.
npm install @trpc/client
For making typesafe API calls from your client. Install in your client codebase.
npm install @trpc/react
For generating a powerful set of React hooks for querying your tRPC API. Recommended for non-Next.js React projects. Powered by react-query.
npm install @trpc/next
A set of utilies for integrating tRPC with Next.js.
Let's walk through the steps of building a typesafe API with tRPC. To start, this API will only contain two endpoints:
First we define a router somewhere in our server codebase:
.query() method to add a query endpoint to the router. Arguments:
.query(name: string, params: QueryParams)
name: string: The name of this endpoint
params.input: Optional. This should be a function that validates/casts the input of this endpoint and either returns a strongly typed value (if valid) or throws an error (if invalid). Alternatively you can pass a Zod or Yup schema.
params.resolve: This is the actual implementation of the endpoint. It's a function with a single
reqargument. The validated input is passed into
req.inputand the context is in
req.ctx(more about context later!)
Similarly to GraphQL, tRPC makes a distinction between query and mutation endpoints. Let's add a
tRPC includes more sophisticated client-side tooling designed for React projects generally and Next.js specifically. Read the appropriate guide next: