express-limit
express-limit is a small project that add rate limitations to your API.
Installation
npm install --save express-limit
Usage
const limit = require("express-limit").limit;
app.get(
"/api/users",
limit({
max: 5,
period: 60 * 1000,
}),
function (req, res) {
res.status(200).json({});
}
);
Options
{
(max = 60),
(period = 60 * 1000),
(prefix = "rate-limit-"),
(status = 429),
(message = "Too many requests"),
(identifier = (request) => {
return request.ip || request.ips;
}),
(headers = {
remaining: "X-RateLimit-Remaining",
reset: "X-RateLimit-Reset",
limit: "X-RateLimit-Limit",
}),
(store = new Store());
}
In some cases, you could want to skip the limitation you made for trusted client.
In this case, you can add a special field in the request object:
req._skip_limits = true;
Also, you could want to add specific limitations for a special client.
In this case, you can add a special field in the request object:
req._custom_limits = {
max: 1000,
period: 60 * 1000,
};
Just don't forget where you place this modification! It could be applied for all routes!
Available Stores
Actually, two stores have been made:
- InMemoryStore (default store, nothing to do)
const RateLimiter = require("express-limit").RateLimiter;
const InMemoryStore = require("express-limit").InMemoryStore;
const store = new InMemoryStore();
const limit = (options = {}) => {
options.store = store;
return new RateLimiter(options).middleware;
};
app.get(
"/api/users",
limit({
max: 5,
period: 60 * 1000,
}),
function (req, res) {
res.status(200).json({});
}
);
const redis = require("redis");
const client = redis.createClient();
const RateLimiter = require("express-limit").RateLimiter;
const RedisStore = require("express-limit").RedisStore;
const store = new RedisStore(client);
const limit = (options = {}) => {
options.store = store;
return new RateLimiter(options).middleware;
};
app.get(
"/api/users",
limit({
max: 5,
period: 60 * 1000,
}),
function (req, res) {
res.status(200).json({});
}
);
- RedisLegacyStore (node-redis v3 or node-redis v4 with legacyMode
true
)
const redis = require("redis");
const client = redis.createClient({
legacyMode: true,
});
const RateLimiter = require("express-limit").RateLimiter;
const RedisLegacyStore = require("express-limit").RedisLegacyStore;
const store = new RedisLegacyStore(client);
const limit = (options = {}) => {
options.store = store;
return new RateLimiter(options).middleware;
};
app.get(
"/api/users",
limit({
max: 5,
period: 60 * 1000,
}),
function (req, res) {
res.status(200).json({});
}
);
Keep in touch!