Skip to content

Building Type-Safe APIs with tRPC and Next.js

A current tRPC Next.js setup for the App Router, why the real win is an API you can click through, and when OpenAPI or GraphQL is the better contract.

13 min read
Illustrative macro photograph of two precisely keyed modular connectors in complementary charcoal and teal material.
On this page

Rename a tRPC procedure and the compiler hands you a list of every component that calls it. Rename a REST endpoint and you find out from a 404, or from a grep you hope caught every string. That difference is the real reason to pick a tRPC Next.js setup, and it's also why tRPC is the wrong contract for a good share of the APIs teams build with it.

This post covers the current tRPC v11 setup for the App Router (router, validated procedures, the route handler, TanStack Query on the client, direct calls from Server Components), error handling that doesn't leak internals, and a decision table for when OpenAPI or GraphQL should own the contract instead.

The API contract you can click through

The tRPC docs pitch it as a way to build and consume fully typesafe APIs with no schema files and no code generation step. It relies on TypeScript inference, so a mismatch between client and server shows up at build time instead of in production.[1]

Most people stop at "I get types on the client." I think the bigger payoff is that you can click through the API. The client doesn't call a URL string. It calls trpc.invoice.byId, a property on a type inferred from the router object. So Go to Definition on that call lands on the byId: line in the server's router file, and Find All References on that line lists every component, page and test that calls it. That's plain TypeScript language service behaviour, so it works in any editor without a plugin.

Compare a REST call: fetch('/api/invoices/' + id). The link between client and handler is a string plus a file-system convention. To find the callers you search text and hope nobody assembled the URL from pieces. I've argued that code search matters more than you think, and it does. With tRPC you need less of it at this particular seam, because the compiler already knows the call graph across the network boundary.

Here's my contrarian take: end-to-end type safety is the least interesting thing tRPC gives you. Plenty of tools generate typed clients. What tRPC gives a team is an API layer a new engineer reads the same way they read the rest of the code, by following references. If you use a systematic approach to understanding a codebase, you know the hard part is usually the seams between systems. tRPC removes one of those seams.

A minimal tRPC Next.js setup for the App Router

The current major version is tRPC v11. Its docs recommend the @trpc/tanstack-react-query integration over the classic @trpc/react-query client. The new one doesn't wrap TanStack Query in tRPC-specific hooks. It gives you queryOptions and mutationOptions objects that you pass to the normal useQuery and useMutation.[2]

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

A request passes through five stops, and only one of them, the procedure, is something you write per feature. The rest is plumbing you set up once.

REQUEST · plain HTTP: GET for queries, POST for mutations Component useTRPC() tRPC client httpBatchLink Route handler fetch adapter Validation Zod input Procedure invoice.byId defines export type AppRouter inferred from the router object import type · renames fail at compile time SHARED TYPE · no schema file, no code generation
Figure 1. Requests travel over plain HTTP, while the contract travels back as a TypeScript type.

Procedures with input validation

Start with trpc/init.ts. The context function takes headers so the route handler and Server Components can both build it. The protectedProcedure middleware narrows userId from string | null to string, so every procedure built on it gets a signed-in user at the type level, not just at runtime.

typescript
// src/trpc/init.ts
import { initTRPC, TRPCError } from '@trpc/server';
import { getUserId } from '~/lib/auth'; // your session lookup

// Called by the route handler and by the Server Component caller.
export const createTRPCContext = async (opts: { headers: Headers }) => {
  return { userId: await getUserId(opts.headers) };
};

const t = initTRPC
  .context<Awaited<ReturnType<typeof createTRPCContext>>>()
  .create({
    errorFormatter({ shape }) {
      // Never ship raw database or library messages to the browser.
      if (shape.data.code !== 'INTERNAL_SERVER_ERROR') return shape;
      return { ...shape, message: 'Internal server error' };
    },
  });

export const createTRPCRouter = t.router;
export const baseProcedure = t.procedure;

export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
  if (!ctx.userId) throw new TRPCError({ code: 'UNAUTHORIZED' });
  return next({ ctx: { userId: ctx.userId } }); // now string, not string | null
});

