2024-09-29 16:40:23 -05:00
|
|
|
import { NextResponse } from 'next/server';
|
|
|
|
import { Ratelimit } from '@upstash/ratelimit';
|
|
|
|
import { kv } from '@vercel/kv';
|
|
|
|
|
|
|
|
const ratelimit = new Ratelimit({
|
|
|
|
redis: kv,
|
2024-09-30 19:41:26 -05:00
|
|
|
// 5 requests from the same IP in 10 seconds
|
2024-09-29 16:40:23 -05:00
|
|
|
limiter: Ratelimit.slidingWindow(5, '10 s'),
|
|
|
|
});
|
|
|
|
|
2024-09-30 19:41:26 -05:00
|
|
|
// Define which routes you want to rate limit
|
2024-09-29 16:40:23 -05:00
|
|
|
export const config = {
|
2024-09-30 19:41:26 -05:00
|
|
|
matcher: '/',
|
2024-09-29 16:40:23 -05:00
|
|
|
};
|
|
|
|
|
2024-09-30 19:41:26 -05:00
|
|
|
export default async function middleware(request) {
|
|
|
|
// You could alternatively limit based on user ID or similar
|
2024-09-29 16:40:23 -05:00
|
|
|
const ip = request.ip ?? '127.0.0.1';
|
2024-09-30 19:41:26 -05:00
|
|
|
const { success, pending, limit, reset, remaining } = await ratelimit.limit(
|
|
|
|
ip
|
|
|
|
);
|
2024-09-29 16:40:23 -05:00
|
|
|
return success
|
|
|
|
? NextResponse.next()
|
|
|
|
: NextResponse.redirect(new URL('/blocked', request.url));
|
|
|
|
}
|