Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
express-rate-limit
Advanced tools
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
The express-rate-limit npm package is a middleware for Express applications that enables rate limiting to prevent abuse by restricting the number of requests a client can make in a given time frame. It is useful for preventing brute force attacks, DDoS attacks, and to generally control the traffic to an API or web application.
Basic rate-limiting
This feature sets up basic rate-limiting on an Express application, limiting clients to a specified number of requests within a time frame.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
// Apply to all requests
app.use(limiter);
Custom message
This feature allows customization of the message sent back to the client when the rate limit is exceeded.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests, please try again later.'
});
app.use(limiter);
Skip certain requests
This feature allows some requests to bypass the rate limit, based on a condition such as a specific IP address.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
skip: function (req, res) {
return req.ip === '123.123.123.123';
}
});
app.use(limiter);
Customize response headers
This feature enables sending HTTP headers to the client with information about their current rate limit status.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
headers: true
});
app.use(limiter);
The 'ratelimiter' package is similar to 'express-rate-limit' but uses Redis for storing rate limit data, which makes it suitable for distributed applications. It is more complex to set up due to the dependency on Redis.
The 'express-brute' package provides rate limiting with a focus on preventing brute-force attacks. It offers more customization options for handling lockouts and has a pluggable store system, which can be more flexible than 'express-rate-limit'.
The 'express-slow-down' package is similar to 'express-rate-limit' but instead of blocking requests after a limit is reached, it slows down the response times. It's useful for slowing down repeated requests rather than completely blocking them.
Basic rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
Plays nice with express-slow-down.
Note: this module does not share state with other processes/servers by default. If you need a more robust solution, I recommend using an external store:
This module was designed to only handle the basics and didn't even support external stores initially. These other options all are excellent pieces of software and may be more appropriate for some situations:
$ npm install --save express-rate-limit
For an API-only server where the rate-limiter should be applied to all requests:
const rateLimit = require("express-rate-limit");
// Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set('trust proxy', 1);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
// apply to all requests
app.use(limiter);
For a "regular" web server (e.g. anything that uses express.static()
), where the rate-limiter should only apply to certain requests:
const rateLimit = require("express-rate-limit");
// Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set('trust proxy', 1);
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100
});
// only apply to requests that begin with /api/
app.use("/api/", apiLimiter);
Create multiple instances to apply different rules to different routes:
const rateLimit = require("express-rate-limit");
// Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set('trust proxy', 1);
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100
});
app.use("/api/", apiLimiter);
const createAccountLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour window
max: 5, // start blocking after 5 requests
message:
"Too many accounts created from this IP, please try again after an hour"
});
app.post("/create-account", createAccountLimiter, function(req, res) {
//...
});
Note: most stores will require additional configuration, such as custom prefixes, when using multiple instances. The default built-in memory store is an exception to this rule.
A req.rateLimit
property is added to all requests with the limit
, current
, and remaining
number of requests and, if the store provides it, a resetTime
Date object. These may be used in your application code to take additional actions or inform the user of their status.
Max number of connections during windowMs
milliseconds before sending a 429 response.
May be a number, or a function that returns a number or a promise.
Defaults to 5
. Set to 0
to disable.
How long in milliseconds to keep records of requests in memory.
Defaults to 60000
(1 minute).
Error message sent to user when max
is exceeded.
May be a String, JSON object, or any other value that Express's res.send supports.
Defaults to 'Too many requests, please try again later.'
HTTP status code returned when max
is exceeded.
Defaults to 429
.
Enable headers for request limit (X-RateLimit-Limit
) and current usage (X-RateLimit-Remaining
) on all responses and time to wait before retrying (Retry-After
) when max
is exceeded.
Defaults to true
.
Function used to generate keys.
Defaults to req.ip:
function (req /*, res*/) {
return req.ip;
}
The function to handle requests once the max limit is exceeded. It receives the request and the response objects. The "next" param is available if you need to pass to the next middleware.
Thereq.rateLimit
object has limit
, current
, and remaining
number of requests and, if the store provides it, a resetTime
Date object.
Defaults to:
function (req, res, /*next*/) {
res.status(options.statusCode).send(options.message);
}
Function that is called the first time a user hits the rate limit within a given window.
Thereq.rateLimit
object has limit
, current
, and remaining
number of requests and, if the store provides it, a resetTime
Date object.
Default is an empty function:
function (req, res, options) {
/* empty */
}
When set to true
, failed requests won't be counted. Request considered failed when:
close
event triggered)error
event was triggrered by response(Technically they are counted and then un-counted, so a large number of slow requests all at once could still trigger a rate-limit. This may be fixed in a future release.)
Defaults to false
.
When set to true
successful requests (response status < 400) won't be counted.
(Technically they are counted and then un-counted, so a large number of slow requests all at once could still trigger a rate-limit. This may be fixed in a future release.)
Defaults to false
.
Function used to skip requests. Returning true
from the function will skip limiting for that request.
Defaults to always false
(count all requests):
function (/*req, res*/) {
return false;
}
The storage to use when persisting rate limit attempts.
By default, the MemoryStore is used.
Available data stores are:
You may also create your own store. It must implement the following in order to function:
function SomeStore() {
/**
* Increments the value in the underlying store for the given key.
* @method function
* @param {string} key - The key to use as the unique identifier passed
* down from RateLimit.
* @param {Function} cb - The callback issued when the underlying
* store is finished.
*
* The callback should be called with three values:
* - error (usually null)
* - hitCount for this IP
* - resetTime - JS Date object (optional, but necessary for X-RateLimit-Reset header)
*/
this.incr = function(key, cb) {
// increment storage
cb(null, hits, resetTime);
};
/**
* Decrements the value in the underlying store for the given key. Used only when skipFailedRequests is true
* @method function
* @param {string} key - The key to use as the unique identifier passed
* down from RateLimit.
*/
this.decrement = function(key) {
// decrement storage
};
/**
* Resets a value with the given key.
* @method function
* @param {[type]} key - The key to reset
*/
this.resetKey = function(key) {
// remove key from storage or reset it to 0
};
}
Resets the rate limiting for a given key. (Allow users to complete a captcha or whatever to reset their rate limit, then call this method.)
delayAfter
and delayMs
options; they were moved to a new module: express-slow-down.handler
function so that it no longer changes the response format. Now uses res.send.onLimitReached
now only triggers once for a given ip and window. only handle
is called for every blocked request.v2 uses a less precise but less resource intensive method of tracking hits from a given IP. v2 also adds the limiter.resetKey()
API and removes the global: true
option.
MIT © Nathan Friedly
FAQs
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
The npm package express-rate-limit receives a total of 1,159,045 weekly downloads. As such, express-rate-limit popularity was classified as popular.
We found that express-rate-limit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.