Skip to main content
skillsFirst-partyReview first Safety · Privacy ·

tRPC Type-Safe API Builder Skill

Build end-to-end type-safe APIs with tRPC and TypeScript, eliminating code generation and runtime bloat for full-stack applications. tRPC provides end-to-end type safety without code generation, schema stitching, or serialization layers - delivering a lighter, more intuitive developer experience than REST or GraphQL.

by JSONbored·added 2025-10-16·
Claude CodeCodexWindsurfGeminiCursorCLI
HarnessClaude CodeCodexWindsurfGeminiCursorCLI
Level:advancedType:generalVerified:draft
Review first review before installing

Open the source and read safety notes before installing.

Prerequisites

  • Node.js 18+
  • TypeScript 5.0+
  • @trpc/server ^10.0.0
  • @trpc/client ^10.0.0
  • @trpc/react-query ^10.0.0
  • TypeScript 5.0+ for full type inference and end-to-end type safety between client and server

Schema details

Install type
package
Reading time
6 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Package metadata
Package verified
Yes
SHA-256
33c0ad29db6fc2f841bd0bf3521a4ebb8111a34d702a317745ea11735d7422c0
Skill and platform metadata
Skill type
general
Skill level
advanced
Verification
draft
Verified at
2025-10-16
Retrieval sources
https://trpc.io/docs/
Tested platforms
ClaudeCodexOpenClawCursorWindsurfGemini
PlatformSupportInstall path
claude-codeNative.claude/skills/<skill-name>/SKILL.md
codexNative.agents/skills/<skill-name>/SKILL.md
windsurfNative.windsurf/skills/<skill-name>/SKILL.md
geminiNative.gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md
cursorAdapter.cursor/rules/<skill-name>.mdc
cliManualAGENTS.md or tool-specific context file
Full copyable content
import { initTRPC, TRPCError } from '@trpc/server';
import { z } from 'zod';
import { db } from './db';

// Context creation
export const createContext = async ({ req }: { req: Request }) => {
  const token = req.headers.get('authorization')?.replace('Bearer ', '');
  const user = token ? await verifyToken(token) : null;
  
  return {
    db,
    user,
  };
};

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

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

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

// Procedures
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(isAuthed);

// Router
export const appRouter = t.router({
  users: t.router({
    list: publicProcedure.query(async ({ ctx }) => {
      return ctx.db.user.findMany();
    }),
    
    create: protectedProcedure
      .input(
        z.object({
          name: z.string().min(3),
          email: z.string().email(),
        })
      )
      .mutation(async ({ ctx, input }) => {
        return ctx.db.user.create({
          data: input,
        });
      }),
  }),
});

export type AppRouter = typeof appRouter;

About this resource

What This Skill Enables

Claude can build fully type-safe APIs using tRPC (TypeScript Remote Procedure Call), part of the T3 Stack explosion in 2025. tRPC provides end-to-end type safety without code generation, schema stitching, or serialization layers - delivering a lighter, more intuitive developer experience than REST or GraphQL. With zero dependencies, tiny client-side footprint, and automatic type inference, tRPC makes full-stack TypeScript development actually enjoyable.

Compatibility

Native

  • Claude Code / Claude: native skill usage via SKILL.md.
  • Codex/OpenAI workflows: compatible with Agent Skills-style SKILL.md content as reusable workflow instructions.

