Skip to content

Instantly share code, notes, and snippets.

@snghnishant
Last active November 9, 2022 08:36
Show Gist options
  • Save snghnishant/69fd8f9ee126931deb566320e6efd754 to your computer and use it in GitHub Desktop.
Save snghnishant/69fd8f9ee126931deb566320e6efd754 to your computer and use it in GitHub Desktop.
Express + Redis API Rate limiter
const rateLimit = require("express-rate-limit");
const RateLimitRedis = require("rate-limit-redis");
const { REDIS_HOST } = process.env;
const RedisClient = require("ioredis");
// Create a `ioredis` client
const options = REDIS_HOST
? { host: REDIS_HOST, port: 6379 }
: { host: "localhost", port: 6379 };
// console.log("Redis IO config: ", options);
const client = new RedisClient(options);
function redisRateLimiter(
prefix = "rl:",
windowSize = 1 * 60 * 1000,
requestLimit = 4
) {
const limiter = rateLimit({
// Redis store configuration
store: new RateLimitRedis({
prefix: prefix,
sendCommand: (...args) => client.call(...args)
}),
standardHeaders: false, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
max: requestLimit,
windowMs: windowSize, // lookup window size (requests in certain time range in milliseconds)
keyGenerator: (request) => {
// Adding user level identifier to limit the requests on specific user data resource
// This helps to avoid bruteforce attacks with ip change to a speicifc user data resource access
const suffix = request.userData
? request.userData.userId
: request.body.payload ?? request.body.phone;
// console.log(prefix + suffix);
return prefix + suffix;
}
});
return limiter;
}
module.exports = redisRateLimiter;
// Usage
// rate limiter for auth verification api
// const myApiRateLimiter = require("./rateLimiter")(
// "rl_keyName:"
// );
// router.post("/route", myApiRateLimiter, controllerFunction);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment