0
0
Rest-apiComparisonIntermediate · 4 min read

REST vs tRPC: Key Differences and When to Use Each

REST is a traditional API style using HTTP methods and URLs to manage resources, while tRPC is a modern TypeScript-based RPC framework that enables type-safe, direct function calls between client and server without needing REST endpoints. tRPC offers automatic type inference and simpler client-server communication compared to REST's more manual setup.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of REST and tRPC based on key factors.

FactorRESTtRPC
ArchitectureResource-based with HTTP verbs (GET, POST, etc.)Procedure-based with direct function calls
Type SafetyNo built-in type safety; relies on manual validationFull TypeScript type safety and inference
Setup ComplexityRequires defining routes, controllers, and schemasMinimal setup with automatic type sharing
Client UsageUses HTTP requests with URLs and payloadsCalls server functions directly as if local
PerformanceOverhead of HTTP and JSON parsingLess overhead, uses JSON but optimized calls
Error HandlingManual error codes and messagesBuilt-in structured error handling
⚖️

Key Differences

REST APIs organize communication around resources identified by URLs and use standard HTTP methods like GET, POST, PUT, and DELETE. This approach is language-agnostic and widely supported but requires manual handling of request validation, response formatting, and error management. Developers must define routes and data schemas separately, which can lead to duplicated effort between client and server.

tRPC is designed for TypeScript projects and allows clients to call server functions directly with full type safety. It automatically infers types from server code to client, eliminating the need for manual API schema definitions or client code generation. This reduces bugs and speeds up development by ensuring client and server stay in sync.

While REST is flexible and works across any platform, tRPC is best suited for full-stack TypeScript environments. REST APIs use standard HTTP semantics, making them easy to cache and scale with existing web infrastructure. In contrast, tRPC focuses on developer experience and type correctness, trading some of REST's universal compatibility for tighter integration.

⚖️

Code Comparison

typescript
import express from 'express';

const app = express();
app.use(express.json());

// Sample data
const users = [{ id: 1, name: 'Alice' }];

// REST endpoint to get user by ID
app.get('/users/:id', (req, res) => {
  const id = Number(req.params.id);
  const user = users.find(u => u.id === id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ error: 'User not found' });
  }
});

app.listen(3000, () => {
  console.log('REST API running on http://localhost:3000');
});
Output
REST API running on http://localhost:3000
↔️

tRPC Equivalent

typescript
import { initTRPC } from '@trpc/server';
import express from 'express';
import * as trpcExpress from '@trpc/server/adapters/express';

const t = initTRPC.create();

// Sample data
const users = [{ id: 1, name: 'Alice' }];

const appRouter = t.router({
  getUser: t.procedure.input((id: number) => id).query(({ input }) => {
    const user = users.find(u => u.id === input);
    if (!user) throw new Error('User not found');
    return user;
  }),
});

const app = express();

app.use('/trpc', trpcExpress.createExpressMiddleware({ router: appRouter }));

app.listen(3000, () => {
  console.log('tRPC API running on http://localhost:3000/trpc');
});
Output
tRPC API running on http://localhost:3000/trpc
🎯

When to Use Which

Choose REST when you need broad compatibility across different platforms, languages, or third-party clients. REST is ideal for public APIs, microservices, or when you want to leverage HTTP caching and standard web infrastructure.

Choose tRPC when building full-stack TypeScript applications where you control both client and server. It speeds up development with automatic type safety and simpler client-server communication, reducing bugs and boilerplate.

In summary, REST is best for universal, language-agnostic APIs, while tRPC excels in tightly integrated TypeScript environments focused on developer experience.

Key Takeaways

REST uses resource URLs and HTTP verbs, while tRPC uses direct function calls with TypeScript types.
tRPC provides automatic type safety and reduces manual API schema work compared to REST.
REST is more universal and language-agnostic; tRPC is best for full-stack TypeScript projects.
Choose REST for public APIs and broad compatibility, tRPC for faster TypeScript development.
tRPC simplifies client-server communication but requires TypeScript on both sides.