Server router() procedure() Client useQuery() useMutation() Types tRPC End-to-End Type Safety
Backend

tRPC: End-to-End Type-Safe APIs

Mayur Dabhi
Mayur Dabhi
June 16, 2026
14 min read

You rename user.name to user.fullName in a REST endpoint, run the tests, and ship. The frontend still reads user.name, gets undefined, and nobody notices until a user reports a blank profile header. TypeScript couldn't help, because the frontend's User type was a hand-written copy that nobody updated.

tRPC closes that gap by letting the client import the server's types directly. No code generation, no schema file. In this post I'll set up tRPC with Next.js, build a router with queries and mutations, add Zod validation and auth middleware, and then talk about where it fits and where it doesn't.

Where You've Probably Seen It

tRPC is the API layer in create-t3-app, a popular full-stack TypeScript starter, and open source projects like Cal.com use it. The appeal is simple: a whole class of "frontend and backend disagree about the shape of the data" bugs turns into compile errors.

How tRPC Works

The name stands for TypeScript Remote Procedure Call. You call server functions from the client almost as if they were local, and TypeScript knows the input and output types on both sides. With REST you maintain the client types yourself. With GraphQL you write a schema and run a codegen step. tRPC skips both and relies on TypeScript's own inference.

You define procedures (plain functions) on the server inside a router. You export the router's type, and the client uses that type for autocomplete and type checking. There's no JSON Schema, no OpenAPI spec and no GraphQL SDL. It's just TypeScript.

Server Router appRouter.ts procedure definitions Zod input schemas Type Inference AppRouter type exported shared to client zero runtime cost Client Hooks trpc.users.getAll .useQuery() full autocomplete typeof inferred HTTP transport (JSON over fetch), hidden from you

tRPC's type safety flows from server definition to client without code generation

Setting Up Your tRPC Project

tRPC wants the server and client in the same TypeScript project, or at least the same monorepo. Next.js is the usual choice because API routes and components already live side by side.

1

Create a Next.js TypeScript project

Start with a fresh Next.js app, or use create-t3-app for an opinionated full setup with tRPC, Prisma, and NextAuth pre-configured.

Terminal
# Option 1: Plain Next.js
npx create-next-app@latest my-trpc-app --typescript --app

# Option 2: create-t3-app (recommended, includes tRPC + Prisma + Auth)
npm create t3-app@latest my-t3-app
2

Install tRPC and dependencies

Install the core tRPC packages, React Query adapter, and Zod for input validation.

Terminal
npm install @trpc/server @trpc/client @trpc/react-query @trpc/next
npm install @tanstack/react-query zod
npm install @tanstack/react-query-devtools --save-dev
3

Initialize tRPC on the server

Create a central trpc.ts file that exports your procedure builders and router factory.

4

Create a client-side tRPC instance

Export a typed React client that mirrors your server's router type, giving you full autocomplete in components.

Building Your First Router

On the server you need a trpc.ts file that creates the procedure builders, plus one or more router files that use them. Keeping these apart stops you from ending up with one giant file once the API grows.

server/trpc.ts
import { initTRPC, TRPCError } from '@trpc/server';
import { type Context } from './context';

// Initialize tRPC with your context type
const t = initTRPC.context<Context>().create();

// Export reusable router and procedure builders
export const router = t.router;
export const publicProcedure = t.procedure;
export const middleware = t.middleware;

// Reusable auth middleware
const isAuthed = middleware(({ ctx, next }) => {
  if (!ctx.session?.user) {
    throw new TRPCError({
      code: 'UNAUTHORIZED',
      message: 'You must be signed in to perform this action',
    });
  }
  return next({
    ctx: {
      ...ctx,
      // Narrows user type to non-null after this middleware
      user: ctx.session.user,
    },
  });
});

// Protected procedure: requires authentication
export const protectedProcedure = t.procedure.use(isAuthed);

Next come the routers. I split them by domain (users, posts and so on) and merge them into one root router:

server/routers/user.ts
import { z } from 'zod';
import { router, publicProcedure, protectedProcedure } from '../trpc';
import { db } from '../db';

