1

Im using express-rate-limit to limit the amount of requests but I want it to be per user. As of now its being applied to all users. I do get the ip address from req.ip and thought that using keyGenerator and returning the ip would make it be per user but its not. What can I do? Thanks!

const rateLimit = require('express-rate-limit')

const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 1, //this number is just for testing
    standardHeaders: true
    legacyHeaders: false, 
    keyGenerator: (req, res) => {
        return req.ip
    },
    handler: function(req, res, next) {
        throw new BaseError('too many requests', 429);
        next();
    },
})
learncode
  • 127
  • 6
  • It is by default per user, or not. – tom Jul 14 '23 at 22:05
  • Hmm is there then something wrong with my code? Because I apply it for nw for testing for my login route, making it so you can only login once per 15 min (once for testing purposes). then when I use a different phone/getting a different ip address, logging in, I cant because the rate limiter prevents me. However, it shouldnt, because the second time I log in from a different phone – learncode Jul 15 '23 at 08:38

1 Answers1

0

Most likely, there is a reverse proxy between your web app and the internet, and you're rate limiting it's IP.

Try setting app.set('trust proxy', 1), that solves the issue for most users. If 1 doesn't work, try 2, etc. See https://github.com/express-rate-limit/express-rate-limit/wiki/Troubleshooting-Proxy-Issues for more info.

Additionally if you update to the latest release of express-rate-limit (published about 5 days after your question) it will automatically run a few validation checks on the first request and login error to the console if it detects misconfigured proxy settings.

Nathan Friedly
  • 7,837
  • 3
  • 42
  • 59