How to Implement Rate Limiting in Next.js

How to Implement Rate Limiting in Next.js

Learn how to implement rate limiting in Next.js to prevent server overload, enhance security, and ensure fair usage.

Sachin Chaurasiya

Sachin Chaurasiya

Jun 04, 2024 4 min read

In today’s digital world, web services must handle many user requests. But how do they keep their systems fast and reliable? One key method is rate limiting. In this post, we'll explain what rate limiting is, why it matters, and how to use it in a Next.js application.

Table of Contents

  1. What is Rate Limiting?
  2. Why is Rate Limiting Important?
  3. Setting Up a Next.js Project
  4. Adding Rate Limiting to Your API Route
  5. Testing Your Rate Limited API
  6. Bonus Nextjs Jobs
  7. Conclusion

What is Rate Limiting?

Rate limiting controls how many requests a user can make to a service in a certain time frame. Think of it like a bouncer at a club who only lets in a few people at a time to prevent overcrowding. In the same way, rate limiting keeps web services running smoothly and securely by stopping any one user from overloading the system.

Why is Rate Limiting Important?

  1. Prevents Overload: Keeps your servers from being overwhelmed by too many requests, ensuring your service remains fast and responsive.
  2. Enhances Security: Protects against malicious activities like DDoS (Distributed Denial of Service) attacks and brute-force login attempts.
  3. Ensures Fair Usage: Guarantees that all users have fair access to your service, preventing any single user from hogging resources.
  4. Cost Control: Helps users avoid unexpectedly high bills by capping their usage.

Some Examples

  • Weather service API might limit users to 100 requests per minute.
  • Social media platforms might restrict login attempts to 5 per minute.

Setting Up a Next.js Project

First, let's set up a new Next.js project by running the following command

npx create-next-app@latest my-rate-limited-api
cd my-rate-limited-api

Next, install the needed packages for rate limiting

npm install @vercel/kv @upstash/ratelimit

@vercel/kv is a key-value store made for Vercel's platform. It lets you store and get simple key-value pairs quickly. It's great for session storage, caching, and other cases where you need fast data access.

Log in to Vercel, go to the storage tab, and click on Create Database.

Login to Vercel
Log in to Vercel, go to the storage tab, and click on Create Database.

Create a KV storage, get the secrets, and add them to the .env file.

// .env


@upstash/ratelimit is a powerful HTTP-based rate limiting library that supports various algorithms. It helps prevent misuse and ensures fair use of your web services. It supports methods like fixed window, sliding window, and token bucket, making it flexible for different needs.

Adding Rate Limiting to Your API Route

Let's create a simple API route in Next.js and add rate limiting to it.

Create a new API route In the pages/api directory, create a file called hello.ts

// pages/api/hello.ts

import { Ratelimit } from '@upstash/ratelimit';
import { kv } from '@vercel/kv';
import { NextRequest, NextResponse } from 'next/server';

// Create a new rateLimit instance
const rateLimit = new Ratelimit({
	redis: kv, // Use Vercel KV for storage
	limiter: Ratelimit.slidingWindow(5, '1m'), // Limit to 5 requests per minute

// set the runtime to edge so that the function runs on the edge
export const runtime = 'edge';

export default async function handler(request: NextRequest) {
	// Get the IP address of the user

	const ip = request.headers['x-forwarded-for'];

	// Check if the user has reached their rate limit
	const { success } = await rateLimit.limit(`ratelimit_${ip}`);

	if (!success) {
		return NextResponse.json(
				message: 'Too many requests, please try again later.',
				status: 429,

	return NextResponse.json(
			message: 'Hello, World!',
			status: 200,
  • We import @vercel/kv and @upstash/ratelimit.
  • We initialize the rate limiter with Ratelimit.slidingWindow(5, '1m'), which allows 5 requests per minute.
  • In the API handler, we get the user's IP address and check the rate limit.
  • If the limit is exceeded, we respond with a 429 Too Many Requests status.
  • Otherwise, we respond with a friendly message.

Testing Your Rate Limited API

To test your API, run the development server

npm run dev

Then, make requests to the API endpoint /api/hello. You can use tools like curl or Postman to send multiple requests and observe the rate limiting in action.

curl http://localhost:3000/api/hello

After making 5 requests within a minute, you should start receiving the 429 Too Many Requests response.

Bonus: Nextjs Jobs

If you are looking for new opportunity, you must check Software Developer Jobs on Peerlist


Rate limiting is a simple but effective way to keep your web services reliable and secure. By adding rate limiting to your Next.js API routes, you can prevent server overload, improve security, ensure fair usage, and control costs.

I hope this guide helps you. If you have any questions or need more help, feel free to reach out. Thanks to Peerlist for the opportunity to share this post.