Rate Limiting Next.js API Routes: In-Memory, Redis, and Plan-Based Limits
The Rate Limiting Problem No rate limiting = your AI SaaS gets scraped, abused, or accidentally DDoS'd by a runaway script. One user's infinite loop shouldn't kill service for everyone else. Here's...

Source: DEV Community
The Rate Limiting Problem No rate limiting = your AI SaaS gets scraped, abused, or accidentally DDoS'd by a runaway script. One user's infinite loop shouldn't kill service for everyone else. Here's how to add rate limiting to Next.js API routes without Redis. Option 1: In-Memory Rate Limiter (No Infrastructure) Good for: single-instance deployments, dev environments, prototypes. // lib/rate-limit.ts const rateLimitMap = new Map<string, { count: number; resetTime: number }>() export function rateLimit({ key, limit = 10, windowMs = 60_000, }: { key: string limit?: number windowMs?: number }) { const now = Date.now() const record = rateLimitMap.get(key) if (!record || now > record.resetTime) { rateLimitMap.set(key, { count: 1, resetTime: now + windowMs }) return { success: true, remaining: limit - 1 } } if (record.count >= limit) { return { success: false, remaining: 0, resetTime: record.resetTime } } record.count++ return { success: true, remaining: limit - record.count } } U