Skip to main content

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
import type { AppRouter } from '../path/to/server/trpc';

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
// pages/index.tsx
import type { AppRouter } from '../path/to/server/trpc';
import { createTRPCClient } from '@trpc/client';

const client = createTRPCClient<AppRouter>({
url: 'http://localhost:5000/trpc',
});

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

client.ts
const bilbo = await client.query('getUser', 'id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };

const frodo = await client.mutation('createUser', { name: 'Frodo' });
// => { id: 'id_frodo', name: 'Frodo' };