Type safety has become increasingly important in modern web development. With TypeScript adoption at an all-time high, developers want that safety to extend across the entire stack.
The Problem with Traditional APIs
REST APIs require manual type definitions on both client and server. GraphQL solves this with code generation, but adds complexity. tRPC offers a simpler path.
const appRouter = router({
user: router({
getById: publicProcedure
.input(z.string())
.query(async ({ input }) => {
return db.user.findUnique({ where: { id: input } });
}),
}),
});
Setting Up Your Project
First, install the required dependencies. We'll use Next.js as our framework, but tRPC works with any React setup.
Pro tip: Use Zod for runtime validation alongside TypeScript's compile-time checks for maximum safety.