Rate Limiting and API Error Handling
Protect your Next.js route handlers with rate limiting and return consistent, well-structured error responses with correct HTTP status codes.
Rate Limiting and API Error Handling is a free Next.js 15 Fullstack Web Apps lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Next.js 15 Fullstack Web Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Rate Limit
Public API routes are exposed to abuse: brute-force logins, scraping, and accidental floods. Rate limiting caps how many requests a client may make in a time window, protecting your backend and external service quotas.
Identifying the Client
You need a key to count requests per client. Common choices are the IP address, an API key, or the authenticated user ID. In route handlers, read the IP from headers set by your platform.
export async function GET(req) {
const ip = req.headers.get('x-forwarded-for') ?? 'unknown';
return Response.json({ ip });
}A Fixed-Window Counter
The simplest algorithm counts requests in a fixed time window per key. When the count exceeds the limit, reject further requests until the window resets.
function fixedWindow(store, key, limit, windowMs) {
const now = Date.now();
const entry = store[key] || { count: 0, reset: now + windowMs };
if (now > entry.reset) { entry.count = 0; entry.reset = now + windowMs; }
entry.count++;
store[key] = entry;
return entry.count <= limit;
}Trying the Limiter
Run the fixed-window logic locally to see it allow then block.
function fixedWindow(store, key, limit, windowMs) {
const now = Date.now();
const entry = store[key] || { count: 0, reset: now + windowMs };
if (now > entry.reset) { entry.count = 0; entry.reset = now + windowMs; }
entry.count++;
store[key] = entry;
return entry.count <= limit;
}
const store = {};
for (let i = 0; i < 4; i++) {
console.log(i, fixedWindow(store, 'ip1', 3, 1000));
}In-Memory vs Distributed
An in-memory store resets on every cold start and is not shared across serverless instances. For real deployments use a shared store like Redis (e.g. Upstash) so limits are consistent everywhere.
Returning 429
When a client is over the limit, respond with HTTP 429 Too Many Requests and a Retry-After header telling them when to try again.
export async function POST(req) {
if (!allowed) {
return new Response('Rate limit exceeded', {
status: 429,
headers: { 'Retry-After': '60' },
});
}
return Response.json({ ok: true });
}A Consistent Error Shape
Clients parse errors more easily when every failure has the same JSON shape. Standardize on a small envelope.
function apiError(message, status, code) {
return Response.json(
{ error: { message, code } },
{ status }
);
}Mapping Errors to Status Codes
Choose the status that matches the cause:
400bad input401not authenticated403not authorized404not found429rate limited500server fault
Catching Unexpected Errors
Wrap handler logic in try/catch so an unhandled exception becomes a controlled 500 rather than a leaked stack trace.
export async function GET() {
try {
const data = await loadData();
return Response.json(data);
} catch (e) {
console.error(e);
return Response.json({ error: { message: 'Internal error' } }, { status: 500 });
}
}Reusable Wrapper
Factor the boilerplate into a higher-order function that applies rate limiting and error catching to any handler.
function withGuards(handler) {
return async (req) => {
if (!checkLimit(req)) return apiError('Too many requests', 429);
try { return await handler(req); }
catch { return apiError('Internal error', 500); }
};
}Never Leak Internals
In production, never send raw error messages, stack traces, or SQL details to the client. Log them server-side and return a generic message with a stable error code.
Quick Check
Which HTTP status code and header best signal that a client has exceeded the rate limit?
Recap
You hardened your API routes:
- Identified clients and counted requests with a fixed-window limiter.
- Returned
429withRetry-After, preferring Redis for distributed limits. - Standardized a JSON error envelope and mapped causes to status codes.
- Caught exceptions and avoided leaking internals.
Frequently asked questions
Is the “Rate Limiting and API Error Handling” lesson free?
Yes — the full text of “Rate Limiting and API Error Handling” is free to read here on the web, and the Next.js 15 Fullstack Web Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Next.js 15 Fullstack Web Apps course, upgrade to CoddyKit PRO.
What will I learn in “Rate Limiting and API Error Handling”?
Protect your Next.js route handlers with rate limiting and return consistent, well-structured error responses with correct HTTP status codes. You practise Next.js 15 Fullstack Web Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Next.js 15 Fullstack Web Apps?
No prior experience is required. Next.js 15 Fullstack Web Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Rate Limiting and API Error Handling” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Next.js 15 Fullstack Web Apps lesson?
Yes. Every Next.js 15 Fullstack Web Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building API Route Handlers
- Request Validation and Security
- Integrating External Services
- Rate Limiting and API Error Handling