Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
API DevelopmentintermediateNew

tRPC Router

Share

Build tRPC routers with input validation and middleware

Works with OpenClaude

You are a backend API developer building type-safe RPC routers. The user wants to create tRPC routers with input validation and middleware.

What to check first

  • Run npm list trpc zod to verify tRPC and Zod are installed (Zod is the recommended validator)
  • Check your tRPC version with npm view trpc version — this skill uses v10+ syntax

Steps

  1. Import initTRPC from @trpc/server and create a tRPC instance with initTRPC.create()
  2. Define your context type — a function that returns an object with authenticated user, database, or request metadata
  3. Create a base procedure using t.procedure that will inherit context automatically
  4. Define input validation schemas using zod (e.g., z.object({ id: z.string().uuid() }))
  5. Build individual procedures by chaining .input(schema).query() or .mutation() with resolver logic
  6. Apply middleware to procedures using .use() for authentication, logging, or rate limiting
  7. Combine procedures into routers using t.router({ procedureName: procedure })
  8. Merge routers with t.mergeRouters() to organize by domain

Code

import { initTRPC, TRPCError } from '@trpc/server';
import { z } from 'zod';

// Define context type
interface Context {
  userId?: string;
  isAdmin: boolean;
  db: any;
}

// Create tRPC instance
const t = initTRPC.context<Context>().create();

// Define middleware for authentication
const isAuthed = t.middleware(async ({ ctx, next }) => {
  if (!ctx.userId) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next();
});

// Create protected procedure
const protectedProcedure = t.procedure.use(isAuthed);

// Define input schemas
const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1),
  role: z.enum(['user', 'admin']).default('user'),
});

const getUserSchema = z.object({
  id: z.string().uuid(),
});

// Build user router
const userRouter = t.router({
  create: protectedProcedure
    .input(createUserSchema)
    .mutation(async ({ ctx, input }) => {
      const user = await ctx.db.user.create({
        data: input,
      });
      return { id: user.id, email: user.email };
    }),

  getById: t.procedure
    .input(getUserSchema)
    .query(async ({ ctx, input }) => {
      return await ctx.db.user.findUnique({
        where: { id: input.id },
      });
    }),

  list: protected

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Not validating request bodies before processing — attackers will send malformed payloads to crash your service
  • Returning detailed error messages in production — leaks internal architecture to attackers
  • Forgetting CORS headers — frontend will silently fail with cryptic browser errors
  • Hardcoding API keys in code — use environment variables and secret management
  • No rate limiting — one client can DoS your entire API

When NOT to Use This Skill

  • When a single shared library would suffice — APIs add network latency and failure modes
  • For internal-only data flow within the same process — use direct function calls
  • When you need transactional consistency across services — APIs can't guarantee this without distributed transactions

How to Verify It Worked

  • Test all CRUD operations end-to-end including error cases (404, 401, 403, 500)
  • Run an OWASP ZAP scan against your API — catches common security issues automatically
  • Load test with k6 or Artillery — verify your API holds up under realistic traffic
  • Verify rate limits actually trigger when exceeded — they often don't due to misconfiguration

Production Considerations

  • Version your API from day one (/v1/) — breaking changes are inevitable, give yourself a path
  • Set request size limits — prevents memory exhaustion attacks
  • Add structured logging with request IDs — trace every request across your stack
  • Document your API with OpenAPI — generates client SDKs and interactive docs for free

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
trpcroutervalidation

Install command:

curl -o ~/.claude/skills/trpc-router.md https://clskills.in/skills/api/trpc-router.md

Related API Development Skills

Other Claude Code skills in the same category — free to download.

Want a API Development skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.