Web Development 1 min read 1,668 views

tRPC: End-to-End Type Safety Without GraphQL

tRPC provides full-stack type safety without schemas or code generation. Learn to build type-safe APIs.

E
tRPC TypeScript code

tRPC enables end-to-end type safety between your frontend and backend without schemas, code generation, or REST/GraphQL complexity.

How tRPC Works

Define procedures on the server, call them with full type inference on the client:

Server

import { initTRPC } from "@trpc/server";
import { z } from "zod";

const t = initTRPC.create();

export const appRouter = t.router({
  user: t.router({
    getById: t.procedure
      .input(z.string())
      .query(({ input }) => {
        return db.users.findById(input);
      }),
    create: t.procedure
      .input(z.object({ name: z.string(), email: z.string().email() }))
      .mutation(({ input }) => {
        return db.users.create(input);
      }),
  }),
});

export type AppRouter = typeof appRouter;

Client

import { createTRPCClient } from "@trpc/client";
import type { AppRouter } from "./server";

const trpc = createTRPCClient<AppRouter>({ url: "/api/trpc" });

// Full type inference!
const user = await trpc.user.getById.query("123");
const newUser = await trpc.user.create.mutate({ name: "John", email: "john@example.com" });

Benefits

  • No schema files or code generation
  • Instant type errors across the stack
  • Works with React Query built-in
  • Subscriptions for real-time data
Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!