universal-rate-limit

Next.js Middleware (@universal-rate-limit/nextjs)

Next.js App Router wrapper and Edge Middleware for universal-rate-limit.

header

Next.js App Router wrapper and Edge middleware for universal-rate-limit — a zero-dependency rate limiter built on web standards. Supports fixed-window, sliding-window, and token-bucket algorithms, pluggable stores (memory, Redis, or your own), and IETF-compliant rate limit headers out of the box.

Try the playground to see rate limiting in action.

Install

npm install @universal-rate-limit/nextjs

Usage

App Router Route Handlers

Wrap your route handler with withRateLimit:

// app/api/hello/route.ts
import { withRateLimit } from '@universal-rate-limit/nextjs';

async function handler(request: Request) {
    return Response.json({ hello: 'world' });
}

export const GET = withRateLimit(handler, {
    algorithm: { type: 'sliding-window', windowMs: 60_000 }, // 1 minute
    limit: 60 // 60 requests per window
});

Edge Middleware

Use nextjsRateLimit for custom logic in Edge Middleware:

// middleware.ts
import { nextjsRateLimit } from '@universal-rate-limit/nextjs';
import { NextResponse } from 'next/server';

const limiter = nextjsRateLimit({
    algorithm: { type: 'sliding-window', windowMs: 60_000 },
    limit: 60
});

export async function middleware(request: Request) {
    const result = await limiter(request);

    if (result.limited) {
        return new Response('Too Many Requests', {
            status: 429,
            headers: result.headers
        });
    }

    const response = NextResponse.next();
    for (const [key, value] of Object.entries(result.headers)) {
        response.headers.set(key, value);
    }
    return response;
}

Options

Both withRateLimit and nextjsRateLimit accept all core optionslimit, algorithm, cost, store, keyGenerator, skip, handler, message, statusCode, headers, legacyHeaders, failOpen, and prefix.

Example

See examples/nextjs for a complete Next.js App Router app with integration tests.

Documentation

View the full documentation

License

MIT

On this page