Rate limiting

    If you are deploying to Vercel you can use their firewall plugin read their guide here or upstash by following the guide below, both solutions are good.

    Setup

    1. Create an account on upstash
    2. Create a new redis database
      • Chose a name and a region close to you
      • Select the free plan when prompted
    3. Copy UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN from your redis database and add them to .env.local
    4. Install dependencies

    Terminal

    # with npm
    npm install @upstash/redis @upstash/ratelimit
    # with yarn
    yarn add @upstash/redis @upstash/ratelimit
    
    1. Update /src/middleware.ts

    /src/middleware.ts

    import { Redis } from "@upstash/redis";
    import { Ratelimit } from "@upstash/ratelimit";
    import { NextRequest, NextResponse } from "next/server";
    
    // initialize redis
    const redis = new Redis({
      url: process.env.UPSTASH_REDIS_REST_URL,
      token: process.env.UPSTASH_REDIS_REST_TOKEN,
    });
    
    // initialize the rate limiter
    const limiter = new Ratelimit({
      redis: redis,
      // users can have 60 requests per minute
      limiter: Ratelimit.slidingWindow(60, "60 s"),
    });
    
    export async function middleware(req: NextRequest) {
      // get the user ip
      const ip =
        req.headers.get("x-forwarded-for")?.split(",")[0].trim() || "127.0.0.1";
      // check if they exceeded their limit
      const { success } = await limiter.limit(ip);
      if (!success) {
        return new NextResponse(null, { status: 429 });
      }
      // rest of the middleware...
    }