Why tRPC
tRPC gives you end-to-end type safety between your API and client — no code generation, no GraphQL schema, no OpenAPI spec. Change a server type, and TypeScript catches client errors instantly.
Install
npm install @trpc/server @trpc/client zod
Server
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
getUser: t.procedure
.input(z.object({ id: z.string() }))
.query(async ({ input }) => {
return await db.user.findUnique({ where: { id: input.id } });
}),
createUser: t.procedure
.input(z.object({
name: z.string().min(2),
email: z.string().email(),
}))
.mutation(async ({ input }) => {
return await db.user.create({ data: input });
}),
listUsers: t.procedure
.input(z.object({
page: z.number().default(1),
limit: z.number().max(100).default(20),
}))
.query(async ({ input }) => {
return await db.user.findMany({
skip: (input.page - 1) * input.limit,
take: input.limit,
});
}),
});
export type AppRouter = typeof appRouter;
Client
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
const trpc = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
});
// Full type safety — autocomplete + error checking
const user = await trpc.getUser.query({ id: '123' });
const newUser = await trpc.createUser.mutate({ name: 'Alice', email: 'alice@example.com' });
React Integration
import { trpc } from './utils/trpc';
function UserList() {
const users = trpc.listUsers.useQuery({ page: 1, limit: 10 });
if (users.isLoading) return <div>Loading...</div>;
return users.data.map(u => <div key={u.id}>{u.name}</div>);
}
Key Features
- End-to-end type safety — no code generation
- Zod validation — input validation with types
- Batching — multiple requests in one HTTP call
- Subscriptions — WebSocket support
- React Query — built-in integration
- Middleware — auth, logging, rate limiting
Resources
Need to extract API schemas, type definitions, or endpoint data? Check out my Apify tools or email spinov001@gmail.com for custom solutions.
Top comments (0)