Blog

My Journey as a Web Developer

How to Add a Rate Limiter for Your API Using Next.js 13

24/03/2023

author avatar

API rate limiting is an essential aspect of API development. A rate limiter is a tool that helps you control the number of requests that can be made to an API in a given period. Without a rate limiter, your API can easily be overloaded, causing your server to crash or become unresponsive. In this blog post, we will walk through how to add a rate limiter for your API using Next.js 13

Step 1: Set up Redis

The first thing we need to do is set up Redis. Redis is an in-memory data structure store that can be used as a database, cache, and message broker. It's an excellent choice for implementing rate limiting because it's fast, scalable, and easy to use.

To set up Redis, we create a file called 'redis.js' in the '/lib' directory of our Next.js project. We then import the Redis package from '@upstash/redis' and create a new Redis instance using the following code:

import { Redis } from "@upstash/redis";

export const redis = new Redis({
  url: process.env.REDIS_URL,
  token: process.env.REDIS_SECRET,
});

This code sets up a new Redis instance and passes in the Redis URL and secret as environment variables. Make sure to set these environment variables in your Next.js project's '.env' file.

Step 2: Set up the Rate Limiter

Next, we need to set up the rate limiter. For this, we use the '@upstash/ratelimit' package. This package provides a simple interface for implementing rate limiting using Redis.

To set up the rate limiter, we create a new file called 'rate-limiter.js' in the '/lib' directory of our Next.js project. We then import the Redis instance we created earlier and the 'Ratelimit' class from '@upstash/ratelimit' package. We then create a new rate limiter instance using the following code:

import { redis } from "./redis";
import { Ratelimit } from "@upstash/ratelimit";

export const rateLimiter = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(1, "40 s"),
});

This code sets up a new rate limiter instance using a sliding window algorithm with a limit of 1 request per 40 seconds. We will use this just for testing purposes, but change this to something more suited to your needs when in production.

Step 3: Use the Rate Limiter in an API Route or Middleware

Finally, we need to use the rate limiter in an API route or middleware. For this, we import the 'rateLimiter' instance from './lib/rate-limiter.js' and use it to limit the number of requests.

Here's an example of how to use the rate limiter in an API route:

import { rateLimiter } from "@/lib/rate-limiter";

export default async function handler(req, res) {
  const ip = req.ip ?? "127.0.0.1";

  try {
    const { success } = await rateLimiter.limit(ip);

    if (!success)
      return Response.json({ status: 429, message: "Too many submissions" });
  } catch (error) {
    return new NextResponse("Something went wrong with your form.");
  }

  // Process the API request

In conclusion, adding a rate limiter to your API is essential to ensure that your server remains responsive and available. I know when I created my first API, I was nervous about billing and security. Adding a rate limiter is an essential part to helping you sleep at night and securing your application. Upstash Redis makes it easy to implement a rate limiter using Redis and the @upstash/ratelimit package. By following the steps outlined in this blog post, you can easily add a rate limiter to your Next.js API and protect it from overload. Good luck!

← Blog Home