| 1 | import { NextResponse } from 'next/server'; |
| 2 | import type { NextRequest } from 'next/server'; |
| 3 | |
| 4 | // In-memory store for rate limiting (Note: in Edge environment, this is per-isolate) |
| 5 | // For a fully distributed cache across all instances, Redis/Vercel KV should be used. |
| 6 | const rateLimitMap = new Map<string, { count: number; resetTime: number }>(); |
| 7 | |
| 8 | const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute |
| 9 | const MAX_REQUESTS_PER_WINDOW = 100; |
| 10 | |
| 11 | export function middleware(request: NextRequest) { |
| 12 | // Only apply to API routes |
| 13 | if (!request.nextUrl.pathname.startsWith('/api')) { |
| 14 | return NextResponse.next(); |
| 15 | } |
| 16 | |
| 17 | // request.ip is populated securely by the hosting platform (Vercel). |
| 18 | // Fallback to the leftmost x-forwarded-for if running locally/custom node server. |
| 19 | const forwarded = request.headers.get('x-forwarded-for'); |
| 20 | const ip = (request as any).ip || (forwarded ? forwarded.split(',')[0].trim() : 'unknown'); |
| 21 | const now = Date.now(); |
| 22 | |
| 23 | let limitData = rateLimitMap.get(ip); |
| 24 | |
| 25 | // Clean up expired entry |
| 26 | if (limitData && now > limitData.resetTime) { |
| 27 | limitData = undefined; |
| 28 | } |
| 29 | |
| 30 | if (!limitData) { |
| 31 | limitData = { count: 1, resetTime: now + RATE_LIMIT_WINDOW_MS }; |
| 32 | rateLimitMap.set(ip, limitData); |
| 33 | } else { |
| 34 | limitData.count++; |
| 35 | } |
| 36 | |
| 37 | // Periodic cleanup of the Map to prevent memory leaks in long-running isolates |
| 38 | if (Math.random() < 0.01) { // 1% chance to run cleanup on request |
| 39 | for (const [key, value] of rateLimitMap.entries()) { |
| 40 | if (now > value.resetTime) { |
| 41 | rateLimitMap.delete(key); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | if (limitData.count > MAX_REQUESTS_PER_WINDOW) { |
| 47 | return new NextResponse( |
| 48 | JSON.stringify({ |
| 49 | error: 'Too Many Requests', |
| 50 | message: `Rate limit exceeded. Try again in ${Math.ceil((limitData.resetTime - now) / 1000)} seconds.`, |
| 51 | }), |
| 52 | { |
| 53 | status: 429, |
| 54 | headers: { |
| 55 | 'Content-Type': 'application/json', |
| 56 | 'Retry-After': Math.ceil((limitData.resetTime - now) / 1000).toString(), |
| 57 | }, |
| 58 | } |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | const response = NextResponse.next(); |
| 63 | |
| 64 | // Attach rate limit headers |
| 65 | response.headers.set('X-RateLimit-Limit', MAX_REQUESTS_PER_WINDOW.toString()); |
| 66 | response.headers.set('X-RateLimit-Remaining', Math.max(0, MAX_REQUESTS_PER_WINDOW - limitData.count).toString()); |
| 67 | response.headers.set('X-RateLimit-Reset', limitData.resetTime.toString()); |
| 68 | |
| 69 | return response; |
| 70 | } |
| 71 | |
| 72 | export const config = { |
| 73 | matcher: '/api/:path*', |
| 74 | }; |