By default, express-rate-limit
has a keyGenerator
of req.ip
. When I log this on my server it is '::ffff:127.0.0.1'
which is obviously going to be the same for every request, thus limiting for all IP addresses once it’s limited for one.
My solution was to use request-ip
to get the correct IP address like so:
const rateLimit = require('express-rate-limit');
const requestIp = require('request-ip');
const app = express();
app.use(requestIp.mw());
app.use(rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 30, // limit each IP to 30 requests per windowMs
keyGenerator: (req, res) => {
return req.clientIp // IP address from requestIp.mw(), as opposed to req.ip
}
}));
keyGenerator: function (req: any) {
return req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}