REST vs GraphQL vs tRPC in 2026: Choosing an API Style
REST vs GraphQL vs tRPC compared with the same endpoint built three ways: caching, versioning, auth, errors, file uploads, and a decision table by team stage.
By Pavle AleksicWeb DevelopmentUpdated 22 min read
On this page
- The short answer
- The endpoint, three ways
- REST
- GraphQL
- tRPC
- The N+1 trap in GraphQL
- Caching
- Versioning and evolving the contract
- Auth and authorization
- Error handling
- File uploads
- Public vs internal APIs
- What changed by 2026
- Recommendations by team size and stage
- REST vs GraphQL vs tRPC: the decision table
- The decision framework
- Frequently asked questions
- Is GraphQL better than REST?
- Is tRPC a replacement for REST?
- Can tRPC be used with mobile apps?
- Is GraphQL dead in 2026?
- Which API style is fastest?
- Do I need OpenAPI if I use REST?
- Should I use Next.js Server Actions instead of tRPC?
- Working with me
REST vs GraphQL vs tRPC is the wrong fight to have in the abstract. The real question is "who is calling my API, and what do they need from it." I've shipped all three in production, and the failures I've watched were never about the technology being bad. They were about picking GraphQL for a single TypeScript app that had exactly one consumer, or REST for a mobile team that needed forty different response shapes and got versioning hell instead.
The direct answer: use REST with OpenAPI for anything public or consumed by clients you don't control, use tRPC when one TypeScript team owns both the client and the server, and use GraphQL when many different clients genuinely need different slices of the same data. If none of those fits cleanly, REST is the lowest-regret default. The REST vs GraphQL debate in particular is usually settled by one question: do you have a client-driven data-fetching problem, or do you just like the idea of one?
This post is for tech leads and founders making the call, and for developers who'll live with it. I'll build the same endpoint three ways, then walk through the parts that actually decide projects: caching, versioning, auth, error handling, file uploads, and public versus internal APIs. Then recommendations by team size and stage, and a decision table you can paste into an architecture doc.
The short answer
- Public API, partner API, mobile apps you ship to app stores, or any non-TypeScript consumer: REST + OpenAPI.
- Full-stack TypeScript app, one team, one repo (or a shared workspace): tRPC.
- Several distinct clients (web, iOS, Android, partners) with different data needs, and a team that can afford the operational overhead: GraphQL.
- Unsure: REST + OpenAPI. It's boring, and boring is cheap to maintain.
- A common, healthy combo: tRPC (or Server Actions) for your own app, plus a small REST + OpenAPI surface for external consumers.
The endpoint, three ways
The scenario: fetch a user and their recent orders. Trivial on purpose, because the differences show up in the plumbing, not the feature.
REST
REST leans on HTTP. URLs are resources, methods are actions, and the response is whatever the server decides to send.
// GET /api/users/:id?orderLimit=5
import { Hono } from "hono";
import { z } from "zod";
const app = new Hono();
const Query = z.object({ orderLimit: z.coerce.number().int().min(1).max(50).default(5) });
app.get("/api/users/:id", async (c) => {
const id = c.req.param("id");
const parsed = Query.safeParse(c.req.query());
if (!parsed.success) {
return c.json({ type: "about:blank", title: "Invalid query", status: 400 }, 400);
}
const user = await db.user.findUnique({
where: { id },
select: {
id: true,
name: true,
orders: { take: parsed.data.orderLimit, orderBy: { createdAt: "desc" } },
},
});
if (!user) return c.json({ type: "about:blank", title: "Not found", status: 404 }, 404);
c.header("Cache-Control", "private, max-age=30");
return c.json(user);
});The win is that the whole HTTP ecosystem just works. A CDN can cache the response based on Cache-Control. A browser respects ETag. curl debugs it. Any language on earth can call it. The cost is that the response shape is fixed by the server. A mobile client that only wants the user's name still gets the orders, and a dashboard that wants twenty orders needs a parameter. Add enough parameters and you're slowly reinventing a query language.
Pair REST with OpenAPI so the contract is machine-readable. In 2026 I consider this non-negotiable: it's how you get generated clients, request validation, and docs. The OpenAPI Specification is at 3.2 (published September 2025), though most tooling you'll use day to day still targets 3.0 and 3.1.
# openapi.yaml (excerpt)
paths:
/api/users/{id}:
get:
operationId: getUser
parameters:
- name: id
in: path
required: true
schema: { type: string }
- name: orderLimit
in: query
schema: { type: integer, minimum: 1, maximum: 50, default: 5 }
responses:
"200":
description: A user with recent orders
content:
application/json:
schema: { $ref: "#/components/schemas/UserWithOrders" }
"404":
description: Not found
content:
application/problem+json:
schema: { $ref: "#/components/schemas/Problem" }GraphQL
GraphQL flips control. The server exposes a typed graph; the client writes the query and gets back exactly the fields it asked for.
const typeDefs = /* GraphQL */ `
type Order { id: ID!, total: Int!, createdAt: String! }
type User { id: ID!, name: String!, orders(limit: Int = 5): [Order!]! }
type Query { user(id: ID!): User }
`;
const resolvers = {
Query: {
user: (_parent, { id }, ctx) => ctx.db.user.findUnique({ where: { id } }),
},
User: {
// resolved per user. This is where the N+1 hides.
orders: (user, { limit }, ctx) =>
ctx.db.order.findMany({
where: { userId: user.id },
take: Math.min(limit, 50),
orderBy: { createdAt: "desc" },
}),
},
};# mobile: just the name
query { user(id: "1") { name } }
# dashboard: name plus twenty orders
query { user(id: "1") { name orders(limit: 20) { id total createdAt } } }One graph, and every client carves out its own slice with no new endpoints. That's the entire reason GraphQL exists, and for products with many heterogeneous clients it's the right tool. Note the Math.min in the resolver: with GraphQL, the client controls the shape, so you defend limits in the server, every time.
tRPC
tRPC throws out the schema layer entirely. There's no IDL and no codegen. The server's TypeScript types are the contract, and the client imports them.
// server/routers/user.ts
import { initTRPC, TRPCError } from "@trpc/server";
import { z } from "zod";
const t = initTRPC.context<Context>().create();
export const appRouter = t.router({
getUser: t.procedure
.input(z.object({ id: z.string(), orderLimit: z.number().int().min(1).max(50).default(5) }))
.query(async ({ input, ctx }) => {
const user = await ctx.db.user.findUnique({
where: { id: input.id },
select: {
id: true,
name: true,
orders: { take: input.orderLimit, orderBy: { createdAt: "desc" } },
},
});
if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
return user;
}),
});
export type AppRouter = typeof appRouter;// client/profile.tsx: fully typed, zero codegen
import { useQuery } from "@tanstack/react-query";
import { useTRPC } from "./trpc";
export function Profile({ id }: { id: string }) {
const trpc = useTRPC();
const { data, isPending } = useQuery(trpc.getUser.queryOptions({ id, orderLimit: 10 }));
if (isPending) return <Spinner />;
// data.orders[0].total is typed end to end. Rename it on the
// server and this line is a compile error before you commit.
return <h1>{data?.name}</h1>;
}That comment is the whole pitch. Rename name to displayName on the server and your editor lights up red across the frontend instantly. No regenerate step, no drift between client and server. For a TypeScript monorepo where the same team owns both ends, this is the fastest feedback loop you can buy. The client code above uses tRPC v11's TanStack Query integration, which is what the tRPC docs now lead with.
The N+1 trap in GraphQL
GraphQL's flexibility has a sharp edge. That User.orders resolver runs once per user. Fetch a list of 50 users with their orders and you've fired 1 query for the users plus 50 for the orders. That's the N+1 problem, and in GraphQL APIs I've inherited it's the most common reason they fall over under load.
The standard fix is DataLoader, which batches calls made in the same tick of the event loop:
import DataLoader from "dataloader";
// create per request, so caches never leak between users
export function createLoaders(db: Db) {
return {
ordersByUser: new DataLoader(async (userIds: readonly string[]) => {
const orders = await db.order.findMany({ where: { userId: { in: [...userIds] } } });
// must return results in the same order as the input keys
return userIds.map((id) => orders.filter((o) => o.userId === id));
}),
};
}
const resolvers = {
User: { orders: (user, _args, ctx) => ctx.loaders.ordersByUser.load(user.id) },
};Fifty lookups collapse into one query. The point isn't that GraphQL is slow. It's that GraphQL hands you a footgun and expects you to know about DataLoader, query depth limits, and cost analysis on day one. REST and tRPC don't have this problem in the same way because you wrote the single query. With GraphQL, the query is assembled at runtime by a client you may not control.
Caching
This is where the three diverge the most, and it's the factor teams most often discover too late.
REST gets HTTP caching for free. GET requests with Cache-Control, ETag, and Last-Modified work with browsers, CDNs, and reverse proxies as defined in RFC 9111. Public data like a product catalog can be cached at the edge with s-maxage and stale-while-revalidate, and your origin barely notices traffic spikes. If you want the full picture of the layers, I wrote about browser, CDN, and server caching.
GraphQL makes HTTP caching hard. Most clients send every operation as a POST to one URL, so CDNs see nothing cacheable. The workarounds are real but take effort:
- Send queries as
GET(the GraphQL over HTTP working draft allows this for queries, never for mutations). - Use persisted queries so the URL carries a hash instead of a full query document. Apollo's automatic persisted queries are the common implementation.
- Lean on a normalized client cache (Apollo Client, urql's graphcache) for the in-app experience.
- Add per-field cache hints and a cache-aware gateway if you need server-side response caching.
tRPC sits in between. Queries go over GET, so HTTP caching can work. The tRPC caching docs have you set headers through a responseMeta callback, and they flag the catch: batching is on by default, and a batched URL contains every procedure and input in it. One private procedure in the batch should disable caching for the whole response, and the CDN rarely gets a hit on a batched URL anyway. The fix is a splitLink that sends cacheable public queries through the non-batching httpLink. In practice, most tRPC apps are authenticated dashboards where you rely on TanStack Query's client cache and don't CDN-cache API responses at all, which is fine.
If your API serves lots of anonymous, cacheable reads (catalogs, content, public profiles), that alone is a strong argument for REST.
Versioning and evolving the contract
Every API changes. The question is how much it hurts.
REST has three common approaches. URL versioning (/v1/users) is explicit and easy to route, but you end up maintaining parallel code paths. Header versioning keeps URLs clean but is invisible in logs and browser address bars. Date-based versioning, as Stripe does it, pins each account to the API version it integrated against and transforms responses for older versions. It's the best experience for consumers and the most work for you. For most teams I recommend: additive changes only within a version, a v2 only when you truly must break something, and a published deprecation window.
GraphQL avoids versions by design. You add fields freely, mark old ones with @deprecated(reason: "..."), watch field-level usage metrics, and remove a field when traffic hits zero. The GraphQL best practices page is explicit about preferring continuous evolution over versioning. This works well when you have the usage telemetry. Without it, you're guessing who still reads that field.
tRPC doesn't version, because client and server usually deploy together. Rename a field and the compiler finds every call site. The catch is deploy skew: a user with your old frontend bundle open in a tab will call the new server. Additive changes are safe. Renames and removals need a transition period, same as any API: add the new field, ship the client, then remove the old one. If you have mobile apps on tRPC, you have this problem for months, not minutes, which is one reason I don't put native mobile clients on tRPC.
Auth and authorization
Authentication works the same way in all three: a session cookie or bearer token on the request, verified in middleware, attached to a request context. If you're still deciding between cookies and tokens, see JWT vs session cookies. Authorization is where they differ.
REST authorizes per route. DELETE /projects/:id checks "can this user delete this project" and that's the whole surface. It's easy to reason about and easy to audit.
tRPC authorizes per procedure, and its middleware makes this clean:
const authed = t.middleware(({ ctx, next }) => {
if (!ctx.user) throw new TRPCError({ code: "UNAUTHORIZED" });
return next({ ctx: { user: ctx.user } }); // ctx.user is now non-null in the type
});
export const protectedProcedure = t.procedure.use(authed);The narrowed type is the nice part: downstream procedures know ctx.user exists.
GraphQL needs authorization at the field and object level, because any query can reach any part of the graph through relationships. A user who can read their own Order might traverse order.customer.organization.members and read data they shouldn't. The fix is to put authorization in your business logic layer (not only in top-level resolvers), check object ownership wherever an object is returned, and add query depth and cost limits to stop abusive queries. It's very doable. It's also the area where I most often find holes when I audit GraphQL APIs. If you're designing roles and permissions from scratch, I covered the models in designing a permissions system.
Whichever style you pick, rate limit per user and per operation cost, not just per IP. GraphQL especially needs cost-based limits, since one request can be cheap or enormous. More on that in rate limiting strategies.
Error handling
REST uses HTTP status codes, which every tool understands. For the body, use RFC 9457 Problem Details (application/problem+json) so clients get a consistent shape:
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"detail": "Only 2 units of SKU-123 are available.",
"instance": "/orders/req-8f2a"
}GraphQL usually returns HTTP 200 with an errors array, even when something failed, and can return partial data alongside errors. That's a feature (one failing field doesn't kill the whole page) and a monitoring headache, because your HTTP dashboards show everything as green. The GraphQL over HTTP draft tightens status code rules when clients request the application/graphql-response+json media type, but you can't assume every client or server follows it. For expected business errors, I prefer modeling them in the schema as union result types:
type InsufficientStock { sku: String!, available: Int! }
type OrderPlaced { order: Order! }
union PlaceOrderResult = OrderPlaced | InsufficientStock
type Mutation { placeOrder(input: PlaceOrderInput!): PlaceOrderResult! }Clients then handle each case explicitly, and the errors array is reserved for real failures. It's the same idea as TypeScript discriminated unions, applied to your API.
tRPC has TRPCError with codes that map to HTTP statuses (NOT_FOUND to 404, UNAUTHORIZED to 401, TOO_MANY_REQUESTS to 429, and so on). Any other thrown error becomes INTERNAL_SERVER_ERROR. Use an errorFormatter to attach Zod validation details so the client can show field-level form errors with full types. That's genuinely pleasant to work with.
One rule for all three: never leak stack traces or raw database errors to clients. Log them with a request ID and return the ID.
File uploads
Uploads are a good stress test, because none of the three handles them as elegantly as plain HTTP.
My default for all three: don't stream files through your API. Have the API issue a short-lived presigned URL (S3, R2, GCS), let the client upload directly to storage, then call the API to confirm. Your servers never touch the bytes, you avoid request size and timeout limits, and the upload gets the storage provider's bandwidth. This works the same in REST, GraphQL, and tRPC.
When you do need to send the file through your server:
- REST:
multipart/form-datais the native, universally supported answer. Every framework and every client library handles it. - GraphQL: there's a community multipart request spec (
graphql-multipart-request-spec) that many servers support, but Apollo's own file upload guidance says plainly that it does not recommend multipart uploads for new apps and recommends signed URLs. If you do use multipart with Apollo Server, its CSRF prevention requires clients to send a preflight header. Use signed URLs. - tRPC: v11 supports
FormData,File, and binary inputs on mutations, per the non-JSON content types docs. The gotcha: batching links send JSON, so you need asplitLinkthat routes non-JSON inputs throughhttpLink. Works fine once configured. I still use presigned URLs for anything bigger than an avatar.
Public vs internal APIs
This distinction settles more decisions than anything else in this post.
A public API is consumed by people you'll never meet, in languages you don't use, on release schedules you don't control. They need stable URLs, documentation, SDKs or at least an OpenAPI file they can generate from, predictable rate limits, and a deprecation policy measured in months. REST + OpenAPI is the overwhelming standard here. GraphQL public APIs exist and some are excellent, but they ask every consumer to learn GraphQL and push the cost and abuse protection problem onto you. tRPC is not a public API technology: non-TypeScript consumers can't use its types, and its wire format is an implementation detail.
An internal API has consumers you control: your web app, your admin panel, maybe your own mobile app. Here, iteration speed matters more than ubiquity. tRPC shines for TypeScript web clients. In Next.js specifically, Server Actions and server components already cover a lot of what people used tRPC for; I cover the tradeoffs in Server Actions for forms and mutations.
A partner API sits in between: a handful of known integrators. Treat it like a public API. Partners are slower to update than you expect, and "we'll just coordinate the change" stops working at the second partner.
The bridge pattern works well: tRPC internally, and a thin REST + OpenAPI layer for external consumers. Community packages such as trpc-to-openapi can expose selected procedures as REST endpoints with a generated spec. Be aware these are community-maintained, not part of tRPC itself. For a serious public API I'd write the REST layer by hand, with its own stable contract, calling the same service functions your tRPC procedures call.
What changed by 2026
- tRPC is a mature default for TypeScript teams. v11 is the current line (11.23 as of this writing), with first-class TanStack Query integration, FormData and binary inputs, and streaming. It's not a bet anymore.
- GraphQL consolidated around federation and gateways. At scale, teams run a federated gateway composing subgraphs owned by separate teams. For a single team with a single service, that machinery is overhead you don't need.
- REST + OpenAPI never left. It's still the overwhelming majority of public APIs, and the tooling for generating typed clients from an OpenAPI document (
openapi-typescript,orval, and others) is good enough that "REST is untyped" is no longer a fair complaint. - Frameworks absorbed part of the problem. React Server Components and Server Actions mean a Next.js app can read and write data without a separate API layer for its own UI. That shrinks the space where any API style is needed for internal use.
All three are mature. This is a fit decision, not a maturity decision.
Recommendations by team size and stage
Solo founder or 1–3 developers, pre-product-market fit. Use whatever your framework gives you natively. In Next.js, that's server components and Server Actions, with tRPC if you want a typed client-side data layer. Don't build a GraphQL server at this stage; you'll spend weeks on plumbing that doesn't move your product. If you need a public API for an integration, add a few REST endpoints. Cost is a real factor here, and I break down where the money goes in what a SaaS MVP costs.
Small team (4–15 developers), one product, growing. tRPC for the TypeScript web app, REST + OpenAPI for webhooks, integrations, and mobile. This is the combination I recommend most often. It keeps the internal surface fast to change and the external one stable.
Multiple teams, multiple clients. This is where GraphQL earns its keep. If you have separate web, iOS, and Android teams, each needing different data shapes, and backend teams owning different domains, a federated graph gives every client one place to query and every backend team ownership of its subgraph. Budget for a platform owner: schema governance, persisted queries, cost limits, and observability are a job, not a side task.
Platform or API-first company. The API is the product. REST + OpenAPI, versioned carefully, with SDKs generated from the spec and excellent docs. Some platforms add GraphQL as a second, opt-in interface for power users. Do that only after the REST API is solid.
Inheriting an existing API. Don't rewrite it to change style unless the current one is actively blocking you. Wrapping a messy REST API in a clean OpenAPI spec and typed client usually gets you 80% of the benefit for 10% of the effort. I covered how I approach that kind of work in taking over a legacy codebase.
REST vs GraphQL vs tRPC: the decision table
| Factor | REST + OpenAPI | GraphQL | tRPC |
|---|---|---|---|
| Best for | Public, partner, and mobile APIs | Many diverse clients, multiple teams | Full-stack TypeScript apps |
| Contract | OpenAPI document | SDL schema | TypeScript types (no artifact) |
| Codegen needed | Yes, for typed clients | Yes, for typed clients | No |
| Language support | Any | Any | TypeScript clients only |
| Over/under-fetching | Common | Solved by design | Per procedure, your call |
| HTTP/CDN caching | Native and easy | Hard: needs GET + persisted queries | Possible, awkward with batching |
| N+1 risk | Low | High without DataLoader | Low |
| Authorization | Per route | Per field and object | Per procedure |
| Versioning | URL, header, or date-based | Deprecate fields, evolve continuously | Ship client and server together |
| Error model | HTTP status + Problem Details | 200 + errors array, or union results | TRPCError codes mapped to HTTP |
| File uploads | Multipart, native | Signed URLs recommended | FormData on mutations, needs httpLink |
| Client/server coupling | Loose | Loose | Tight |
| Learning curve | Low | High | Low if you know TypeScript |
| Operational overhead | Low | High | Low |
The decision framework
Walk these in order and stop at the first match.
- Is the API public, or consumed by clients you don't own (partners, third parties, other languages)? Use REST + OpenAPI. You need ubiquity, HTTP caching, and a language-agnostic contract. Don't make an external team learn your GraphQL schema or import your TypeScript types.
- Do you own both ends, and is it all TypeScript in one repo or shared workspace? Use tRPC (or your framework's native server functions). End-to-end type safety with zero codegen multiplies a small team's velocity. Accept the coupling; here it's a feature.
- Do you have many genuinely different clients needing different slices of the same data, and is client-driven querying the actual problem? Use GraphQL. Pay the N+1, caching, and authorization tax knowingly. It's worth it when query flexibility is the core requirement, not a nice-to-have.
- None of the above cleanly? Use REST + OpenAPI. It's the lowest-regret default. The cost of boring REST is real but bounded. The cost of GraphQL you didn't need is a permanent operational tax, and the cost of tRPC you outgrow is a migration when a non-TypeScript client shows up.
One more rule I hold to: don't run two styles to dodge a decision. A tRPC core for your own app plus a thin REST layer for external consumers is a legitimate pattern. Standing up GraphQL "for flexibility" on top of a REST API nobody asked to be flexible is how you end up maintaining three contracts for one set of data. Pick the style that fits the consumer in front of you, and add a second only when a real second consumer arrives.
Frequently asked questions
Is GraphQL better than REST?
Neither is better in general. GraphQL is better when many different clients need different shapes of the same data and you can invest in DataLoader, cost limits, and field-level authorization. REST is better for public APIs, cacheable reads, and teams that want low operational overhead, which is most teams.
Is tRPC a replacement for REST?
For internal APIs between a TypeScript frontend and a TypeScript backend, often yes. For public APIs, mobile apps, or any non-TypeScript consumer, no, because the type safety only exists inside your TypeScript codebase. Many teams use tRPC internally and expose a small REST + OpenAPI surface for everyone else.
Can tRPC be used with mobile apps?
React Native apps written in TypeScript can use tRPC, and some teams do. The problem is deploy skew: old app versions stay installed for months and keep calling your server, and tRPC has no versioning story beyond "deploy together." For native iOS and Android apps, REST with an OpenAPI-generated client is the safer choice.
Is GraphQL dead in 2026?
No. It has settled into the niche where it's strongest: larger organizations with multiple clients and multiple backend teams, usually behind a federated gateway. What faded is the idea that every new project should start with GraphQL. For small teams with one web app, tRPC or plain server functions took much of that ground.
Which API style is fastest?
Raw protocol speed rarely matters here; your database queries and caching do. REST tends to win real-world performance for public reads because CDN caching is trivial. GraphQL can reduce round trips for complex screens, but it's also the easiest to make slow through N+1 queries and unbounded nesting.
Do I need OpenAPI if I use REST?
If anyone besides your own frontend calls the API, yes. An OpenAPI document gives consumers generated clients, gives you request validation and docs, and turns "REST is untyped" into a non-issue. For a tiny internal API it's optional, but it's cheap to add early and painful to retrofit.
Should I use Next.js Server Actions instead of tRPC?
For mutations triggered from your own Next.js UI, Server Actions are often enough and need no extra library. tRPC still earns its place when you want a typed API that client components query with caching and invalidation, or when non-Next.js clients in the same monorepo need the same procedures. Many apps use both.
Working with me
If you're designing a new API, deciding whether GraphQL is worth it for your product, or untangling one that grew in three directions at once, that's a core part of the backend development work I do. I've built and maintained REST, GraphQL, and tRPC APIs across 18 years and 600+ projects, and I'm happy to give you a straight answer on which fits your team and stage. Get in touch with a short description of your clients and constraints.