Vanilla client

The magic of tRPC is making strongly typed API calls without relying on code generation. With full-stack TypeScript projects, you can directly import types from the server into the client! This is a vital part of how tRPC works.

Import the AppRouter type into your client from the file your root tRPC router is defined. This single type represents the type signature of your entire API.

client.ts

  1. import type { AppRouter } from '../path/to/server/trpc.ts';

The import type keywords let you import from any TypeScript file on your filesystem. Plus import type can only import types, NOT code. So there’s no danger of accidentally importing server-side code into your client. All calls to import type are always fully erased from your compiled JavaScript bundle (source).

Initialize a tRPC client

Create a typesafe client with the createTRPCClient method from @trpc/client:

client.ts

  1. // pages/index.tsx
  2. import type { AppRouter } from '../path/to/server/trpc.ts';
  3. import { createTRPCClient } from '@trpc/client';
  4. const client = createTRPCClient<AppRouter>({
  5. url: 'http://localhost:5000/trpc',
  6. });

As you can see, we passed AppRouter as a type argument of createTRPCClient. This returns a strongly typed client instance:

client.ts

  1. const bilbo = await client.query('getUser', 'id_bilbo');
  2. // => { id: 'id_bilbo', name: 'Bilbo' };
  3. const frodo = await client.mutation('createUser', { name: 'Frodo' });
  4. // => { id: 'id_frodo', name: 'Frodo' };