Edge Middleware Rate Limiter
Rate limit API requests at the edge using a sliding window counter with configurable thresholds.
import { NextRequest, NextResponse } from 'next/server';
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 60;
// Edge-compatible in-memory store (use Upstash Redis for production)
const store = new Map<string, { count: number; resetAt: number }>();
export function middleware(req: NextRequest) {
if (!req.nextUrl.pathname.startsWith('/api')) return NextResponse.next();
const ip = req.headers.get('x-forwarded-for') ?? 'unknown';
const now = Date.now();
const entry = store.get(ip);
if (!entry || now > entry.resetAt) {
store.set(ip, { count: 1, resetAt: now + WINDOW_MS });
return NextResponse.next();
}
if (entry.count >= MAX_REQUESTS) {
return NextResponse.json(
{ error: 'Too many requests' },
{ status: 429, headers: { 'Retry-After': String(Math.ceil((entry.resetAt - now) / 1000)) } }
);
}
entry.count++;
return NextResponse.next();
}
export const config = { matcher: '/api/:path*' };Sponsored
Try Upstash — Serverless Rate Limiting
Use Cases
- API abuse prevention
- DDoS mitigation
- Fair usage enforcement
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Edge Middleware Geolocation
Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Nginx Rate Limiting Configuration
Nginx rate limiting with multiple zones for API and login routes, burst handling, and custom error pages.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.