Getting Started with tRPC: A Beginner’s Guide to Type-Safe APIs
Vimal Prakash
Director of Software Engineering at Skillmine Technology Consulting | Driving Innovation and Excellence in Technology Solutions
APIs are the backbone of modern web applications, but they often involve tedious boilerplate, type mismatches, and runtime errors. Enter tRPC—a revolutionary library that simplifies API development with end-to-end type safety. If you're building full-stack TypeScript applications, tRPC is here to make your life easier.
In this article, we’ll explore what tRPC is, why it’s worth considering, and how to get started in a few simple steps.
What is tRPC?
tRPC stands for TypeScript Remote Procedure Call, a library that enables you to create APIs with type safety shared between your client and server. Unlike traditional API tools like REST or GraphQL, tRPC eliminates the need for schema synchronization and code generation. Instead, it leverages TypeScript to provide a seamless development experience.
Why Choose tRPC?
Getting Started
Here’s how you can set up tRPC in your project:
Step 1: Install tRPC
Install the required packages:
npm install @trpc/server @trpc/client @trpc/react-query
Step 2: Define Your API
Create a router to define your API endpoints.
领英推荐
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const appRouter = t.router({
getUser: t.procedure
.input((val: { id: string }) => val) // Validate input
.query(({ input }) => {
return { id: input.id, name: 'John Doe' }; // Example response
}),
});
export type AppRouter = typeof appRouter;
Step 3: Integrate with Your Server
Use an adapter (e.g., Express) to serve your API.
import express from 'express';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
import { appRouter } from './router';
const app = express();
app.use(
'/trpc',
createExpressMiddleware({
router: appRouter,
createContext: () => null,
})
);
app.listen(3000, () => console.log('Server is running on https://localhost:3000'));
Step 4: Consume the API on the Client
Set up a client to call your API:
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './router';
const client = createTRPCProxyClient<AppRouter>({
links: [httpBatchLink({ url: 'https://localhost:3000/trpc' })],
});
// Fetch user data
const user = await client.getUser.query({ id: '123' });
console.log(user); // { id: '123', name: 'John Doe' }
When to Use tRPC
tRPC is perfect for:
Final Thoughts
tRPC is a powerful tool that bridges the gap between API and client development by leveraging the full potential of TypeScript. With its simplicity, type safety, and performance, it’s a must-try for modern developers.
?? Ready to dive in? Explore the tRPC Documentation and start building type-safe APIs today!