0Pricing
Next.js 15 Fullstack Web Apps · Aula

Limitação de taxa e tratamento de erros da API

Proteja os manipuladores de rotas do Next.js com limitação de taxa e retorne respostas de erro consistentes e bem estruturadas, com os códigos de estado HTTP corretos.

Limitação de taxa e tratamento de erros da API é uma aula grátis de Next.js 15 Fullstack Web Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack Web Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Limitação de taxa e tratamento de erros da API” é grátis?

Sim — o texto completo de “Limitação de taxa e tratamento de erros da API” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack Web Apps, atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

O que vou aprender em “Limitação de taxa e tratamento de erros da API”?

Proteja os manipuladores de rotas do Next.js com limitação de taxa e retorne respostas de erro consistentes e bem estruturadas, com os códigos de estado HTTP corretos. Você pratica Next.js 15 Fullstack Web Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Next.js 15 Fullstack Web Apps?

Nenhuma experiência prévia é necessária. Next.js 15 Fullstack Web Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Limitação de taxa e tratamento de erros da API”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Next.js 15 Fullstack Web Apps?

Sim. Cada aula de Next.js 15 Fullstack Web Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Construção de Manipuladores de Rotas de API
  2. Validação de Requisições e Segurança
  3. Integração com Serviços Externos
  4. Limitação de taxa e tratamento de erros da API
← Voltar para Next.js 15 Fullstack Web Apps