Each procedure declares its input with Zod. If validation fails, the resolver never runs and the caller gets a BAD_REQUEST.

typescript
// src/trpc/routers/invoice.ts
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { db } from '~/server/db';
import { createTRPCRouter, protectedProcedure } from '../init';

export const invoiceRouter = createTRPCRouter({
  byId: protectedProcedure
    .input(z.object({ id: z.string().min(1) }))
    .query(async ({ ctx, input }) => {
      const invoice = await db.invoice.findFirst({
        where: { id: input.id, ownerId: ctx.userId },
      });
      if (!invoice) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Invoice not found' });
      }
      return invoice;
    }),

  markPaid: protectedProcedure
    .input(z.object({ id: z.string().min(1) }))
    .mutation(async ({ ctx, input }) => {
      const { count } = await db.invoice.updateMany({
        where: { id: input.id, ownerId: ctx.userId },
        data: { status: 'paid' },
      });
      if (count === 0) throw new TRPCError({ code: 'NOT_FOUND' });
      return { id: input.id, status: 'paid' as const };
    }),
});
typescript
// src/trpc/routers/_app.ts
import { createTRPCRouter } from '../init';
import { invoiceRouter } from './invoice';

export const appRouter = createTRPCRouter({
  invoice: invoiceRouter,
});

export type AppRouter = typeof appRouter;

That last line is the whole contract. The client imports AppRouter as a type, so no server code ships to the browser, and there's no generated file to keep in sync.

The App Router route handler

App Router route handlers work with Web standard Request and Response objects, so tRPC uses its fetch adapter here rather than the Pages Router adapter. Export both GET and POST. Queries go out as GET by default and mutations as POST, and a missing export answers with a 405.[3]

typescript
// src/app/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { createTRPCContext } from '~/trpc/init';
import { appRouter } from '~/trpc/routers/_app';

const handler = (req: Request) =>
  fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext: () => createTRPCContext({ headers: req.headers }),
    onError({ error, path }) {
      // The full error, cause included, stays on the server.
      if (error.code === 'INTERNAL_SERVER_ERROR') console.error('tRPC', path, error);
    },
  });

// Queries go out as GET, mutations as POST: export both.
export { handler as GET, handler as POST };

Calling procedures from Client Components

Two files are pure boilerplate: trpc/query-client.ts (a QueryClient factory) and trpc/client.tsx (which creates TRPCProvider and useTRPC with createTRPCContext and builds the tRPC client with httpBatchLink). Copy them from the official App Router setup page and mount the provider in your root layout. The part you write per feature looks like this:

tsx
// src/app/invoices/[id]/invoice-status.tsx
'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTRPC } from '~/trpc/client';

export function InvoiceStatus({ id }: { id: string }) {
  const trpc = useTRPC();
  const queryClient = useQueryClient();
  const invoice = useQuery(trpc.invoice.byId.queryOptions({ id }));
  const markPaid = useMutation(
    trpc.invoice.markPaid.mutationOptions({
      onSuccess: () =>
        queryClient.invalidateQueries(trpc.invoice.byId.queryFilter({ id })),
    }),
  );

  if (invoice.error?.data?.code === 'NOT_FOUND') return <p>No such invoice.</p>;
  if (invoice.error) return <p>Could not load the invoice.</p>;
  if (!invoice.data) return <p>Loading</p>;

  return (
    <button
      disabled={invoice.data.status === 'paid' || markPaid.isPending}
      onClick={() => markPaid.mutate({ id })}
    >
      {invoice.data.status === 'paid' ? 'Paid' : 'Mark as paid'}
    </button>
  );
}

There's no URL, no hand-written response type and no hand-written cache key. The key comes from the procedure path plus the input, so the queryFilter used for invalidation can't drift from the query it targets.

Calling procedures from Server Components

A Server Component doesn't need HTTP at all. The caller exported from trpc/server.tsx (also from the setup page, built with appRouter.createCaller) runs the procedure in-process, with the same middleware and the same input validation.

