0Pricing
React Academy · Lesson

Setting Up tRPC with React and Next.js

Configure a tRPC router, procedures, and the React client adapter in a Next.js App Router project.

Setting Up tRPC with React and Next.js is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Installing tRPC Dependencies

Install @trpc/server and @trpc/client for the core tRPC packages. Add @trpc/react-query for the React hooks adapter and @tanstack/react-query as the peer dependency that powers the hooks.

For Next.js API route integration, no additional adapter package is needed in recent versions of tRPC.

Initializing tRPC on the Server

Create a server/trpc.ts file and call initTRPC.create() to get the t object. Export t.router as router, t.procedure as publicProcedure, and t.mergeRouters as a utility.

The initTRPC factory accepts a context type generic that defines what data is available in every procedure's ctx argument.

Defining Your First Procedure

A procedure is defined by chaining .input(zodSchema).query(handler) or .mutation(handler) onto publicProcedure. For a simple hello endpoint: publicProcedure.input(z.object({ name: z.string() })).query(({ input }) => "Hello " + input.name).

The Zod schema provides both TypeScript types and runtime validation for the input.

Building the App Router

Create an appRouter using the router() function: router({ hello: helloHandler, users: usersRouter }). Nested routers allow you to organize procedures by domain (users, posts, comments) into separate files.

Export the AppRouter type: export type AppRouter = typeof appRouter. This type is what the client will import.

Next.js API Route Handler

Create app/api/trpc/[trpc]/route.ts (App Router) or pages/api/trpc/[trpc].ts (Pages Router). Use fetchRequestHandler from @trpc/server/adapters/fetch to handle all tRPC requests through this single catch-all route.

Pass the router, createContext function, and the request/response objects to fetchRequestHandler.

Creating the tRPC Client for React

Create a utils/trpc.ts file. Call createTRPCReact() to create the typed trpc client object. This object has a property for every procedure in your router, each exposing React Query hooks.

The AppRouter type import is from your server file; TypeScript follows the import chain to validate all usages.

QueryClient and TRPCProvider Setup

In your app layout or _app.tsx, create a QueryClient instance and a tRPC client instance using trpc.createClient({ links: [httpBatchLink({ url: '/api/trpc' })] }).

Wrap your component tree in both trpc.Provider (with the trpc client) and QueryClientProvider (with the QueryClient). Both providers are required.

Making Your First tRPC Query

In any component: const { data, isLoading, error } = trpc.hello.useQuery({ name: 'World' }). The hook is fully typed: data is the inferred return type of the hello procedure, and the input object is type-checked against the Zod schema.

Passing an incorrect input type is a TypeScript compile error, not a runtime error.

TypeScript Project References

For tRPC to work, the client must be able to import types from the server file. In a Next.js project, the server and client code share the same TypeScript compilation, so imports just work.

In a monorepo with separate packages, configure TypeScript project references or path aliases in tsconfig.json to point to the server package.

Environment Differences

The tRPC handler runs on the server (as a Next.js API route or Edge Function). The tRPC client runs in the browser. TypeScript evaluates type-level imports at build time without executing server code in the browser.

Only the AppRouter type is imported on the client, not the actual implementation, so no server secrets leak to the client bundle.

Testing the Setup

Start the Next.js dev server and open the browser console. The trpc.hello.useQuery call should log the server response. Check the Network tab to see the HTTP request to /api/trpc/hello with the input batched as a query parameter.

The default httpBatchLink combines multiple concurrent requests into one HTTP call, visible in the network waterfall.

tRPC Server Router Setup

Which function initializes the tRPC instance and provides the router and procedure factories?

Lesson Recap

Install @trpc/server, @trpc/client, @trpc/react-query, and @tanstack/react-query. Initialize tRPC with initTRPC.create(), define procedures, export the AppRouter type. Create the Next.js API catch-all route, set up TRPCProvider and QueryClientProvider, then call procedures with trpc.procedureName.useQuery().

TypeScript enforces the entire client-server contract at compile time with no code generation.

Frequently asked questions

Is the “Setting Up tRPC with React and Next.js” lesson free?

Yes — the full text of “Setting Up tRPC with React and Next.js” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Setting Up tRPC with React and Next.js”?

Configure a tRPC router, procedures, and the React client adapter in a Next.js App Router project. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Setting Up tRPC with React and Next.js” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Problem tRPC Solves
  2. Setting Up tRPC with React and Next.js
  3. Queries, Mutations, and Subscriptions
  4. Integrating tRPC with React Query and Auth
← Back to React Academy