ReactHelp
ReactHelp

Reputation: 479

How to set X-RateLimit-Reset with express-rate-limit?

I want to set a custom time that a user must wait if they hit a rate limit. I am using express-rate-limit and thought I could do this by setting a custom X-RateLimit-Reset in the handler. I can set this value, but it does not appear to have any effect.

As an extreme example, I tried to block them for a very long time in the future using the following in my handler:

res.setHeader('X-RateLimit-Reset', Date.now() + 100000000000)

Console logging res after this results in something correct:

 'x-ratelimit-reset': [ 'X-RateLimit-Reset', 1566112162159 ] // <-- far in the future

However, after doing this, a user is still able to call the function that should have been rate limited. How can I set a custom reset time for a user?

Upvotes: 0

Views: 3467

Answers (1)

Rishabh
Rishabh

Reputation: 71

First of all, as you've not mentioned it, I'm assuming you're using the default MemoryStore that comes with the express-rate-limit. So to answer your question, you don't have to manually set the x-ratelimit-reset header in the response, the package does it for you.

  • So if you're using the default MemoryStore, the configuration looks like this,
app.use(
    RateLimit({
        windowMs: 10 * 60 * 1000 , // 10 minutes
        max: 100, // limit each IP to 100 requests per windowMs
        message: 'You have exceeded the 100 requests in 10 minutes limit!',
    })
);
  • And, if you're using a store other than the default one, you can add the store config in it,
app.use(
    RateLimit({
        store: new MongoStore({
            uri: 'mongodb://localhost:27017/your-db-name',
            expireTimeMs: 10 * 60 * 1000 // 10 minutes
        }),
        windowMs: 10 * 60 * 1000 , // 10 minutes
        max: 100, // limit each IP to 100 requests per windowMs
        message: 'You have exceeded the 100 requests in 10 minutes limit!',
    })
);

Just to note here, rate-limt-redis store has some problems with x-ratelimit-reset header and doesn't work as expected. So, you can go ahead with other options.

Upvotes: 0

Related Questions