DEV Community

Arhan Khan
Arhan Khan

Posted on

tRPC for Beginners: End-to-End Type Safety Without Writing a Single API Route

tRPC is a framework for building APIs in TypeScript, and it removes the most annoying part of full-stack development: keeping the frontend and backend in sync. With tRPC, you define a procedure on the server, and the client gets full autocomplete and type checking for it automatically. No REST endpoints to document, no OpenAPI spec to maintain, no client code to generate.

The idea is simple. Your backend exposes functions. Your frontend calls them like local functions, but they run on the server. If you change a function's input or output on the server, TypeScript immediately shows an error on the client. The API contract is the code itself.

// server: src/server/trpc.ts
import { initTRPC } from "@trpc/server";
import { z } from "zod";

const t = initTRPC.create();

export const appRouter = t.router({
  greeting: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => {
      return { message: `Hello, ${input.name}!` };
    }),
});

export type AppRouter = typeof appRouter;
Enter fullscreen mode Exit fullscreen mode
// client: a React component
import { trpc } from "./utils/trpc";

function Welcome() {
  const { data, isLoading } = trpc.greeting.useQuery({ name: "World" });
  if (isLoading) return <p>Loading...</p>;
  return <p>{data?.message}</p>; // Fully typed, with autocomplete
}
Enter fullscreen mode Exit fullscreen mode

Getting started is simple. The official docs have a quickstart that sets up a working tRPC app in minutes, and the create-t3-app starter includes tRPC preconfigured with Next.js, Prisma, and Tailwind. The core concepts are just three: queries (read data), mutations (change data), and routers (group procedures).

tRPC is for TypeScript developers building full-stack apps, beginners who want to learn APIs without the REST boilerplate, and teams who are tired of frontend and backend drifting apart. It shines in monorepos where the client and server live in the same codebase.

The limits are honest. tRPC only works when the client and server are both TypeScript — it is not for public APIs or non-TypeScript clients. It adds a learning curve if you have never used Zod or React Query, and debugging a procedure is different from debugging a plain HTTP route.

Start today with one thing: build one tRPC query that returns a greeting, and call it from a React component. Change the server's return type and watch the client light up with a type error. In a week you will never want to write a REST endpoint by hand again.

Top comments (0)