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
- Create an account on upstash
- Create a new redis database
- Chose a name and a region close to you
- Select the free plan when prompted
- Copy
UPSTASH_REDIS_REST_URL
,UPSTASH_REDIS_REST_TOKEN
from yourredis
database and add them to.env.local
- Install dependencies
Terminal
# with npm
npm install @upstash/redis @upstash/ratelimit
# with yarn
yarn add @upstash/redis @upstash/ratelimit
- 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...
}