Set up a tRPC Client
1. Install the tRPC Client library
Use your preferred package manager to install the @trpc/client
library, and also install @trpc/server
which contains some required types.
- npm
- yarn
- pnpm
bash
npm install @trpc/client @trpc/server
bash
npm install @trpc/client @trpc/server
bash
yarn add @trpc/client @trpc/server
bash
yarn add @trpc/client @trpc/server
bash
pnpm add @trpc/client @trpc/server
bash
pnpm add @trpc/client @trpc/server
2. Import your App Router
Import your AppRouter
type into the client application. This type holds the shape of your entire API.
ts
import type {AppRouter } from '../server/router';
ts
import type {AppRouter } from '../server/router';
By using import type
you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, see the Typescript docs.
3. Initialize the tRPC client
Create a tRPC client with the createTRPCProxyClient
method, and add a links
array with a terminating link pointing at your API. To learn more about tRPC links, click here.
client.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
client.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
4. Use the tRPC Client
Under the hood this creates a typed JavaScript Proxy which allows you to interact with your tRPC API in a fully type-safe way:
client.tsts
const bilbo = await client.getUser.query('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };const frodo = await client.createUser.mutate({ name: 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
client.tsts
const bilbo = await client.getUser.query('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };const frodo = await client.createUser.mutate({ name: 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
You're all set!