Manual Adaptation

  • Gemini CLI: native skill usage via .gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md where supported.
  • Cursor: use the generated .cursor/rules/*.mdc adapter for project rules.
  • OpenClaw and similar agents: use the same skill content as a reusable prompt/workflow file when native skill import is unavailable.

Prerequisites

Required:

  • Claude Pro subscription or Claude Code CLI
  • Node.js 18+ with TypeScript 5.0+
  • Understanding of React or Next.js
  • Basic API development knowledge

What Claude handles automatically:

  • Setting up tRPC server with Express, Next.js, or standalone
  • Creating type-safe routers and procedures
  • Implementing middleware for authentication
  • Generating React Query hooks automatically
  • Adding input validation with Zod
  • Configuring error handling and transformers
  • Setting up WebSocket subscriptions
  • Integrating with Prisma or other ORMs

How to Use This Skill

Create Basic tRPC API

Prompt: "Set up a tRPC API with Next.js 15 that has procedures for creating, reading, updating, and deleting todos. Include Zod validation and automatic React Query hooks."

Claude will:

  1. Initialize tRPC router with type-safe procedures
  2. Add Zod schemas for input validation
  3. Create CRUD operations with proper types
  4. Set up Next.js API route handlers
  5. Generate React hooks for client usage
  6. Include error handling and transformers
  7. Add TypeScript types exported automatically

Authentication Middleware

Prompt: "Add JWT authentication middleware to my tRPC API. Protected procedures should verify the token and attach user data to context."

Claude will:

  1. Create authentication middleware
  2. Verify JWT tokens with jose library
  3. Extend tRPC context with user data
  4. Create protected procedure wrapper
  5. Add type-safe context typing
  6. Include refresh token logic
  7. Implement role-based authorization

Real-Time Subscriptions

Prompt: "Build a tRPC subscription that sends real-time notifications when new messages are posted. Use WebSocket transport."

Claude will:

  1. Configure WebSocket link on client
  2. Create subscription procedure
  3. Implement event emitter pattern
  4. Add connection status handling
  5. Include automatic reconnection
  6. Type subscription payloads properly
  7. Add subscription filters

Full-Stack T3 App

Prompt: "Create a complete T3 Stack application with tRPC, Prisma, NextAuth, and Tailwind. Include user authentication, database models, and type-safe API routes."

Claude will:

  1. Initialize T3 app with create-t3-app
  2. Set up Prisma schema and migrations
  3. Configure NextAuth providers
  4. Create tRPC routers for all features
  5. Build authenticated UI components
  6. Add optimistic updates with React Query
  7. Include comprehensive error handling

Tips for Best Results

  1. Use Zod for Validation: tRPC integrates perfectly with Zod. Always request Zod schemas for input validation to get runtime safety matching TypeScript types.

  2. Leverage Context: Put database clients, auth sessions, and shared utilities in tRPC context for type-safe access across all procedures.

  3. React Query Integration: tRPC's React hooks are powered by React Query. Request configurations for caching, refetching, and optimistic updates.

  4. Organize with Sub-Routers: For large APIs, ask Claude to split procedures into feature-based sub-routers (users, posts, comments) merged into a root router.

  5. Type Inference Magic: tRPC's inferProcedureInput and inferProcedureOutput utilities maintain types across client/server. Request these for shared type definitions.

  6. Error Handling: Use tRPC's TRPCError with specific codes (BAD_REQUEST, UNAUTHORIZED, etc.) for consistent error responses.

Common Workflows

E-Commerce API

"Build a type-safe e-commerce API with tRPC:
1. Product catalog with filtering and search
2. Shopping cart management
3. Order processing with Stripe
4. User authentication with NextAuth
5. Admin dashboard procedures
6. Real-time inventory updates
7. Include Zod validation and Prisma integration"

Social Media Backend

"Create a social media backend using tRPC:
1. User profiles with follow/unfollow
2. Posts with likes and comments
3. Real-time notifications via subscriptions
4. Image uploads to S3
5. Feed algorithm with pagination
6. Direct messaging between users
7. Content moderation procedures"

SaaS Multi-Tenant API

"Build a multi-tenant SaaS API with tRPC:
1. Organization and team management
2. Role-based access control middleware
3. Usage tracking and billing
4. Webhook integrations
5. Audit logging for all actions
6. Rate limiting per tenant
7. Data isolation at database level"

AI Chat Application

"Create a chat app with tRPC and streaming:
1. OpenAI integration with streaming responses
2. Chat history with Prisma
3. Real-time message updates
4. Typing indicators via subscriptions
5. File uploads for context
6. Conversation summarization
7. Cost tracking per user"

Troubleshooting

Issue: Type errors between client and server Solution: Ensure both use the same TypeScript version and tRPC version. Export AppRouter type from server and import on client. Run tsc --noEmit to catch type issues.

Issue: Queries not refetching properly Solution: Configure React Query's staleTime and cacheTime. Use utils.invalidate() after mutations or enable optimistic updates with onMutate.

Issue: Authentication context undefined Solution: Verify middleware runs before protected procedures. Check that createContext properly extracts auth token from headers. Ensure client passes credentials.

Issue: Slow API responses Solution: Add database query optimization, implement batching with DataLoader pattern, use tRPC's batching link on client, and consider Redis caching for expensive operations.

Issue: WebSocket subscriptions disconnecting Solution: Implement heartbeat/ping-pong pattern, add automatic reconnection with exponential backoff, check firewall/proxy timeouts, and use connection pooling.

Issue: Zod validation too strict Solution: Use .optional(), .nullable(), or .default() on schema fields. For flexible objects, use z.record() or .passthrough() to allow extra keys.

Learn More

Features

  • End-to-end type safety without code generation - TypeScript types flow from server to client automatically
  • Zero runtime dependencies and tiny bundle size - minimal overhead compared to GraphQL or REST
  • Automatic React Query hooks generation with @trpc/react-query for seamless data fetching
  • WebSocket subscriptions support for real-time updates with observable pattern
  • Middleware system for authentication, logging, rate limiting, and custom logic
  • Zod integration for runtime input validation matching TypeScript types
  • Batching support for multiple queries in single HTTP request for performance
  • Adapters for Express, Next.js, Fastify, and standalone servers with flexible deployment

Use Cases

  • Full-stack TypeScript applications with shared types between client and server
  • Real-time collaborative apps with WebSocket subscriptions and live updates
  • Type-safe microservices communication with end-to-end type inference
  • T3 Stack applications (Next.js, tRPC, Prisma, NextAuth, Tailwind)
  • Monorepo architectures with shared type definitions across packages
  • API-first development with automatic client generation and type safety
#trpc#typescript#api#type-safety#t3-stack

Source citations

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.