How to Use tRPC for End-to-End Type Safety: A Comprehensive Tutorial

Modern web development has long struggled with the disconnect between frontend and backend type systems. Even with TypeScript on both sides, maintaining consistent types across the network boundary often requires manually duplicating interfaces, generating OpenAPI specs, or relying on code generators that add complexity to the build pipeline. This is where tRPC comes in as a radical paradigm shift. tRPC (TypeScript Remote Procedure Call) allows you to build fully typesafe APIs with no code generation, no runtime schema, and no REST endpoints to manage manually. Instead, you simply import functions from your backend into your frontend, and TypeScript ensures that every parameter, response, and error is perfectly aligned. In this comprehensive tutorial, we will walk through everything you need to know to implement tRPC in a real-world application—from initial setup to advanced patterns like middleware, error handling, and subscriptions. By the end, you will understand why tRPC is rapidly becoming the standard for full‑stack TypeScript developers and how you can leverage it for end‑to‑end type safety that eliminates an entire class of runtime bugs.

Article illustration

The core philosophy behind tRPC is simple: treat your backend procedures as if they were local functions. Instead of defining routes and manually serializing JavaScript objects over HTTP, tRPC uses a lightweight server adapter (Express, Fastify, Next.js, etc.) to expose TypeScript functions as callable endpoints. On the client side, the same type definitions are imported directly from a shared package or a monorepo, giving you full autocompletion and compile‑time checking for every API call. This approach not only reduces boilerplate dramatically but also eliminates the need for middleware like Redux Toolkit Query or React Query to manually type responses—tRPC integrates naturally with React Query for caching and revalidation while keeping everything typesafe. In this tutorial, we will assume you are building a Next.js application (the most common tRPC use case), but the principles apply to any Node.js framework. We will cover server setup, router creation, client integration, error handling, and real‑time subscriptions, and we will include practical tables and FAQs to solidify your understanding. Let’s dive in.

What Is tRPC and Why Does End‑to‑End Type Safety Matter?

End‑to‑end type safety means that the types used on the backend (for input validation, database models, and return values) are automatically enforced on the frontend without any additional effort from the developer. In a traditional REST or GraphQL setup, you typically define your types on the backend (e.g., using Zod, Prisma, or TypeScript interfaces) and then manually replicate them on the frontend, often leading to mismatches when the API evolves. GraphQL mitigates this with a schema definition language and code generation, but it still requires a separate schema file and a complex build step. tRPC bypasses this entirely by leveraging TypeScript’s type system across the network. When you define a procedure on the server using .query() or .mutation(), the input and output types are inferred directly from the function signature. The client then imports the router type and can call these procedures with full IntelliSense and type checking. If you change the return shape of a query, the frontend will immediately show a TypeScript error at compile time, preventing runtime crashes. This tight feedback loop is the holy grail of full‑stack development, and tRPC delivers it without sacrificing performance or flexibility.

Step‑by‑Step Guide to Implementing tRPC

Step 1: Setting Up the Project and Installing Dependencies

Start by creating a new Next.js application with TypeScript. You can use the official Next.js starter or set up a monorepo with Turborepo if you plan to scale. For this tutorial, we’ll use a simple standalone Next.js project:

npx create-next-app@latest my-trpc-app --typescript
cd my-trpc-app

Next, install the core tRPC packages along with React Query and Zod for validation. tRPC works with React Query to handle caching and refetching, so we need both:

npm install @trpc/server @trpc/client @trpc/react-query @trpc/next @tanstack/react-query zod

If you plan to use subscriptions, also install @trpc/server with WebSocket support (we’ll cover this later). For the server adapter, Next.js uses the App directory or Pages directory. In this guide we will use the App Router, which is the modern recommended approach. Create the following file structure inside src/:

  • src/server/trpc.ts – where we initialize the tRPC instance with context and middleware.
  • src/server/routers/ – folder for individual routers (e.g., user.ts, post.ts).
  • src/server/index.ts – app router that merges all sub‑routers.
  • src/trpc/server.ts – server‑side client for calling procedures from SSR or server components.
  • src/trpc/client.ts – client‑side tRPC client for React hooks.

