tRPC enables end-to-end type safety between your frontend and backend without schemas, code generation, or REST/GraphQL complexity.
How tRPC Works
Define procedures on the server, call them with full type inference on the client:
Server
import { initTRPC } from "@trpc/server";
import { z } from "zod";
const t = initTRPC.create();
export const appRouter = t.router({
user: t.router({
getById: t.procedure
.input(z.string())
.query(({ input }) => {
return db.users.findById(input);
}),
create: t.procedure
.input(z.object({ name: z.string(), email: z.string().email() }))
.mutation(({ input }) => {
return db.users.create(input);
}),
}),
});
export type AppRouter = typeof appRouter;
Client
import { createTRPCClient } from "@trpc/client";
import type { AppRouter } from "./server";
const trpc = createTRPCClient<AppRouter>({ url: "/api/trpc" });
// Full type inference!
const user = await trpc.user.getById.query("123");
const newUser = await trpc.user.create.mutate({ name: "John", email: "john@example.com" });
Benefits
- No schema files or code generation
- Instant type errors across the stack
- Works with React Query built-in
- Subscriptions for real-time data
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!