Skip to main content

Lesson 6 of 8

tRPC - End-to-End Type-Safe APIs (Concept)

tRPC eliminates the API contract problem - the server's router type is imported directly by the client, so any change to a server procedure immediately surfaces as a type error on the client. There are no separate API DTOs, no code generation, and no OpenAPI specs to maintain. This is the next evolution beyond manual typed fetch wrappers.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

tRPC - Type Share from Server to Client

tRPC - Type Share from Server to Client
// ── The problem tRPC solves ──────────────────────────────────
// Without tRPC: Server returns Task, client has to manually keep
// its Task type in sync. If server adds a field, client doesn't know.
// With tRPC: Server router type IS the client's type - sharing across
// the module boundary with no duplication.

// ── tRPC server - src/server/router.ts ───────────────────────
// npm install @trpc/server @trpc/client zod

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

// Context - what each procedure has access to (auth user, db, etc.)
interface Context {
  user: { id: number; role: "member" | "admin" } | null;
}

const t = initTRPC.context<Context>().create();

// Reusable middleware - require auth
const authedProcedure = t.procedure.use(({ ctx, next }) => {
  if (!ctx.user) throw new Error("UNAUTHORIZED");
  return next({ ctx: { ...ctx, user: ctx.user } });  // user is non-null after guard
});

// ── Router definition ─────────────────────────────────────────
export const taskRouter = t.router({
  // GET-equivalent: query
  list: t.procedure
    .input(z.object({ status: z.enum(["todo", "done"]).optional() }))
    .query(async ({ input }) => {
      return taskRepo.findAll({ status: input.status });
      // Return type inferred as Task[] - no manual annotation needed
    }),

  getById: t.procedure
    .input(z.number())
    .query(async ({ input: id }) => {
      return taskRepo.findById(id);   // Task | undefined
    }),

  // POST-equivalent: mutation
  create: authedProcedure
    .input(z.object({
      title:    z.string().min(1),
      priority: z.enum(["low", "medium", "high", "critical"]),
    }))
    .mutation(async ({ input, ctx }) => {
      return taskService.createTask(input, ctx.user.id);  // Task
    }),
});

// Export the router TYPE - shared with the client
export type AppRouter = typeof taskRouter;

// ── tRPC client - src/client/api.ts ──────────────────────────
import { createTRPCClient, httpBatchLink } from "@trpc/client";
import type { AppRouter }                  from "../server/router"; // TYPE import only!

// The client knows ALL server procedure types at compile time:
const trpc = createTRPCClient<AppRouter>({
  links: [httpBatchLink({ url: "http://localhost:3000/trpc" })],
});

// Fully typed - no DTOs, no code generation:
const tasks = await trpc.list.query({ status: "todo" });
// tasks is Task[] ✅ - TypeScript knows because of AppRouter

const newTask = await trpc.create.mutate({ title: "Test", priority: "high" });
// newTask is Task ✅

// If server renames "list" to "listAll":
// → client.list.query() immediately shows a TypeScript error
// → No runtime API mismatch possible

Common Mistakes

  • Importing tRPC router implementation on the client - only import the `type AppRouter`, never the router implementation itself. Use `import type { AppRouter }` to ensure the import is erased at compile time and no server code runs in the browser.
  • Using tRPC for public APIs - tRPC is ideal for same-codebase client-server. For public third-party APIs, REST+OpenAPI (or GraphQL) is better because tRPC requires the TypeScript router type to be shared.
  • Forgetting tRPC is still HTTP underneath - tRPC uses HTTP batch requests by default. Network errors, CORS, and auth headers all apply. It's not magic - it's a typed transport layer on top of standard HTTP.

Tip

Tip

Practice tRPC EndtoEnd TypeSafe APIs Concept in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for tRPC - End-to-End Type-Safe APIs (Concept)

Practice Task

Note

Practice Task - (1) Write a working example of tRPC EndtoEnd TypeSafe APIs Concept from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with tRPC EndtoEnd TypeSafe APIs Concept is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • tRPC eliminates the API contract problem - the server's router type is imported directly by the client, so any change to a server procedure immediately surfaces as a type error on the client.
  • Importing tRPC router implementation on the client - only import the `type AppRouter`, never the router implementation itself. Use `import type { AppRouter }` to ensure the import is erased at compile time and no server code runs in the browser.
  • Using tRPC for public APIs - tRPC is ideal for same-codebase client-server. For public third-party APIs, REST+OpenAPI (or GraphQL) is better because tRPC requires the TypeScript router type to be shared.
  • Forgetting tRPC is still HTTP underneath - tRPC uses HTTP batch requests by default. Network errors, CORS, and auth headers all apply. It's not magic - it's a typed transport layer on top of standard HTTP.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done