Next.js API Design: REST Patterns, Errors, and Limits
Route handlers make it trivial to stand up an endpoint â export a GET function and you have a URL. What they do not give you is an API design: consistent resource naming, predictable error shapes, pagination that scales, protection against abuse, and a versioning story for the day a breaking change arrives. APIs assembled one handler at a time without those conventions accumulate into the kind of surface area that clients special-case forever.
This lesson treats your route handlers as a product. It defines the response envelope, the error contract, the pagination model, a rate limiter that actually works across requests, and a versioning approach that lets you evolve without stranding consumers.
Prerequisites
- !Comfort with app/api route handlers
- !Experience returning NextResponse.json
- !A database access layer already in place
What You'll Learn
- 1Design resource-oriented URLs and status code discipline
- 2Return a consistent success and error envelope
- 3Implement cursor pagination for growing collections
- 4Add rate limiting and versioning that hold up in production
Resources before handlers
Name URLs after nouns, use HTTP verbs for actions, and let nesting express ownership â one level of nesting is usually the maximum before paths become unreadable.
| Method | Path | Meaning | Success status |
|---|---|---|---|
| GET | /api/v1/invoices | List invoices | 200 |
| POST | /api/v1/invoices | Create invoice | 201 |
| GET | /api/v1/invoices/:id | Fetch one invoice | 200 |
| PATCH | /api/v1/invoices/:id | Partial update | 200 |
| DELETE | /api/v1/invoices/:id | Remove invoice | 204 |
| GET | /api/v1/customers/:id/invoices | Invoices of one customer | 200 |
Status codes are part of the contract. 201 for creation tells monitoring a row was written; 204 for deletion tells the client not to expect a body; 404 versus 403 distinguishes missing from forbidden, which matters when hiding existence is itself a requirement.
One envelope for success, one for errors
Clients should never have to guess whether a field lives at the root or under data. Pick a shape, document it, and return it from every handler without exception.
// app/api/v1/invoices/route.js
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { requireSession } from '@/lib/api-auth';
import { listInvoices, createInvoice } from '@/lib/invoices';
const CreateSchema = z.object({
customerId: z.string().uuid(),
amountCents: z.number().int().positive(),
currency: z.string().length(3).default('usd'),
});
export async function GET(request) {
const auth = await requireSession(request);
if (auth.error) return auth.error;
const { searchParams } = new URL(request.url);
const cursor = searchParams.get('cursor');
const limit = Math.min(Number(searchParams.get('limit') ?? 25), 100);
const page = await listInvoices({
orgId: auth.session.orgId,
cursor,
limit,
});
return NextResponse.json({
data: page.items,
pagination: {
nextCursor: page.nextCursor ?? null,
limit,
},
});
}
export async function POST(request) {
const auth = await requireSession(request);
if (auth.error) return auth.error;
const body = await request.json().catch(() => null);
const parsed = CreateSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{
error: {
code: 'VALIDATION_ERROR',
message: 'Invoice payload is invalid.',
details: parsed.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
})),
},
},
{ status: 400 }
);
}
const invoice = await createInvoice({
orgId: auth.session.orgId,
...parsed.data,
});
return NextResponse.json({ data: invoice }, { status: 201 });
}
The envelope pairs data with pagination on success, and a structured error object on failure. Error codes are stable machine-readable strings; messages are human-readable and may change without breaking clients that switch on code.
Cursor pagination that survives growth
Offset pagination breaks past a few thousand rows: inserts shift pages under the reader's cursor, and deep offsets force the database to scan everything before discarding it. A keyset cursor encodes the last row's sort key so the next page is a single indexed range scan.
// lib/invoices.js
export async function listInvoices({ orgId, cursor, limit }) {
const rows = await db.invoice.findMany({
where: { orgId, ...(cursor ? { id: { lt: cursor } } : {}) },
orderBy: { id: 'desc' },
take: limit + 1,
});
const hasMore = rows.length > limit;
const items = hasMore ? rows.slice(0, limit) : rows;
return {
items,
nextCursor: hasMore ? items[items.length - 1].id : null,
};
}
Fetching one extra row is the standard way to detect hasMore without a second count query. Document that cursors are opaque: clients must round-trip them untouched, which leaves you free to change their encoding later.
Filtering, sorting, and field selection that stay predictable
Collections invite query parameters, and unguided query parameters become a query planner's worst enemy. A practical API restricts filtering to an allowlist of indexed fields, caps the number of filters per request, and rejects anything else with a 400 that names the supported options â silently ignoring an unknown filter is worse than rejecting it, because the client believes its query was honored. Sorting has the same constraint: offer two or three documented sort keys, each with a stable tiebreaker appended so pagination does not skip or repeat rows that sort equal.
Field selection is the quiet performance lever. A list endpoint that returns every column forces the database to materialize data the client discards and pays serialization cost for the privilege. A fields parameter â comma-separated, allowlisted â lets list consumers ask for id, name, and total while detail consumers get everything. The implementation is a projection built from the allowlist intersection, never a passthrough of user input into column names.
Rate and size limits belong here too: a limit parameter with a hard server-side maximum, a default that suits the common case, and a response header echoing what was applied. An API that lets a client request ten thousand rows per page has not empowered the client; it has handed them a denial-of-service tool pointed at your own database.
Rate limiting that survives multiple instances
An in-memory Map of request timestamps works in a single process and lies in production, where several serverless instances each see a fraction of the traffic. Move the counter to a shared store â Redis, or an Upstash-compatible HTTP store when the route runs on Edge.
// lib/rate-limit.js
import { redis } from '@/lib/redis';
export async function rateLimit(key, { limit, windowSec }) {
const now = Date.now();
const windowStart = now - windowSec * 1000;
const bucket = `rl:${key}:${Math.floor(now / 1000 / windowSec)}`;
const current = await redis.incr(bucket);
if (current === 1) {
await redis.expire(bucket, windowSec);
}
const remaining = Math.max(0, limit - current);
const allowed = current <= limit;
return {
allowed,
remaining,
retryAfter: allowed ? 0 : windowSec,
};
}
// Usage inside a route handler
const { allowed, remaining, retryAfter } = await rateLimit(
`invoice-create:${auth.session.orgId}`,
{ limit: 30, windowSec: 60 }
);
if (!allowed) {
return NextResponse.json(
{ error: { code: 'RATE_LIMITED', message: 'Too many requests.' } },
{
status: 429,
headers: {
'Retry-After': String(retryAfter),
'X-RateLimit-Remaining': '0',
},
}
);
}
Emitting X-RateLimit-Remaining on every response lets well-behaved clients slow down before they are blocked, which turns rate limiting from a wall into a speed bump.
Idempotency for requests that must not double
Rate limiting protects the server from volume; idempotency protects the client from its own retries. When a POST create-invoice request times out, the client has no way of knowing whether the write landed. Without idempotency support, a responsible retry after two seconds produces a duplicate invoice and an uncomfortable customer conversation. The standard answer is an Idempotency-Key header: the client generates a UUID per logical operation and sends it with the request.
// app/api/v1/invoices/route.js â idempotent POST fragment
export async function POST(request) {
const idKey = request.headers.get('idempotency-key');
if (!idKey) {
return NextResponse.json(
{ error: { code: 'MISSING_IDEMPOTENCY_KEY', message: 'Header required.' } },
{ status: 400 }
);
}
const existing = await findIdempotentResponse(idKey);
if (existing) {
return NextResponse.json(existing.body, {
status: existing.status,
headers: { 'Idempotent-Replay': 'true' },
});
}
const invoice = await createInvoice(await parseInvoice(request));
await storeIdempotentResponse(idKey, invoice, 201, 86400);
return NextResponse.json({ data: invoice }, { status: 201 });
}
Three properties make this work. The key must be stored atomically with the response â write the result and the key in one transaction so a crash between the two cannot leave a key without a result. Replays must return the original status code, not a fresh 201, so clients can distinguish a retry from a new success. And the stored responses need a time-to-live, typically twenty-four hours, after which the key is forgotten and a genuinely new request proceeds normally. Document the header as required for all unsafe operations; once one endpoint supports it, clients will reasonably expect the same contract everywhere.
Versioning without stranding anyone
Version the surface, not every route, and keep the version in the path â /api/v1/invoices is unambiguous in logs, caches, and support tickets. Additive changes do not bump the version: a new optional field on an existing response is safe for conforming clients. Breaking changes â removing a field, changing a type, redefining a status code â ship as v2 alongside v1 with a documented sunset date.
The practical discipline is contract tests: snapshot the response shape of every endpoint in CI and fail the build when a diff appears outside an intentional version bump. Most accidental breaking changes never reach staging when that check exists.
â ī¸Never leak stack traces
Error handlers should log the full exception server-side and return a correlation ID to the client. A stack trace in a response tells an attacker about file paths and library versions for free.
Common Mistakes
Offset pagination on tables that receive frequent inserts
Fix: Use keyset cursors so pages stay stable and queries remain indexed range scans.
Rate limiting with an in-memory Map in a serverless deployment
Fix: Store counters in Redis or an HTTP store shared across instances.
Returning different error shapes per endpoint
Fix: Standardize one error envelope with a stable code, message, and optional details array.
Bumping the API version for every additive field
Fix: Reserve version bumps for breaking changes; optional fields are backward compatible.
Best Practices
- Keep the success envelope uniform: data plus pagination where a collection is involved
- Treat error codes as the API contract and messages as cosmetic
- Document cursor opacity so you can re-encode them later
- Snapshot response shapes in CI to catch accidental breaking changes
Interview Questions
Q1: Why prefer cursor pagination over offset for large collections?
Cursors resume from a keyset with an indexed range scan; offsets force the database to skip and discard rows, slowing down linearly with page depth.
Q2: How do you rate limit correctly across serverless instances?
Keep the counter in a shared store such as Redis keyed by a stable identifier like the org ID, with a fixed window or sliding-window script.
Q3: When should an API path version change?
Only for breaking changes. Additive fields and new optional parameters are backward compatible and should not force clients to migrate.
Key Takeaways
- Design resource-oriented URLs and be disciplined with status codes.
- One success envelope and one error envelope across every endpoint.
- Cursor pagination keeps deep pages fast and stable under inserts.
- Shared-store rate limiting with Retry-After headers is production-grade protection.
- Version only on breaking change, and snapshot contracts in CI to enforce it.