ts-rest: Contract-First REST APIs
What you'll learn: How ts-rest uses shared contracts to achieve end-to-end type safety between REST servers and clients without code generation.
The Core Idea
ts-rest takes a different approach than tRPC's RPC model—it embraces REST conventions (HTTP methods, status codes, paths) but adds contract-first type safety. You define a single TypeScript contract that describes your REST API's routes, then both your server implementation and client calls derive types from that contract.
Think of it like a legally binding document that both parties (server and client) must honor. The contract specifies "POST /users with this body shape returns 201 with this response shape," and TypeScript ensures both sides comply.
How It Works
Unlike tRPC where you define procedures that become the contract, ts-rest starts with an explicit route contract object. This contract defines:
- HTTP method and path
- Request body, query parameters, path parameters schemas
- Response status codes and their corresponding body types
- Headers if needed
Both server and client import this same contract. The server implements handlers that must match the contract's signatures. The client gets fully typed methods that correspond to each route—with proper URL building, body typing, and response typing.
The Contract-First Philosophy
The contract acts as a shared source of truth living in your monorepo or shared package. When you change an endpoint's contract—say, adding a required field—both the server implementation and every client call show type errors until updated. This prevents the drift that plagues traditional REST APIs where the client "hopes" the server matches expectations.
Unlike OpenAPI generators that create types from YAML, ts-rest's contract is TypeScript—you get immediate feedback, refactoring support, and IDE autocomplete while defining the API itself.
Key Takeaway: ts-rest bridges the gap between REST's ubiquity and tRPC's type safety by treating a TypeScript contract as the single source of truth for both server and client, giving you type-safe REST APIs without code generation.