Quickstart

tip

We highly encourage you to check out the Example Apps to get a feel of tRPC and getting up & running as seamless as possible.

Installation

⚠️ 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 react-query

For generating a powerful set of React hooks for querying your tRPC API. Powered by react-query.

npm install @trpc/next

A set of utilies for integrating tRPC with Next.js.

Installation Snippets

npm:

  1. npm install @trpc/server @trpc/client @trpc/react react-query @trpc/next

yarn:

  1. yarn add @trpc/server @trpc/client @trpc/react react-query @trpc/next

Defining a router

Let’s walk through the steps of building a typesafe API with tRPC. To start, this API will only contain two endpoints:

  1. getUser(id: string) => { id: string; name: string; }
  2. createUser(data: {name:string}) => { id: string; name: string; }

Create a router instance

First we define a router somewhere in our server codebase:

server.ts

  1. import * as trpc from '@trpc/server';
  2. const appRouter = trpc.router();
  3. // only export *type signature* of router!
  4. // to avoid accidentally importing your API
  5. // into client-side code
  6. export type AppRouter = typeof appRouter;

Add a query endpoint

Use the .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, Superstruct or Yup schema.
  • params.resolve: This is the actual implementation of the endpoint. It’s a function with a single req argument. The validated input is passed into req.input and the context is in req.ctx (more about context later!)

server.ts

  1. import * as trpc from '@trpc/server';
  2. const appRouter = trpc.router().query('getUser', {
  3. input: (val: unknown) => {
  4. if (typeof val === 'string') return val;
  5. throw new Error(`Invalid input: ${typeof val}`);
  6. },
  7. async resolve(req) {
  8. req.input; // string
  9. return { id: req.input, name: 'Bilbo' };
  10. },
  11. });
  12. export type AppRouter = typeof appRouter;

Add a mutation endpoint

Similarly to GraphQL, tRPC makes a distinction between query and mutation endpoints. Let’s add a createUser mutation:

  1. createUser(payload: {name: string}) => {id: string; name: string};

server.ts

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. const appRouter = trpc
  4. .router()
  5. .query('getUser', {
  6. input: (val: unknown) => {
  7. if (typeof val === 'string') return val;
  8. throw new Error(`Invalid input: ${typeof val}`);
  9. },
  10. async resolve(req) {
  11. req.input; // string
  12. return { id: req.input, name: 'Bilbo' };
  13. },
  14. })
  15. .mutation('createUser', {
  16. // validate input with Zod
  17. input: z.object({ name: z.string().min(5) }),
  18. async resolve(req) {
  19. // use your ORM of choice
  20. return await UserModel.create({
  21. data: req.input,
  22. });
  23. },
  24. });
  25. export type AppRouter = typeof appRouter;

Next steps

tRPC includes more sophisticated client-side tooling designed for React projects generally and Next.js specifically. Read the appropriate guide next: