Set up tRPC for end-to-end typesafe APIs with Next.js
✓Works with OpenClaudeYou 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 reactto confirm Next.js 13+ and React 18+ are installed - Verify TypeScript is configured with
tsconfig.jsonin the project root - Check that you're in a Next.js project (has
next.config.jsornext.config.ts)
Steps
- Install tRPC and required peer dependencies:
npm install @trpc/client @trpc/server @trpc/react-query @tanstack/react-query zod - Create
src/server/trpc.tswithinitTRPC()to define your tRPC instance and procedures - Define router procedures in
src/server/routers/usingrouter()andpublicProcedureorprotectedProcedure - Create
src/server/routers/_app.tsto merge all routers and export theAppRoutertype - Set up the Next.js API route handler at
pages/api/trpc/[trpc].tsusingcreateNextApiHandler() - Create a client configuration file
src/utils/trpc.tswithcreateTRPCNext()and HTTP link setup - Wrap your Next.js app with
<TRPCProvider>in_app.tsxto enable React Query integration - Call tRPC procedures in components using the
trpchook (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
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.