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?
AdvancedAnswer
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.