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

tRPC Setup

Share

Set up tRPC for end-to-end typesafe APIs with Next.js

Works with OpenClaude

You are a fullstack TypeScript developer. The user wants to set up tRPC for end-to-end typesafe APIs with Next.js.

What to check first

  • Run npm list next react to confirm Next.js 13+ and React 18+ are installed
  • Verify TypeScript is configured with tsconfig.json in the project root
  • Check that you're in a Next.js project (has next.config.js or next.config.ts)

Steps

  1. Install tRPC and required peer dependencies: npm install @trpc/client @trpc/server @trpc/react-query @tanstack/react-query zod
  2. Create src/server/trpc.ts with initTRPC() to define your tRPC instance and procedures
  3. Define router procedures in src/server/routers/ using router() and publicProcedure or protectedProcedure
  4. Create src/server/routers/_app.ts to merge all routers and export the AppRouter type
  5. Set up the Next.js API route handler at pages/api/trpc/[trpc].ts using createNextApiHandler()
  6. Create a client configuration file src/utils/trpc.ts with createTRPCNext() and HTTP link setup
  7. Wrap your Next.js app with <TRPCProvider> in _app.tsx to enable React Query integration
  8. Call tRPC procedures in components using the trpc hook (e.g., trpc.hello.useQuery())

Code

// src/server/trpc.ts
import { initTRPC } from '@trpc/server';
import { ZodError } from 'zod';

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

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

// src/server/routers/_app.ts
import { router, publicProcedure } from '../trpc';
import { z } from 'zod';

export const appRouter = router({
  hello: publicProcedure
    .input(z.object({ name: z.string() }).optional())
    .query(({ input }) => {
      return `Hello ${input?.name ?? 'World'}`;
    }),
  user: publicProcedure
    .input(z.object({ id: z.number() }))
    .query(({ input }) => {
      return { id: input.id, name: 'John Doe', email: 'john@example.com' };
    }),
  create

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
trpctypescriptnextjs

Install command:

curl -o ~/.claude/skills/trpc-setup.md https://clskills.in/skills/api/trpc-setup.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.