Skip to content

Latest commit

 

History

History
44 lines (32 loc) · 942 Bytes

README.md

File metadata and controls

44 lines (32 loc) · 942 Bytes

NextJS Rate Limiting Middleware

Uses in-memory rate limiting for both session & IP. Doesn't require Redis, simple easy setup, and super basic protection from abuse.

Installation

npm install @daveyplate/next-rate-limit

Usage

Default limits are 30 requests per session within 10 seconds, and 300 requests per IP within 10 seconds (10 users)

export function rateLimit({ 
    request, 
    response, 
    sessionLimit = 30, 
    ipLimit = 300, 
    windowMs = 10 * 1000 
})

middleware.js

import { NextResponse } from 'next/server'
import { rateLimit } from '@daveyplate/next-rate-limit'

export function middleware(request) {
    const response = NextResponse.next()

    const rateLimitResponse = rateLimit({ request, response })
    if (rateLimitResponse) return rateLimitResponse

    return response
}

// Apply middleware to all API routes
export const config = {
    matcher: '/api/:path*'
}