Search code examples
node.jsexpressmiddlewarerate-limitingexpress-rate-limit

how to add dynamically windowMS and max value in rateLimit using express-rate-limit


const rateLimit = require("express-rate-limit");
const limitMiddleware = (req = {}, res = {}, next) => {
    return rateLimit({
        windowMs: req.body.timeLimit,
        max: req.body.messageLimit,
        keyGenerator: function (req) {
            console.log("req.query.userId", req.query.userId);
            return req.query.userId;
        },
        handler: function (req, res, next) {
            res.status(429).json({
                message: "You have exceeded your request limit.",
            });
        },
        headers: true,
    });
};

module.exports = limitMiddleware;

i tried with set the limit and duration that are get in body parameter but it's not send message when limit exceeded.


Solution

  • Two problems here:

    1. express-rate-limit does not currently support dynamic window sizes. windowMs must be a single number that is the same for all requests.

    2. The rateLimit instance must be created before you handle any requests. Your code will create a new instance for every request, but never use any of the instances.

    Also, one third related problem, the max field can be dynamic, but it should be a function, similar to your keyGenerator to work correctly.


    Disclosure: I'm the author of express-rate-limit.