From 9c78ed022dfc17cb0d16a0bf333a832c735afee8 Mon Sep 17 00:00:00 2001 From: Hieuhuy Pham Date: Fri, 24 Jan 2025 12:53:24 -0500 Subject: [PATCH] Rate limiting for api so people can't mass report. --- src/middleware.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/middleware.ts diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..2b8a8f5 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,31 @@ +import { NextResponse } from 'next/server'; + +const rateLimitCache = new Map(); +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*', +};