Backend
tRPCTypeScriptAPI
tRPC for End-to-End Type Safety
How we leverage tRPC to ensure type safety from the client to the server.
tRPC for End-to-End Type Safety
tRPC allows us to build fully type-safe APIs without code generation or manual type definitions.
What is tRPC?
tRPC is a TypeScript-first RPC framework that lets you build end-to-end typesafe APIs. It's designed to work seamlessly with React and Next.js.
Key Advantages
Type Safety
- Automatic type inference from server to client
- No manual type definitions needed
- Compile-time error checking
Developer Experience
- Autocomplete for API calls
- Refactoring safety across client and server
- No API documentation needed
Performance
- No runtime overhead
- Tree-shakeable
- Small bundle size
Implementation
Server Setup
// server/api/routers/pdf-converter.ts
export const pdfConverterRouter = createTRPCRouter({
fromHtml: publicProcedure
.input(z.object({
html: z.string(),
fileName: z.string().optional(),
}))
.mutation(async ({ input }) => {
// Implementation
}),
});
Client Usage
// Client component
const pdfMutation = api.pdfConverter.fromHtml.useMutation();
await pdfMutation.mutateAsync({
html: content,
fileName: "document",
});
Benefits for The Workbench
- Safety: Type errors caught at compile time
- Speed: Faster development with autocomplete
- Maintainability: Refactoring is safe and easy
- Documentation: Types serve as documentation