With the foundation laid, you are ready to define your first procedure.

Step 2: Defining Procedures – Queries, Mutations, and Subscriptions

Procedures are the core building blocks in tRPC. They are functions that can be called remotely. The three types mirror HTTP concepts: queries for fetching data (GET), mutations for changing data (POST/PUT/DELETE), and subscriptions for real‑time updates (WebSocket). Each procedure can accept an input that is validated by Zod, and returns a typed output. Create a file src/server/routers/user.ts:

import { z } from 'zod';
import { router, publicProcedure } from '../trpc';

export const userRouter = router({
  getById: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input }) => {
      // Simulate a database call
      const user = { id: input.id, name: 'John Doe', email: 'john@example.com' };
      return user;
    }),
  updateName: publicProcedure
    .input(z.object({ id: z.string(), name: z.string().min(1) }))
    .mutation(async ({ input }) => {
      // Update user in database
      return { success: true, id: input.id, newName: input.name };
    }),
});

Notice that publicProcedure is an alias for an unauthenticated procedure. You can later wrap it in middleware to enforce authentication. The input is validated at runtime using Zod, and the return type is automatically inferred from the function’s return. On the frontend, the client will know that getById expects an object with id: string and returns { id: string; name: string; email: string }. Any mismatch will cause a TypeScript error. To create subscriptions, you use publicProcedure.subscription() with an async generator or event emitter, but we’ll cover that in a later step.

Step 3: Creating the Root Router and Context

The root router combines all sub‑routers into a single API contract. Context is a way to inject dependencies (like database clients, session data, or request‑scoped values) into every procedure. In src/server/trpc.ts, define the context factory and the base tRPC instance:

import { initTRPC } from '@trpc/server';
import { CreateNextContextOptions } from '@trpc/server/adapters/next';
import { getServerSession } from 'next-auth'; // Example authentication

export const createContext = async (opts: CreateNextContextOptions) => {
  const session = await getServerSession(opts.req, opts.res);
  return {
    session,
    db: prisma, // Your Prisma client
  };
};

const t = initTRPC.context<typeof createContext>().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const middleware = t.middleware;

Then in src/server/index.ts, merge all routers:

import { router } from './trpc';
import { userRouter } from './routers/user';
import { postRouter } from './routers/post';

export const appRouter = router({
  user: userRouter,
  post: postRouter,
});

export type AppRouter = typeof appRouter;

Now you have a type‑safe API contract defined entirely in TypeScript. The exported AppRouter type is what the client will import.

Step 4: Connecting the tRPC Client on the Frontend (React / Next.js App Router)

With the server ready, it’s time to set up the client. In Next.js App Router, you create a tRPC provider that wraps your application. First, create src/trpc/client.ts:

import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '@/server';

export const trpc = createTRPCReact<AppRouter>();

This generates the hooks you will use in your components. Next, create a provider component (src/trpc/Provider.tsx):

'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import { useState } from 'react';
import { trpc } from './client';

export default function TRPCProvider({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());
  const [trpcClient] = useState(() =>
    trpc.createClient({
      links: [httpBatchLink({ url: '/api/trpc' })],
    })
  );
  return (
    
      {children}
    
  );
}

Wrap your root layout with this provider. Finally, create the API endpoint handler that tRPC uses: src/app/api/trpc/[trpc]/route.ts (for App Router):

import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '@/server';
import { createContext } from '@/server/trpc';

const handler = (req: Request) =>
  fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext,
  });

export { handler as GET, handler as POST };

Now you can use hooks inside any client component:

'use client';
import { trpc } from '@/trpc/client';