export const userRouter = router({
  // Query: fetch all users (public)
  getAll: publicProcedure.query(async () => {
    return db.user.findMany({
      select: { id: true, name: true, email: true, createdAt: true },
    });
  }),

  // Query: fetch one user by ID (public)
  getById: publicProcedure
    .input(z.object({ id: z.string().cuid() }))
    .query(async ({ input }) => {
      const user = await db.user.findUnique({ where: { id: input.id } });
      if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
      return user;
    }),

  // Mutation: update profile (protected)
  updateProfile: protectedProcedure
    .input(z.object({
      name: z.string().min(1).max(100),
      bio: z.string().max(500).optional(),
    }))
    .mutation(async ({ input, ctx }) => {
      return db.user.update({
        where: { id: ctx.user.id },
        data: input,
      });
    }),
});
server/routers/app.ts
import { router } from '../trpc';
import { userRouter } from './user';
import { postRouter } from './post';

// Root router: merge all sub-routers
export const appRouter = router({
  users: userRouter,
  posts: postRouter,
});

// Export the type. This is what the client uses for inference
export type AppRouter = typeof appRouter;
The Line That Does the Work

export type AppRouter = typeof appRouter is the whole trick. The client imports this type, not the implementation, and TypeScript infers every procedure's input and output from it. Use import type on the client side so your bundler never pulls in server code like Prisma or your auth config.

Queries, Mutations, and Subscriptions

There are three procedure types. Queries read, mutations write, and subscriptions push data to the client as it happens.

Queries fetch data and are called with .useQuery() on the client. They are cached by React Query and re-fetched automatically when the cache is stale.

// Server: define the query
getAll: publicProcedure.query(async () => {
  return db.post.findMany({ orderBy: { createdAt: 'desc' } });
}),

