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:51:23 -05:00
|
|
|
analytics: true,
|
|
|
|
timeout: 1000, // 1 second
|
2024-09-29 16:40:23 -05:00
|
|
|
});
|
|
|
|
|
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:55:56 -05:00
|
|
|
matcher: '/api/:path*',
|
2024-09-29 16:40:23 -05:00
|
|
|
};
|
|
|
|
|
2024-09-30 19:41:26 -05:00
|
|
|
export default async function middleware(request) {
|
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(
|
2024-09-30 19:51:23 -05:00
|
|
|
`ratelimit_middleware_${ip}`
|
2024-09-30 19:41:26 -05:00
|
|
|
);
|
2024-09-30 19:51:23 -05:00
|
|
|
|
|
|
|
if (!success) {
|
|
|
|
return new NextResponse('Too Many Requests', {
|
|
|
|
status: 429,
|
|
|
|
headers: {
|
|
|
|
'Retry-After': reset.toString(),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return NextResponse.next();
|
2024-09-29 16:40:23 -05:00
|
|
|
}
|