Skip to content
backend-trpc logo

tRPC (Type-Safe API Layer)

backend-trpc

Type-safe API layer for TypeScript full-stack applications. Use when building APIs that need end-to-end type safety between client and server WITHOUT code generation. Ideal for Next.js, React, and Express apps where both frontend and backend are TypeScript. Choose tRPC over REST/GraphQL when you ...

SKILL.md

Full skill instructions

tRPC (Type-Safe API Layer)

Overview

tRPC enables end-to-end typesafe APIs by sharing TypeScript types between client and server. No code generation, no schema files—just TypeScript.

Version: v11.7+ (2024-2025)
Requirements: TypeScript ≥5.7.2 with strict mode

Key Benefit: Change a procedure's input/​output → TypeScript errors appear immediately on client.

When to Use This Skill

✅ Use tRPC when:

  • Building full-stack TypeScript apps (Next.js, React + Express)
  • You control both client and server code
  • Need type-safe API without GraphQL complexity
  • Want automatic request batching and caching
  • Building internal APIs, dashboards, admin panels

❌ Don't use tRPC when:

  • External clients need REST/​OpenAPI (use tRPC + OpenAPI adapter)
  • Non-TypeScript clients (mobile apps, third-party integrations)
  • Microservices with different languages

Quick Start

Installation

npm install @trpc/​server @trpc/​client zod

# For React/​Next.js:
npm install @trpc/​react-query @tanstack/​react-query@^5

Core Setup

Always create tRPC instance in a dedicated file:

// src/​server/​trpc.ts
import { initTRPC, TRPCError } from '@trpc/​server';
import { z } from 'zod';

interface Context {
  user?: { id: string; role: string };
  db: PrismaClient;
}

const t = initTRPC.context<Context>().create({
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError: error.cause instanceof z.ZodError 
          ? error.cause.flatten() 
          : null,
      },
    };
  },
});

export const router = t.router;
export const publicProcedure = t.procedure;
export const middleware = t.middleware;
export const createCallerFactory = t.createCallerFactory;

Procedure Patterns

Query vs Mutation

// src/​server/​routers/​user.ts
import { z } from 'zod';
import { router, publicProcedure, protectedProcedure } from '../​trpc';
import { TRPCError } from '@trpc/​server';

export const userRouter = router({
  // Query - GET semantics (reads)
  getById: publicProcedure
    .input(z.object({ id: z.string().uuid() }))
    .query(async ({ input, ctx }) => {
      const user = await ctx.db.user.findUnique({ where: { id: input.id } });
      if (!user) throw new TRPCError({ code: 'NOT_FOUND' });
      return user;
    }),

  // Mutation - POST/​PUT/​DELETE semantics (writes)
  create: protectedProcedure
    .input(z.object({
      name: z.string().min(2).max(100),
      email: z.string().email(),
    }))
    .mutation(async ({ input, ctx }) => {
      return ctx.db.user.create({ data: input });
    }),
});

Cursor-Based Pagination

list: publicProcedure
  .input(z.object({
    limit: z.number().min(1).max(100).default(10),
    cursor: z.string().uuid().optional(),
  }))
  .query(async ({ input, ctx }) => {
    const items = await ctx.db.user.findMany({
      take: input.limit + 1,
      cursor: input.cursor ? { id: input.cursor } : undefined,
      orderBy: { createdAt: 'desc' },
    });
    
    let nextCursor: string | undefined;
    if (items.length > input.limit) {
      nextCursor = items.pop()?.id;
    }
    return { items, nextCursor };
  }),

Middleware Patterns

Authentication Middleware

const isAuthed = middleware(async ({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({ ctx: { user: ctx.user } });
});

export const protectedProcedure = publicProcedure.use(isAuthed);

Role-Based Authorization

const hasRole = (role: string) => middleware(async ({ ctx, next }) => {
  if (ctx.user?.role !== role) {
    throw new TRPCError({ code: 'FORBIDDEN' });
  }
  return next();
});

export const adminProcedure = protectedProcedure.use(hasRole('admin'));

Logging Middleware

const loggerMiddleware = middleware(async ({ path, type, next }) => {
  const start = Date.now();
  const result = await next();
  console.log(`[${type}] ${path} - ${Date.now() - start}ms`);
  return result;
});

Context Creation

Express Adapter

// src/​server/​context.ts
import { CreateExpressContextOptions } from '@trpc/​server/​adapters/​express';
import { prisma } from '../​lib/​prisma';

export async function createContext({ req }: CreateExpressContextOptions) {
  const token = req.headers.authorization?.split(' ')[1];
  const user = token ? await verifyToken(token) : null;
  
  return { user, db: prisma };
}

export type Context = Awaited<ReturnType<typeof createContext>>;

Express Server Setup

// src/​server/​index.ts
import express from 'express';
import cors from 'cors';
import { createExpressMiddleware } from '@trpc/​server/​adapters/​express';
import { appRouter } from './​routers/​_app';
import { createContext } from './​context';

const app = express();
app.use(cors());
app.use('/​trpc', createExpressMiddleware({
  router: appRouter,
  createContext,
}));

app.listen(3000);

Router Merging

// src/​server/​routers/​_app.ts
import { router } from '../​trpc';
import { userRouter } from './​user';
import { postRouter } from './​post';

export const appRouter = router({
  user: userRouter,
  post: postRouter,
});

export type AppRouter = typeof appRouter;

Rules

Do ✅

  • Use Zod for all input validation
  • Create separate routers per domain and merge them
  • Use TRPCError with appropriate codes
  • Enable strict mode in TypeScript
  • Use httpBatchLink on client for request batching
  • Export AppRouter type for client

Avoid ❌

  • Mixing v10 and v11 patterns (breaking changes)
  • Skipping input validation
  • Throwing non-TRPCError exceptions (wrap them)
  • Creating multiple tRPC instances
  • Using any for context types

Error Codes Reference

CodeHTTPUse Case
BAD_REQUEST400Invalid input
UNAUTHORIZED401No/​invalid auth
FORBIDDEN403No permission
NOT_FOUND404Resource missing
CONFLICT409Already exists
INTERNAL_SERVER_ERROR500Unexpected error

Troubleshooting

"Types not updating on client":
  → Run TypeScript server in watch mode
  → Check AppRouter is exported and imported correctly
  → Verify tsconfig paths match

"Input validation errors not showing":
  → Add zodError to errorFormatter
  → Use .safeParse() on client for detailed errors

"CORS errors":
  → Configure cors() before tRPC middleware
  → Check origin whitelist

"Procedures not batching":
  → Ensure using httpBatchLink on client
  → Check all requests go to same endpoint

File Structure

src/​server/
├── trpc.ts              # tRPC instance, base procedures
├── context.ts           # Context creation
└── routers/
    ├── _app.ts          # Root router (merges all)
    ├── user.ts          # User procedures
    └── post.ts          # Post procedures

References

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View