typescriptadvanced

Edge Middleware Rate Limiter

Rate limit API requests at the edge using a sliding window counter with configurable thresholds.

typescript
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.