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.
Two problems here:
express-rate-limit does not currently support dynamic window sizes. windowMs
must be a single number that is the same for all requests.
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.