Quickstart
We highly encourage you to check out the example apps to learn about how tRPC is installed in your favorite framework.
Installation
⚠️ Requirements: tRPC requires TypeScript > 4.1 as it relies on Template Literal Types.
tRPC is broken up into several packages so you can install only what you need. Make sure to install the packages you want in the proper sections of your codebase.
Purpose | Location | Install command |
---|---|---|
Implement endpoints and routers | Server | npm install @trpc/server |
Call procedures on client | Client | npm install @trpc/client @trpc/server |
React hooks powered by @tanstack/react-query | Client | npm install @trpc/react-query @tanstack/react-query |
Next.js integration utilities | Next.js | npm install @trpc/next |
Installation Snippets
Here are some install scripts to add tRPC to your project. These scripts include every @trpc/*
package so feel free to remove what you don't need!
- npm
- yarn
- pnpm
bash
npm install @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
bash
npm install @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
sh
yarn add @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
sh
yarn add @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
sh
pnpm add @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
sh
pnpm add @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query
Defining a backend router
Let's walk through the steps of building a typesafe API with tRPC. To start, this API will only contain two endpoints with these TypeScript signatures:
ts
userById(id: string) => { id: string; name: string; }userCreate(data: { name: string }) => { id: string; name: string; }
ts
userById(id: string) => { id: string; name: string; }userCreate(data: { name: string }) => { id: string; name: string; }
Create a router instance
First, let's define an empty router in our server codebase:
server.tsts
import {initTRPC } from '@trpc/server';constt =initTRPC .create ();constappRouter =t .router ({});// Export type router type signature,// NOT the router itself.export typeAppRouter = typeofappRouter ;
server.tsts
import {initTRPC } from '@trpc/server';constt =initTRPC .create ();constappRouter =t .router ({});// Export type router type signature,// NOT the router itself.export typeAppRouter = typeofappRouter ;
Add a query procedure
Use t.procedure.query()
to add a query procedure/endpoint to the router. The two methods on this procedure are:
input
(optional): When provided, this should be a function that validates and casts the input of this procedure. It should return a strongly typed value when the input is valid or throw an error if the input is invalid. We recommend using a TypeScript validation library like Zod, Superstruct or Yup for input validation.query
: This is the implementation of the procedure (a "resolver"). It's a function with a singlereq
argument to represent the incoming request. The validated (and strongly typed!) input is passed intoreq.input
.
The following creates a query procedure called userById
that takes a single string argument and returns a user object:
server.tsts
// @filename: server.tsimport {initTRPC } from '@trpc/server';import {z } from 'zod';constt =initTRPC .create ();interfaceUser {id : string;name : string;}constuserList :User [] = [{id : '1',name : 'KATT',},];constappRouter =t .router ({userById :t .procedure // The input is unknown at this time.// A client could have sent us anything// so we won't assume a certain data type..input ((val : unknown) => {// If the value is of type string, return it.// TypeScript now knows that this value is a string.if (typeofval === 'string') returnval ;// Uh oh, looks like that input wasn't a string.// We will throw an error instead of running the procedure.throw newError (`Invalid input: ${typeofval }`);}).query ((req ) => {const {input } =req ;constuser =userList .find ((u ) =>u .id ===input );returnuser ;}),});export typeAppRouter = typeofappRouter ;
server.tsts
// @filename: server.tsimport {initTRPC } from '@trpc/server';import {z } from 'zod';constt =initTRPC .create ();interfaceUser {id : string;name : string;}constuserList :User [] = [{id : '1',name : 'KATT',},];constappRouter =t .router ({userById :t .procedure // The input is unknown at this time.// A client could have sent us anything// so we won't assume a certain data type..input ((val : unknown) => {// If the value is of type string, return it.// TypeScript now knows that this value is a string.if (typeofval === 'string') returnval ;// Uh oh, looks like that input wasn't a string.// We will throw an error instead of running the procedure.throw newError (`Invalid input: ${typeofval }`);}).query ((req ) => {const {input } =req ;constuser =userList .find ((u ) =>u .id ===input );returnuser ;}),});export typeAppRouter = typeofappRouter ;
Add a mutation procedure
Similar to GraphQL, tRPC makes a distinction between query and mutation procedures.
The way a procedure works on the server doesn't change much between query and mutation. The method name is different and the way that the client will use this procedure changes - but everything else is the same!
Let's add a userCreate
mutation by adding it as a new property on our router object:
server.tsts
// @filename: server.tsimport {initTRPC } from '@trpc/server';import {z } from 'zod';constt =initTRPC .create ();interfaceUser {id : string;name : string;}constuserList :User [] = [{id : '1',name : 'KATT',},];constappRouter =t .router ({userById :t .procedure .input ((val : unknown) => {if (typeofval === 'string') returnval ;throw newError (`Invalid input: ${typeofval }`);}).query ((req ) => {constinput =req .input ;constuser =userList .find ((it ) =>it .id ===input );returnuser ;}),userCreate :t .procedure .input (z .object ({name :z .string () })).mutation ((req ) => {constid = `${Math .random ()}`;constuser :User = {id ,name :req .input .name ,};userList .push (user );returnuser ;}),});export typeAppRouter = typeofappRouter ;
server.tsts
// @filename: server.tsimport {initTRPC } from '@trpc/server';import {z } from 'zod';constt =initTRPC .create ();interfaceUser {id : string;name : string;}constuserList :User [] = [{id : '1',name : 'KATT',},];constappRouter =t .router ({userById :t .procedure .input ((val : unknown) => {if (typeofval === 'string') returnval ;throw newError (`Invalid input: ${typeofval }`);}).query ((req ) => {constinput =req .input ;constuser =userList .find ((it ) =>it .id ===input );returnuser ;}),userCreate :t .procedure .input (z .object ({name :z .string () })).mutation ((req ) => {constid = `${Math .random ()}`;constuser :User = {id ,name :req .input .name ,};userList .push (user );returnuser ;}),});export typeAppRouter = typeofappRouter ;
Using your new backend on the client
Let's now move to your frontend code and embrace the power of end-to-end typesafety. When we import the AppRouter
type for the client to use, we have achieved full typesafety for our system.
Setup the tRPC Client
client.tsts
// @filename: client.tsimport {createTRPCProxyClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';// Notice the <AppRouter> generic here.consttrpc =createTRPCProxyClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',}),],});
client.tsts
// @filename: client.tsimport {createTRPCProxyClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';// Notice the <AppRouter> generic here.consttrpc =createTRPCProxyClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000/trpc',}),],});
Querying & mutating
You now have access to your API procedures on the trpc
object. Try it out!
client.tsts
// Inferred typesconstuser = awaittrpc .userById .query ('1');constcreatedUser = awaittrpc .userCreate .mutate ({name : 'sachinraja' });
client.tsts
// Inferred typesconstuser = awaittrpc .userById .query ('1');constcreatedUser = awaittrpc .userCreate .mutate ({name : 'sachinraja' });
Full autocompletion
You can open up your Intellisense to explore your API on your frontend. You'll find all of your procedure routes waiting for you along with the methods for calling them.
client.tsts
// Full autocompletion on your routestrpc .u ;
client.tsts
// Full autocompletion on your routestrpc .u ;
Next steps
tRPC includes more sophisticated client-side tooling designed for React projects and Next.js.