0Pricing
Next.js 15 Fullstack Web Apps · Lezione

Rate limiting e gestione degli errori API

Protegga i route handler di Next.js con il rate limiting e restituisca risposte di errore coerenti e ben strutturate, con i corretti codici di stato HTTP.

Rate limiting e gestione degli errori API è una lezione Next.js 15 Fullstack Web Apps gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack Web Apps, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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:

  • 400 bad input
  • 401 not authenticated
  • 403 not authorized
  • 404 not found
  • 429 rate limited
  • 500 server 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 429 with Retry-After, preferring Redis for distributed limits.
  • Standardized a JSON error envelope and mapped causes to status codes.
  • Caught exceptions and avoided leaking internals.

Domande Frequenti

La lezione «Rate limiting e gestione degli errori API» è gratuita?

Sì — il testo completo di «Rate limiting e gestione degli errori API» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack Web Apps, passa a CoddyKit PRO. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.

Cosa imparerò in «Rate limiting e gestione degli errori API»?

Protegga i route handler di Next.js con il rate limiting e restituisca risposte di errore coerenti e ben strutturate, con i corretti codici di stato HTTP. Eserciti Next.js 15 Fullstack Web Apps con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Next.js 15 Fullstack Web Apps?

Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack Web Apps su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Rate limiting e gestione degli errori API»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack Web Apps?

Sì. Ogni lezione Next.js 15 Fullstack Web Apps include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Creazione di Route Handlers per le API
  2. Validazione delle richieste e sicurezza
  3. Integrazione di servizi esterni
  4. Rate limiting e gestione degli errori API
← Torna a Next.js 15 Fullstack Web Apps