// Client: consume the query
function PostList() {
  const { data: posts, isLoading, error } = trpc.posts.getAll.useQuery();

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

Mutations modify data and are called with .useMutation(). They don't run on their own. You call mutate() or mutateAsync() yourself, usually from an event handler.

// Server: define the mutation
create: protectedProcedure
  .input(z.object({
    title: z.string().min(1).max(200),
    content: z.string().min(10),
    published: z.boolean().default(false),
  }))
  .mutation(async ({ input, ctx }) => {
    return db.post.create({
      data: { ...input, authorId: ctx.user.id },
    });
  }),

// Client: consume the mutation
function CreatePost() {
  const utils = trpc.useUtils();
  const createPost = trpc.posts.create.useMutation({
    onSuccess: () => {
      // Invalidate the list cache so it re-fetches
      utils.posts.getAll.invalidate();
    },
  });

  return (
    <button
      onClick={() => createPost.mutate({ title: 'Hello', content: '...' })}
      disabled={createPost.isPending}
    >
      {createPost.isPending ? 'Creating...' : 'Create Post'}
    </button>
  );
}

Subscriptions stream data over WebSockets using .useSubscription(). They require a WebSocket-capable server (like a standalone Node.js server, not Next.js API routes).

// Server: define the subscription (requires WS adapter)
import { observable } from '@trpc/server/observable';

onNewMessage: publicProcedure
  .input(z.object({ roomId: z.string() }))
  .subscription(({ input }) => {
    return observable<Message>(emit => {
      const handler = (message: Message) => {
        if (message.roomId === input.roomId) {
          emit.next(message);
        }
      };
      messageEmitter.on('message', handler);
      // Clean up on unsubscribe
      return () => messageEmitter.off('message', handler);
    });
  }),

// Client: consume the subscription
function ChatRoom({ roomId }: { roomId: string }) {
  const [messages, setMessages] = useState<Message[]>([]);

  trpc.chat.onNewMessage.useSubscription(
    { roomId },
    {
      onData: (message) => {
        setMessages(prev => [...prev, message]);
      },
    }
  );

  return <MessageList messages={messages} />;
}

Input Validation with Zod

Zod is the validator most tRPC projects use (tRPC also accepts Yup, Valibot and others). A Zod schema does two jobs at once: it checks incoming data at runtime, and it gives you the TypeScript type for free, so you don't write the type twice.

Always Validate Inputs

Type safety only covers your own code. Anyone can still hit /api/trpc with curl and send whatever they like. The Zod check runs on the server before your procedure does, so don't skip .input() on anything that takes user data.

Gotcha: Dates Without a Transformer

By default tRPC sends plain JSON, and JSON has no Date type. If you return a Date from a procedure, the client receives an ISO string. The z.date() field in the schema below goes wrong the other way: the client's Date is serialized to a string, and the server rejects it with Expected date, received string. Add superjson as the transformer on both the server and client links, or use z.coerce.date() for the input.

Zod Schema Examples
import { z } from 'zod';

// Basic object schema
const createUserInput = z.object({
  name: z.string().min(1, 'Name is required').max(100),
  email: z.string().email('Invalid email address'),
  age: z.number().int().min(13).max(120).optional(),
  role: z.enum(['user', 'admin', 'moderator']).default('user'),
});

// Nested schemas
const createPostInput = z.object({
  title: z.string().min(1).max(200),
  content: z.string().min(10),
  tags: z.array(z.string().max(30)).max(10).default([]),
  metadata: z.object({
    slug: z.string().regex(/^[a-z0-9-]+$/),
    published: z.boolean().default(false),
    publishedAt: z.date().optional(),
  }),
});

// Use in a procedure
createPost: protectedProcedure
  .input(createPostInput)
  .mutation(async ({ input }) => {
    // input is fully typed as z.infer<typeof createPostInput>
    // Zod already validated it, so it's safe to use directly
    return db.post.create({ data: input });
  }),

// Reuse Zod types in your components
type CreatePostInput = z.infer<typeof createPostInput>;

function PostForm() {
  const [formData, setFormData] = useState<CreatePostInput>({...});
  // TypeScript ensures form state matches the server's expectation
}

Custom Error Handling

Throw a TRPCError inside a procedure and tRPC maps its code to an HTTP status for you. The client gets the code and message on error.data and error.message:

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

getPost: publicProcedure
  .input(z.object({ slug: z.string() }))
  .query(async ({ input }) => {
    const post = await db.post.findUnique({ where: { slug: input.slug } });

    if (!post) {
      throw new TRPCError({
        code: 'NOT_FOUND',         // → 404
        message: `Post "${input.slug}" not found`,
      });
    }

    if (!post.published) {
      throw new TRPCError({
        code: 'FORBIDDEN',         // → 403
        message: 'This post is not published',
      });
    }

    return post;
  }),

// Available codes: BAD_REQUEST, UNAUTHORIZED, FORBIDDEN,
// NOT_FOUND, CONFLICT, TOO_MANY_REQUESTS, INTERNAL_SERVER_ERROR, etc.

Next.js Integration

Wiring tRPC into Next.js takes one catch-all API route that handles every tRPC call, plus a client provider around your app. You write it once and then mostly forget about it.

app/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '~/server/routers/app';
import { createContext } from '~/server/context';

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

export { handler as GET, handler as POST };
utils/trpc.ts (client setup)
import { createTRPCReact } from '@trpc/react-query';
import { type AppRouter } from '~/server/routers/app';

// This is the typed client. Import trpc from this file everywhere
export const trpc = createTRPCReact<AppRouter>();
app/providers.tsx (wrap the app)
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import { useState } from 'react';
import { trpc } from '~/utils/trpc';

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());
  const [trpcClient] = useState(() =>
    trpc.createClient({
      links: [
        httpBatchLink({
          url: '/api/trpc',
          // Optional: add auth headers
          headers: () => ({
            authorization: getAuthToken() ?? '',
          }),
        }),
      ],
    })
  );

  return (
    <trpc.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>
        {children}
      </QueryClientProvider>
    </trpc.Provider>
  );
}

tRPC vs REST vs GraphQL

The choice mostly comes down to two questions: is everything TypeScript, and does anyone outside your team need to call this API?

Feature tRPC REST GraphQL
Type Safety Automatic (TypeScript inference) Manual or via OpenAPI codegen Via schema + codegen (graphql-codegen)
Schema Language None (TypeScript is the schema) OpenAPI / JSON Schema (optional) SDL (required)
Code Generation Not needed Optional Usually required for type safety
Public API Support No (TypeScript-only clients) Yes (any language) Yes (any language)
Over-fetching Controlled per procedure Common None (client specifies fields)
Real-time Subscriptions (WebSocket) SSE / WebSocket (manual) Subscriptions (WebSocket)
Learning Curve Low (TypeScript + functions) Very low High (SDL, resolvers, N+1 problem)
Best For TypeScript monorepos Public APIs, polyglot teams Complex data graphs, multiple clients
When NOT to Use tRPC

