Course contentsShow
← React
Lesson 1814 of 2,39642. Data Fetching LibrariesFree lesson

Creating a tRPC Router on the Server

Defining procedures with .query() and .mutation() methods; exporting the AppRouter type for client-side inference.

Creating a tRPC Router on the Server

You'll learn how to define your API contract on the server by creating procedures that automatically generate full TypeScript types for your React frontend.

The Core Idea

A tRPC router is where you define all your API endpoints (called "procedures") on the server. Think of it as your API's blueprint—you declare what queries (reads) and mutations (writes) are available, and tRPC automatically generates TypeScript types that your client can import. No manual API documentation or type-syncing needed!

Defining Procedures

You create procedures using two methods:

  • .query() — for data fetching operations (like GET requests)
  • .mutation() — for data modifications (like POST/PUT/DELETE)
import { initTRPC } from '@trpc/server';

const t = initTRPC.create();

export const appRouter = t.router({
  getUser: t.procedure.query(() => {
    return { id: 1, name: 'Alice' };
  }),
  
  createUser: t.procedure.mutation(() => {
    // Save user logic here
    return { id: 2, name: 'Bob' };
  }),
});

The Magic: Exporting AppRouter Type

The crucial step is exporting your router's type:

export type AppRouter = typeof appRouter;

This AppRouter type is what you'll import in your React client. It contains the complete shape of every procedure—inputs, outputs, everything. Your frontend now "knows" your API structure at compile time, giving you autocomplete and type-checking across the network boundary.

Think of it like sharing a contract: the server writes it once, and the client reads the exact same document—no telephone game, no drift.

Key Takeaway: Create your tRPC router by defining .query() and .mutation() procedures, then export the AppRouter type so your React client can infer all API shapes automatically—achieving true end-to-end type safety.