Back to results for “Handlers”
Next.js › Route Handlers (API Route.js)

How would you implement rate limiting inside a route handler to prevent abuse of a public API endpoint?

Advanced

Answer

You track the number of requests coming from a specific identifier, such as an IP address or an API key, over a time window, usually using an external store like Redis for reliability across multiple server instances, and return a too many requests response once a client exceeds the allowed limit within that window.
export async function GET(request) {
  const ip = request.headers.get('x-forwarded-for');
  const requestCount = await getRequestCount(ip);
  if (requestCount > 100) {
    return Response.json({ error: 'Too many requests' }, { status: 429 });
  }
  await incrementRequestCount(ip);
  return Response.json({ data: 'success' });
}
Real-world example A public weather API endpoint limits each visitor to one hundred requests per hour, protecting the service from being overwhelmed by a single client sending excessive traffic.

Common follow-ups: What storage options work best for tracking rate limits across multiple server instances?;How do you communicate the remaining rate limit to API consumers?