Home > OS >  Set different rate limiters for a single route using express-rate-limit
Set different rate limiters for a single route using express-rate-limit

Time:11-08

I have a route like this in express

router.route('/sign-upload').post(signUpload)

And I want to use different rate limiters for this route based on the request.

router.route('/sign-upload').post(function (req, res, next) {
switch (req.body.qty) {
  case 'one':
    console.log('case one')
    B1Limiter
    break
  case '10-50':
    console.log('case 10-50')
    B10To50Limiter
    break
  case '50-250':
    console.log('case 50-250')
    B50To250Limiter
    break
  case '250-1000':
    console.log('case  250-1000')
    B250To1kLimiter
    break
  default:
    console.log('case default')
    B1Limiter
    break
}
next()},signUpload)

These are my limiters:

import rateLimit from 'express-rate-limit'

// B1 15req/hr
export const B1Limiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 15, 
  message: 'Too many requests from this IP. Please try again after an hour',
})

// B10-50 300req/day
export const B10To50Limiter = rateLimit({
  windowMs: 24 * 60 * 60 * 1000,
  max: 300,
  message: 'Too many requests from this IP. Please try again tomorrow',
})

// B50-250 750req/3 days
export const B50To250Limiter = rateLimit({
  windowMs: 3 * 24 * 60 * 60 * 1000,
  max: 750,
  message: 'Too many requests from this IP. Please try again after three days',
})

// B250-1000 3kreq/week
export const B250To1kLimiter = rateLimit({
  windowMs: 7 * 24 * 60 * 60 * 1000,
  max: 3000, 
  message: 'Too many requests from this IP. Please try again after week',
})

Rate limiters for this code are not executing. I don't know why.

I cant use a single limiter because windowMs and message are not functions. https://github.com/nfriedly/express-rate-limit/issues/122

Limiter works if I remove the switch case and use only one limiter

router.route('/sign-upload').post(B1Limiter,signUpload)

Does this mean I have to make separate routes for each rate limiter?

CodePudding user response:

You can conditionally select and execute which middleware you want like this:

router.route('/sign-upload').post(function (req, res, next) {
    let limiter = B1Limiter;
    switch (req.body.qty) {
      case 'one':
        console.log('case one')
        limiter = B1Limiter
        break
      case '10-50':
        console.log('case 10-50')
        limiter = B10To50Limiter
        break
      case '50-250':
        console.log('case 50-250')
        limiter = B50To250Limiter
        break
      case '250-1000':
        console.log('case  250-1000')
        limiter = B250To1kLimiter
        break
      default:
        console.log('case default')
        limiter = B1Limiter
        break
    }
    // now call the selected middleware and
    // let it handle calling next()
    limiter(req, res, next);
}, signUpload);
  • Related