typescriptadvanced
Edge Middleware Rate Limiter
Rate limit API requests at the edge using a sliding window counter with configurable thresholds.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Rate Limiter for Edge Functions
Implement sliding window rate limiting in Next.js middleware using in-memory or KV store.
Best for: API protection
#nextjs#rate-limiting
typescriptintermediate
Edge Middleware Geolocation
Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.
Best for: GDPR consent flows
#edge#geolocation
typescriptadvanced
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
#nextjs#middleware
typescriptadvanced
Middleware Geo-based Redirect
Redirect users based on their geographic location using Next.js edge middleware.
Best for: internationalization
#nextjs#middleware