Build tRPC routers with input validation and middleware
✓Works with OpenClaudeYou 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 zodto 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
- Import
initTRPCfrom@trpc/serverand create a tRPC instance withinitTRPC.create() - Define your context type — a function that returns an object with authenticated user, database, or request metadata
- Create a base procedure using
t.procedurethat will inherit context automatically - Define input validation schemas using
zod(e.g.,z.object({ id: z.string().uuid() })) - Build individual procedures by chaining
.input(schema).query()or.mutation()with resolver logic - Apply middleware to procedures using
.use()for authentication, logging, or rate limiting - Combine procedures into routers using
t.router({ procedureName: procedure }) - 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
Related API Development Skills
Other Claude Code skills in the same category — free to download.
REST API Scaffold
Scaffold a complete REST API with CRUD operations
GraphQL Schema Generator
Generate GraphQL schema from existing data models
API Documentation
Generate OpenAPI/Swagger documentation from code
API Versioning
Implement API versioning strategy
Rate Limiter
Add rate limiting to API endpoints
API Error Handler
Create standardized API error handling
Request Validator
Add request validation middleware (Zod, Joi)
API Response Formatter
Standardize API response format
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.