tsx
// src/app/invoices/[id]/page.tsx
import { TRPCError } from '@trpc/server';
import { notFound } from 'next/navigation';
import { caller } from '~/trpc/server';

export default async function InvoicePage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const invoice = await caller.invoice.byId({ id }).catch((error: unknown) => {
    if (error instanceof TRPCError && error.code === 'NOT_FOUND') notFound();
    throw error;
  });

  return <h1>Invoice {invoice.number}</h1>;
}

One catch: the caller's result never enters the TanStack Query cache. If a Client Component further down needs the same data, prefetch instead: call prefetch(trpc.invoice.byId.queryOptions({ id })) in the page first, then wrap the Client Component in <HydrateClient> and read the data there with useSuspenseQuery. Order matters, because HydrateClient only sends queries that were prefetched before it renders. If that component sticks with plain useQuery, await getQueryClient().prefetchQuery(...) instead, or React reports a hydration mismatch.

Error handling that doesn't leak internals

tRPC errors carry a code. Throw a TRPCError with NOT_FOUND, UNAUTHORIZED or FORBIDDEN and the adapter maps it to the matching HTTP status. With the router above, an unauthenticated call gets a 401, a missing invoice a 404 and an empty id a 400 from input validation.

The trap is everything else. Any error that isn't a TRPCError gets wrapped as INTERNAL_SERVER_ERROR and keeps its original message, so a database error naming a table goes straight to the browser. The errorFormatter in init.ts replaces that message, and the onError hook in the route handler keeps the full error on the server for your logs or error tracker. Stack traces are only sent when isDev is true, which defaults to NODE_ENV !== 'production'.[4]

Validation errors deserve a decision too. A BAD_REQUEST from Zod carries Zod's issue list as its message. That's handy for forms, and it also tells any caller exactly how your input is shaped. For an internal app I leave it. For anything strangers can reach, I'd format it down in the same errorFormatter.

On the client, error.data?.code is typed, so the component above branches on 'NOT_FOUND' instead of parsing strings. On the server, the caller throws a real TRPCError, which is why the page can turn NOT_FOUND into the Next.js notFound() page.

Where tRPC falls apart

Everything above rests on one assumption: the client was compiled against the same router type the server is running. Break that and tRPC goes from the safest option to a quietly risky one. The tRPC FAQ is upfront about it. A monorepo isn't mandatory, but without one you lose the guarantee that client and server work together, and the suggested workaround is publishing your backend types as a private npm package.[5]

Four boundaries break the assumption:

  • Public or third-party consumers. They don't have your types, and they shouldn't need your repo to call your API. They need a published, documented contract.
  • Non-TypeScript clients. A Swift, Kotlin, Python or Go client gets nothing from type inference. tRPC is HTTP and JSON underneath, so they can call it, but they're hand-writing the contract you were trying to avoid. The @trpc/openapi package can generate an OpenAPI 3.1 document from a router, but it's marked alpha.
  • Separately deployed or versioned services. If two services ship on different schedules, the type that compiled one of them last week isn't necessarily what the other is running today. tRPC has no versioning model of its own. The router is always "now".
  • Mobile apps on old builds. This is the sharpest edge in my view. A web client redeploys with the server. An app store build doesn't, and it keeps calling procedures whose input you may have tightened since. Compile-time safety says nothing about binaries already on phones.

None of these are bugs. They're the price of having no schema artifact between client and server, and a schema artifact is exactly what the alternatives sell. It's also why repo layout matters more than people expect: the monorepo vs polyrepo choice decides whether "rename it and let tsc find the callers" is even possible.

tRPC vs OpenAPI vs GraphQL: a decision table

The OpenAPI Specification defines a language-agnostic description of an HTTP API that people and tools can read without the source code. That's what you want when the consumer can't see your repo. GraphQL gives clients a typed schema they query field by field, and it evolves by deprecating fields rather than by cutting versions. tRPC gives you neither artifact. That's the point, and the limit.[6][7]