The type safety only exists when both ends are TypeScript. If you need a public API for mobile apps, third parties or clients in other languages, use REST or GraphQL. tRPC makes sense when you own both ends of the wire.

Advanced Patterns

Context and Authentication

Context carries request-scoped data, like the current session, into your procedures. tRPC builds it once per request and passes it to every procedure as ctx:

server/context.ts
import { type inferAsyncReturnType } from '@trpc/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '~/server/auth';
import { db } from '~/server/db';

export async function createContext(opts: { req: Request }) {
  const session = await getServerSession(authOptions);

  return {
    session,
    user: session?.user ?? null,
    db,
  };
}

// Export the type so tRPC can infer it
export type Context = inferAsyncReturnType<typeof createContext>;

Procedure Chaining and Middleware

Middleware is where logging, rate limiting and role checks go, so you don't repeat them in every procedure:

Middleware examples
// Timing middleware: log slow procedures
const timingMiddleware = middleware(async ({ path, type, next }) => {
  const start = Date.now();
  const result = await next();
  const duration = Date.now() - start;

  if (duration > 500) {
    console.warn(`Slow procedure: ${type} ${path} took ${duration}ms`);
  }

  return result;
});

// Role-based access
const isAdmin = middleware(({ ctx, next }) => {
  if (ctx.user?.role !== 'admin') {
    throw new TRPCError({ code: 'FORBIDDEN', message: 'Admins only' });
  }
  return next({ ctx });
});

// Chain middleware on a procedure
export const adminProcedure = t.procedure
  .use(timingMiddleware)
  .use(isAuthed)
  .use(isAdmin);

Optimistic Updates

Since tRPC sits on top of React Query, optimistic updates use the normal React Query pattern. The UI changes right away and rolls back if the server says no:

Optimistic update example
function LikeButton({ postId }: { postId: string }) {
  const utils = trpc.useUtils();

  const likeMutation = trpc.posts.like.useMutation({
    // Optimistically update the UI before server responds
    onMutate: async ({ postId }) => {
      await utils.posts.getById.cancel({ id: postId });
      const prev = utils.posts.getById.getData({ id: postId });

      utils.posts.getById.setData({ id: postId }, old =>
        old ? { ...old, likeCount: old.likeCount + 1, liked: true } : old
      );

      return { prev };
    },
    // Roll back on error
    onError: (err, vars, context) => {
      utils.posts.getById.setData({ id: postId }, context?.prev);
    },
    // Always refetch after mutation settles
    onSettled: () => {
      utils.posts.getById.invalidate({ id: postId });
    },
  });

  return (
    <button onClick={() => likeMutation.mutate({ postId })}>
      Like
    </button>
  );
}
Component calls mutate() React Query optimistic update local cache tRPC Server validates input runs mutation Database persists data confirm or rollback optimistic update

Optimistic update flow: UI updates instantly, server confirms asynchronously

When I'd Use tRPC (and When I Wouldn't)

I'd reach for tRPC when one team owns a TypeScript frontend and a TypeScript backend in the same repo and the API changes every week. That's where it pays off most: you rename a field, and the compiler shows you every component that needs fixing before anything ships.

Where It Gets Awkward

  • Public or partner APIs: Outside consumers can't import your router type. You'd end up bolting on an OpenAPI layer, and at that point plain REST is often simpler.
  • Native mobile apps: A Swift or Kotlin client gets nothing from TypeScript inference. React Native in the same monorepo is fine.
  • Separate repos: If the frontend and backend live apart, you have to publish the router type as a package and keep versions in sync, which brings back the drift tRPC was supposed to remove.
  • Very large routers: Hundreds of procedures in one router can make the TypeScript language server noticeably slow. Splitting routers and keeping return types simple helps.
  • Caching at the HTTP layer: Batched requests go to URLs like /api/trpc/a,b,c, which CDNs don't cache well. If you depend on edge caching for reads, plan for it or turn off batching for those calls.

If you already have a Next.js app with REST routes, you don't have to migrate everything at once. Add the tRPC handler next to the existing routes and move one endpoint over when you next need to touch it.

tRPC TypeScript API Full-Stack Next.js React Query Zod
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.