Node js Rate Limit

Mihir Patel picture Mihir Patel · Feb 26, 2017 · Viewed 9.9k times · Source

I am trying to set API rate limit on my app using express-rate-limit. It works if it is from the same IP address. I have an error message once it reaches a max of 5. However, it fails when it is tried from different IP address/computer. Any idea how I can fix this? I tried using 127.0.0.1 to generate a key regardless of which IP address but that failed as well.

Below is my code:

// Rate Limit
var RateLimit = require('express-rate-limit');

app.enable('trust proxy');

var limiter = new RateLimit({
  windowMs: 365*24*60*60*1000, // 1 year
  max: 5, // limit each IP to 1 requests per windowMs
  delayMs: 365*24*60*60*1000, // delaying - 365 days until the max limit is reached
  message: "Sorry, the maximum limit of 50 letters sent has been reached. Thank you for participating!",
  keyGenerator: function (req) {
    req.ip = "127.0.0.1";
    // req.ip = "ip address";
    return req.ip;
  }
});

app.use('/api/letter', limiter); 

Answer

robertklep picture robertklep · Feb 26, 2017

The memory store implementation used by express-rate-limit uses setTimeout() to clear the store after windowMs milliseconds.

According to the Node.js documentation for setTimeout(),

When delay is larger than 2147483647 or less than 1, the delay will be set to 1.

In your case, the delay is larger than that amount, namely 31536000000 milliseconds. This results in the store never storing any data for more than 1ms.

To solve this, you probably have to implement your own store (see the store option), or perhaps look for an alternative rate limiter that doesn't have this limit (it seems to me that with such large expiry times, you'll need some sort of persistent storage anyway).