@prexjs/rate-limit
v1.0.0
Published
Configurable rate limiting middleware for Node.js, Express, and Prex to protect endpoints from abuse and brute force.
Readme
@prexjs/rate-limit
Configurable rate limiting middleware for Node.js, Express, and Prex to protect endpoints from abuse and brute force.
@prexjs/rate-limit is a flexible rate-limiting middleware for Node.js HTTP servers, Prex, and Express. It tracks client request frequencies within rolling time windows to protect endpoints against denial of service, brute force attacks, and abusive scraping.
Features
- Sliding & Fixed Windows: Configurable time window (
windowMs) with convenient constants (MINUTE,HOUR,DAY). - Store Abstraction: Ships with high-performance
MemoryStore, and supports custom external stores (e.g. Redis, Memcached). - Standard Rate Limit Headers: Automatically sends
RateLimit-*andRetry-Afterheaders conforming to draft RFC standards. - Custom Key Generation: Identify clients by IP address with IPv6 subnet normalization, API keys, or custom session tokens.
- Granular Handler & Skip Rules: Conditionally bypass limits or customize rejection payloads and status codes.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/rate-limit
# pnpm
pnpm add @prexjs/rate-limit
# Yarn
yarn add @prexjs/rate-limit
# Bun
bun add @prexjs/rate-limitQuick start
import http from 'node:http';
import rateLimit, { MINUTE } from '@prexjs/rate-limit';
// Allow a maximum of 100 requests per 15 minutes
const limiter = rateLimit({
windowMs: 15 * MINUTE,
limit: 100,
standardHeaders: 'draft-7', // draft-6, draft-7, or combined
legacyHeaders: false,
message: { error: 'Too many requests, please try again later.' },
});
const server = http.createServer((req, res) => {
limiter(req as any, res as any, (err) => {
if (err) {
res.statusCode = 500;
res.end('Server error');
return;
}
res.end('Welcome! Request allowed.');
});
});
server.listen(3000);API
rateLimit(options)
Creates the rate-limiting middleware.
windowMs: Time frame for which requests are checked/remembered in milliseconds (e.g.15 * MINUTE).limit: Maximum number of connections duringwindowMs(or a function returning a number).message: Response body sent when a client exceeds the limit (string, object, or custom function).statusCode: HTTP status returned upon limit breach (default:429).keyGenerator: Function(req, res) => stringused to generate unique client identifiers (defaults to IP address).skip: Function(req, res) => booleanto conditionally bypass rate limiting.store: Storage engine instance (defaults tonew MemoryStore()).
Exported Constants
SECOND:1000msMINUTE:60 * 1000msHOUR:60 * 60 * 1000msDAY:24 * 60 * 60 * 1000ms
Compatibility
- Node.js >= 18.0.0
- Supports both ESM and CommonJS
- TypeScript 5.0+
Related Packages
@prexjs/ipaddress: IP address parser and CIDR calculator.@prexjs/debug: Small debugging utility.
