Rate limiting is a technique used to control the rate at which a user or client can access a server or application. In the context of a Next.js application, rate limiting can be used to control the rate at which API routes are accessed.
In this article, we will discuss how to implement rate limiting for Next.js API routes using Upstash and Redis.
Step 1: Upstash Database Setup
-
What is Upstash?
Upstash is an incredibly powerful Serverless Data Platform that offers both Redis and Kafka support, making it perfect for a wide range of use cases. Whether you need a caching layer or a database, Upstash can provide the support you need. It is also incredibly easy to set up and use, allowing you to quickly get going and start taking advantage of its features.
- First, you will need to go sign up for an Upstash account.
- Once finish sign up, create a Redis Database using Upstash Console or CLI.
- Copy the
UPSTASH_REDIS_REST_URL
andUPSTASH_REDIS_REST_TOKEN
and save them in a file that can be accessed easily for next step.
Step 2: Next.js Project Setup
-
Create a new Next.js application using the CLI
npx create-next-app@latest
-
Install required Upstash dependencies.
npm install @upstash/ratelimit @upstash/redis
Step 3: Rate Limiting Next.js API Routes
-
Update,
pages/api/hello.js
and make sure to replace UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN.import {Ratelimit} from "@upstash/ratelimit"; import {Redis} from "@upstash/redis"; const redis = new Redis({ url: 'UPSTASH_REDIS_REST_URL', token: 'UPSTASH_REDIS_REST_TOKEN', }) // Create a new ratelimiter, that allows 10 requests per 60 seconds const ratelimit = new Ratelimit({ redis: redis, limiter: Ratelimit.fixedWindow(10, "60 s"), }); export default async function handler(req, res) { const identifier = "api"; const result = await ratelimit.limit(identifier); res.setHeader('X-RateLimit-Limit', result.limit) res.setHeader('X-RateLimit-Remaining', result.remaining) if (!result.success) { res.status(200).json({message: 'The request has been rate limited.', rateLimitState: result}) return } res.status(200).json({name: 'John Doe', rateLimitState: result}) }
Here, we are allowing 10 requests per 60 seconds.
Step 4: Run the application
Run the Next.js application npm run dev
and test the Rate Limiting.
Try live demo: https://edge-functions-api-rate-limit.vercel.app/
Conclusion
In conclusion, rate limiting is an important security measure that helps protect your server resources and prevent abuse. By using Upstash, a cloud-based Redis service, and Redis, an in-memory data structure store, it is easy to implement rate limiting for Next.js API routes.
The example provided demonstrates how you can use Redis to store and manage request counters, and quickly and easily enforce rate limits. Additionally, Upstash’s web console allows you to monitor the rate limit key and see how many requests are being made by a user. Overall, implementing rate limiting with Upstash and Redis is a simple and effective way to ensure the security and stability of your API.