export default function UserProfile({ id }: { id: string }) {
  const { data, isLoading } = trpc.user.getById.useQuery({ id });
  if (isLoading) return <p>Loading...</p>;
  return <p>{data?.name}</p>;
}

The hook useQuery is fully typesafe: the input parameter is typed, and the data object matches the server’s output exactly. Mutations work similarly with useMutation.

Step 5: Error Handling and Custom Middleware

tRPC provides a structured way to handle errors. You can throw TRPCError inside a procedure, which will be serialized to the client as an error with a code (e.g., UNAUTHORIZED, NOT_FOUND). Example:

import { TRPCError } from '@trpc/server';

export const userRouter = router({
  getSecret: publicProcedure
    .query(({ ctx }) => {
      if (!ctx.session) throw new TRPCError({ code: 'UNAUTHORIZED' });
      return { secret: 's3cret' };
    }),
});

On the client, you can catch these errors using the onError callback in the query options or via the trpc.useUtils().user.getSecret.fetch() pattern. For more advanced logic, you can create middleware that applies to multiple procedures. For example, an authentication middleware that attaches the user object to the context:

const isAuth = middleware(async ({ ctx, next }) => {
  if (!ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
  return next({
    ctx: {
      user: ctx.session.user,
    },
  });
});

export const protectedProcedure = publicProcedure.use(isAuth);

Now any procedure using protectedProcedure will automatically require a valid session.

Step 6: Subscriptions for Real‑Time Updates

To enable real‑time features like live chat or notifications, tRPC supports subscriptions. On the server, you need to add WebSocket support. Install ws and use the applyWSSHandler from @trpc/server/adapters/ws. Here’s a minimal example:

import { applyWSSHandler } from '@trpc/server/adapters/ws';
import { WebSocketServer } from 'ws';
import { appRouter } from './server';
import { createContext } from './server/trpc';

const wss = new WebSocketServer({ port: 3001 });
applyWSSHandler({ wss, router: appRouter, createContext });

Then define a subscription procedure:

import { observable } from '@trpc/server/observable';

export const liveRouter = router({
  onMessage: publicProcedure.subscription(() => {
    return observable<string>((emit) => {
      const interval = setInterval(() => emit.next('New message!'), 2000);
      return () => clearInterval(interval);
    });
  }),
});

On the client, you use trpc.live.onMessage.useSubscription() and receive real‑time data. The types remain consistent throughout.

Best Practices and Tips for Production‑Ready tRPC

Tip 1: Always Validate Inputs with Zod (or Your Validator of Choice)

Even though TypeScript catches type mismatches at compile time, runtime validation is essential for security and data integrity. tRPC is agnostic to validation libraries but Zod is the most commonly used due to its excellent TypeScript integration. Always define strict input schemas—never trust the client. For complex inputs, compose schemas using Zod’s .merge() or .object(). This also acts as built‑in documentation for what your API expects.

Tip 2: Leverage React Query’s Caching and Revalidation

tRPC’s React integration is built on top of @tanstack/react-query, meaning you get all its caching, background refetching, and mutation invalidation capabilities without extra work. Use trpc.useUtils() to manually invalidate queries after a mutation. For example, after updating a user’s name, call utils.user.getById.invalidate({ id }) to refetch that user’s data. This keeps your UI synchronized with the server without manual state management.

Tip 3: Structure Your Routers Modularly

As your application grows, avoid a monolithic router file. Group related procedures into sub‑routers (e.g., userRouter, postRouter, paymentRouter) and merge them into the root appRouter. This keeps the codebase maintainable and allows you to reuse middleware selectively. Also consider using a monorepo with a shared types package if you have a separate frontend and backend repository.

Reference Tables

Comparison: tRPC vs. GraphQL vs. REST for Type Safety
Feature tRPC GraphQL REST + TypeScript
End‑to‑end type safety Native, zero‑code Via code generation Manual duplication or OpenAPI
Schema definition TypeScript functions SDL language OpenAPI / TypeScript interfaces
Latency overhead Minimal (batchable) Single endpoint, query overhead Multiple endpoints, caching simple
Learning curve Low (if you know TypeScript) Medium (queries, mutations, fragments) Low to medium
Tooling React Query, Zod Apollo, Relay, codegen Axios, React Query
tRPC Procedure Types and Their Default HTTP Mapping
Procedure Type HTTP Method Use Case Client Hook Example
.query() GET Fetch data without side effects trpc.user.getById.useQuery(input)
.mutation() POST Create, update, or delete data trpc.user.updateName.useMutation()
.subscription() WebSocket Real‑time event streams trpc.chat.onMessage.useSubscription()

Frequently Asked Questions (FAQ)

1. How does tRPC differ from a traditional REST API?

Traditional REST APIs require manual type definitions on both ends. You define endpoints, serialization rules, and often generate client SDKs to maintain type safety. tRPC removes this duplication by letting you write plain TypeScript functions on the server and import their types directly into the client. There are no manual routes, no HTTP method concerns (tRPC uses POST by default, but you can configure batch links), and no serialisation mismatch—everything is type‑checked at compile time.

2. Can I use tRPC with a frontend framework other than React?

Yes. While tRPC provides excellent React/Next.js integration, the core @trpc/client is framework‑agnostic. You can use it with Vue, Svelte, or plain JavaScript by using the bare client (import { createTRPCClient } from '@trpc/client'). The community also maintains adapters for Solid and React Native. The end‑to‑end type safety still applies as long as both sides are TypeScript.

3. How do I handle authentication with tRPC?

Authentication is typically handled via context. In your createContext function (e.g., inside Next.js API route), you parse cookies, JWT tokens, or session headers and attach the user info to the context. Then you create a protectedProcedure using tRPC’s middleware that checks for the user. If authentication fails, throw a TRPCError with code 'UNAUTHORIZED'. The client can then handle the error globally (e.g., redirect to login).

4. Is tRPC suitable for large‑scale applications with many endpoints?

Absolutely. tRPC’s modular router system scales well. You can split routers across files and merge them. The batching link (httpBatchLink) collapses multiple requests into a single HTTP call, reducing latency. For even larger setups, you can use server‑less deployments (Vercel, AWS Lambda) because tRPC adapters are lightweight. However, if you need complex caching layers or public REST API consumption, you might still want a separate REST layer – tRPC excels for internal services and full‑stack apps.

5. How do I handle file uploads with tRPC?

tRPC does not natively support multipart form uploads because its default protocol is JSON. For file uploads, you have a few options: (a) Use a separate endpoint (e.g., a Next.js API route) to handle the file and return a URL, then pass that URL to a tRPC mutation. (b) Encode the file as base64 and send it as a string — but this is inefficient for large files. (c) Use a solution like tRPC-formdata or a custom link that serializes FormData. The recommended approach is to use a dedicated file upload endpoint (e.g., using multer or a third‑party service like UploadThing) and then reference the uploaded file by URL in your tRPC procedures.

Conclusion

tRPC fundamentally changes how we think about building full‑stack TypeScript applications. By eliminating the boundary between server and client types, it removes an entire class of bugs, speeds up development, and provides an unmatched developer experience. In this tutorial, we walked through the complete setup: from installing dependencies and defining procedures with Zod validation, to creating context, setting up the client in Next.js, adding error handling, middleware, and even real‑time subscriptions. We also compared tRPC with traditional approaches and answered common questions to help you avoid pitfalls. The key takeaway is that tRPC is not just another RPC framework—it is the embodiment of the “type‑first” philosophy that modern TypeScript developers have been craving. Whether you are building a small side project or a large enterprise application, adopting tRPC will make your codebase more robust, your APIs self‑documenting, and your team more productive. Start by migrating a single endpoint and experience the joy of automatic type safety across the wire. Your future self—and your users—will thank you.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *