How can rate limiter be used per userId?

798 Views Asked by At

We are currently using rate limiter which from my understanding limits requests per user IP. Example code below

import rateLimit from 'express-rate-limit'

const apiLimiter = rateLimit({
    windowMs:  10000, // 10 seconds
    max: 1, 
    standardHeaders: true, 
    legacyHeaders: false, 
})

app.use('/api', apiLimiter, //endpoint)

Is it possible to use rate limiter per userId incase requests are sent from multiple devices at once which will have different IPs

1

There are 1 best solutions below

0
Nathan Friedly On

Yes, you can set a custom keyGenerator to return a userId rather than an IP address:

import rateLimit from 'express-rate-limit'

const apiLimiter = rateLimit({
    windowMs:  10000, // 10 seconds
    max: 1, 
    standardHeaders: true, 
    legacyHeaders: false,
    keyGenerator: function(req) {
      // return the user id for the request here
    } 
})

app.use('/api', apiLimiter, //endpoint)

The keyGenerator function may also be async or return a Promise if you can't determine userId synchronously.


Disclosure: I'm the author of express-rate-limit.