CodePark/ questions / Client–server contract
START PRACTICINGPRACTICE
Frontend question · Frontend system design › Client–server contract

Compare REST, GraphQL and tRPC from the frontend's point of view. When would you pick each?

Each one fits a different situation. My default is REST or tRPC for a single web app, and GraphQL when many clients build varied views over the same data.

REST is based on resources and uses normal HTTP meaning, like GET, POST and status codes. Because of that:

  • It works well with HTTP caching and CDNs (content delivery networks).
  • Every client and tool understands it.
  • OpenAPI can generate typed clients.

The downside for the frontend is shape mismatch. You may over-fetch (get fields you don't need), or need several round trips to build one screen.

GraphQL lets the client ask for exactly the fields a screen needs, in one request. It has a typed schema, and fragments that live next to the components that use them. It shines with many clients (web, iOS, Android) and with nested data. It has costs:

  • You must configure a normalised client cache.
  • HTTP caching is harder, because most queries are POSTs to one endpoint.
  • The server needs work on query cost limits and on N+1. The N+1 problem is one query that triggers many small database queries.

tRPC gives end-to-end TypeScript types with no schema and no code generation. It does this by sharing the router's types between server and client. It fits a full-stack TypeScript monorepo where one team owns both sides. It is a poor fit for public APIs, or for clients not written in TypeScript.

  • REST is simple and works with HTTP caching, but the response shape often doesn't match the screen.
  • GraphQL returns exact shapes and suits many clients, but adds cache and server complexity.
  • tRPC gives end-to-end types, but only fits a TypeScript monorepo.
  • The choice depends on how many clients there are and which team owns each side.