Ratenbegrenzung und API-Fehlerbehandlung
Schützen Sie Ihre Next.js-Route-Handler mit Ratenbegrenzung und geben Sie konsistente, gut strukturierte Fehlerantworten mit den richtigen HTTP-Statuscodes zurück.
Ratenbegrenzung und API-Fehlerbehandlung ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Ratenbegrenzung und API-Fehlerbehandlung“ kostenlos?
Ja — der vollständige Text von „Ratenbegrenzung und API-Fehlerbehandlung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Ratenbegrenzung und API-Fehlerbehandlung“?
Schützen Sie Ihre Next.js-Route-Handler mit Ratenbegrenzung und geben Sie konsistente, gut strukturierte Fehlerantworten mit den richtigen HTTP-Statuscodes zurück. Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Ratenbegrenzung und API-Fehlerbehandlung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- API-Route-Handler erstellen
- Anfragevalidierung und Sicherheit
- Externe Dienste integrieren
- Ratenbegrenzung und API-Fehlerbehandlung