Rate limiting for api so people can't mass report.

This commit is contained in:
Hieuhuy Pham 2025-01-24 12:53:24 -05:00
parent 838e9730a4
commit 9c78ed022d

31
src/middleware.ts Normal file
View File

@ -0,0 +1,31 @@
import { NextResponse } from 'next/server';
const rateLimitCache = new Map<string, { timestamp: number; count: number }>();
const RATE_LIMIT_WINDOW_MS = 60000;
const RATE_LIMIT_MAX_REQUESTS = 5;
export function middleware(request: Request) {
const ip = request.headers.get('x-forwarded-for') || '127.0.0.1';
const now = Date.now();
const userRateLimit = rateLimitCache.get(ip) || { count: 0, timestamp: now };
if (now - userRateLimit.timestamp > RATE_LIMIT_WINDOW_MS) {
rateLimitCache.set(ip, { count: 1, timestamp: now });
} else if (userRateLimit.count >= RATE_LIMIT_MAX_REQUESTS) {
return NextResponse.json(
{ message: 'Rate limit exceeded. Please wait a moment.' },
{ status: 429 }
);
} else {
userRateLimit.count += 1;
rateLimitCache.set(ip, userRateLimit);
}
return NextResponse.next();
}
// Apply middleware only to API routes
export const config = {
matcher: '/api/:path*',
};