Initial commit
This commit is contained in:
43
middleware.ts
Normal file
43
middleware.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
|
||||
const MAX_REQUESTS = 100; // 100 requests per window
|
||||
|
||||
const ipMap = new Map<string, { count: number; expires: number }>();
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
// Simple in-memory rate limiting implementation
|
||||
// Note: specific to a single instance container. For distributed, use Redis.
|
||||
const ip = request.headers.get('x-forwarded-for') || 'unknown';
|
||||
const now = Date.now();
|
||||
|
||||
// Logging Stub: In future, this will push to a DB service
|
||||
console.log(`[${new Date().toISOString()}] Request to ${request.nextUrl.pathname} from ${ip}`);
|
||||
|
||||
const record = ipMap.get(ip);
|
||||
|
||||
if (!record || now > record.expires) {
|
||||
ipMap.set(ip, { count: 1, expires: now + RATE_LIMIT_WINDOW });
|
||||
} else {
|
||||
record.count++;
|
||||
if (record.count > MAX_REQUESTS) {
|
||||
return new NextResponse('Too Many Requests', { status: 429 });
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup old entries occasionally (naive approach for this scale)
|
||||
if (ipMap.size > 1000) {
|
||||
for (const [key, val] of ipMap.entries()) {
|
||||
if (now > val.expires) {
|
||||
ipMap.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: '/:path*',
|
||||
};
|
||||
Reference in New Issue
Block a user