How to apply rate limit to Next.js App router

Published on: (Updated on: )
In this article, I am going to show you how to control access to an API resource in Next.js 13 and 14 using the App router. The technique I am going to demonstrate involves using Redis on your own server for rate limiting. This is a useful alternative to Vercel kv if your Next.js app is self-hosted. Similar posts available on this topic are based on the Next.js Page router, so I thought creating this post would be beneficial for those using the new Next.js app router.
To use Redis for rate-limiting in the Next.js App router, you need to have Redis installed on your server. You should probably use a VPS or similar hosting that grants you root access, as some shared hosting services do not offer Redis on their servers. If you're not familiar with Redis, don't worry; it's quite easy to install.
What is rate limit in API context?
Rate-limiting, sometimes referred to as throttling, can help prevent abuse, protect against denial-of-service (DoS) attacks, and ensure fair usage of server resources. It involves restricting the number of requests made to a server or API within a defined period. Rate-limiting sets thresholds on the frequency of requests, typically measured in requests per second (RPS) or requests per minute (RPM). When the limit is reached, further requests may be delayed, rejected, or handled differently based on the rate-limiting strategy in place.
Why use rate-limiting for your API?
Implementing rate-limiting for your API offers several benefits:
- Prevent Abuse: Limiting requests discourages spamming, scraping, or unauthorized access.
- Protect Server Resources: Controls incoming requests to prevent server overload.
- Ensure Fair Usage: Treats all clients equally, preventing resource monopolization.
- Mitigate DoS Attacks: Defends against flooding attacks, ensuring API availability.
Imagine you're using a third-party API like Spotify, and it grants you 200 requests per day. While your site visitors may use your resource moderately, a malicious bot could exhaust your API limit within seconds.
Creating your own API allows more generous API hits, but with third-party APIs, you may need to apply a rate limit. This is crucial, especially if you're charged per API call.
For self-hosted APIs, rate limiting or throttling might be built into your framework. For example, Django Rest Framework includes a throttle class for easy implementation.