Question tRPC OpenAPI / REST GraphQL
Who consumes it? Your own TypeScript frontends Anyone, including partners and the public Many in-house clients with different data needs
Client languages TypeScript, in practice Any, through generated clients Any, through schema tooling
Deployment coupling Client and server ship together Independent, contract is versioned Independent, schema evolves by deprecation
Team boundary One team or one repo owns both sides Contract crosses team or company lines A platform team owns the schema
Where a breaking change shows up Compile error in the same pull request Spec diff or consumer tests Schema review before a field is removed
Extra artifact to maintain None The spec, written or generated The schema and its resolvers

My rule of thumb, which you're welcome to steal: if the person changing a procedure can run tsc across every client of it in the same pull request, use tRPC. If they can't, use a contract that lives outside the code. Pick OpenAPI when consumers sit outside your org or don't use TypeScript. Pick GraphQL when you have many of your own clients with very different data needs and a team willing to own the schema. If none of those apply, OpenAPI is still the safer default.

Q1 · Same PR, every client? can the author run tsc on all callers? yes tRPC own TypeScript clients, ship together no Q2 · Outside or non-TypeScript? partners, public, mobile, other languages yes OpenAPI / REST published, language-agnostic contract no Q3 · Many in-house clients? with very different data needs yes GraphQL schema owned by one team no to all three: OpenAPI is still the safer default
Figure 2. Choose tRPC only when every client compiles in the same pull request as the server.

Mixing them is normal. The shape I'd default to is tRPC for the Next.js app's own backend-for-frontend and OpenAPI for anything public, with both calling the same service functions underneath. If you don't know who calls an endpoint today, map the dependencies before you pick.

Key takeaways

  • tRPC's biggest win is that the API is part of the code graph: Go to Definition from a client call lands on the server procedure, and a rename breaks every caller at compile time.
  • In tRPC v11 on the App Router, use a fetch adapter route handler that exports GET and POST, @trpc/tanstack-react-query in Client Components and the server caller in Server Components.
  • Replace INTERNAL_SERVER_ERROR messages in errorFormatter and log full errors in onError, or database messages reach the browser.
  • tRPC is only safe when client and server compile from the same router and ship together.
  • Use OpenAPI for public and non-TypeScript consumers, and GraphQL for many in-house clients backed by a team that owns the schema.

Before adding tRPC, ask one question: who calls this, and will they recompile when I change it? If the answer is "only us, every time", tRPC is the cheapest API contract you'll ever maintain.

Frequently asked questions

Is tRPC better than REST for a Next.js app?

When the only clients are the app's own TypeScript pages, tRPC usually beats hand-written REST routes: no URL strings, typed inputs and outputs, and renames that fail at compile time. REST with an OpenAPI spec wins once outside consumers, non-TypeScript clients or independently deployed services need the API.

Do I need a monorepo to use tRPC?

No, but you give up much of the benefit without one. The tRPC FAQ says a monorepo isn't mandatory while warning that you lose the guarantee that client and server work together. Publishing the router types as a private package works, but the client then compiles against the version it installed, not the one that's deployed.

Should I use @trpc/react-query or @trpc/tanstack-react-query?

For new projects, use @trpc/tanstack-react-query. The tRPC docs recommend it over the classic client because it works with TanStack Query's own useQuery and useMutation through queryOptions and mutationOptions, instead of wrapping them in tRPC-specific hooks. It's also what the official App Router setup uses.

When should I not use tRPC?

Skip it when the API has consumers you don't compile: public or partner APIs, mobile apps that stay on old builds, clients written in other languages, or services that deploy on their own schedule. Its safety is a compile-time check, so it says nothing about a client built against an older router. Those cases need a published contract.

Sources

  1. [1]tRPC · tRPC Docs
  2. [2]TanStack React Query · tRPC Docs
  3. [3]Set up with Next.js App Router · tRPC Docs
  4. [4]Error Handling · tRPC Docs
  5. [5]FAQ / Troubleshooting · tRPC Docs
  6. [6]OpenAPI Specification v3.2.1 · OpenAPI Initiative
  7. [7]Introduction to GraphQL · GraphQL Foundation

Checked against these sources on

Related Articles