Home > Back-end >  Can I use api rate limiter by passing it in router.use() in express?
Can I use api rate limiter by passing it in router.use() in express?

Time:06-15

I want to limit API requests of a user according to his plan. For this I am using router.use() functionality here. I just want to ask is this the right way, or my api will not support concurrent requests even after doing that way. If it is wrong please suggest me the correct way of doing it.

Here is my code :

      router.get("requestURL" , async(req,res) => {
      if (user.plan == "PLANTYPE") {
      if (user.requests < user.quota) {
      const limiter = rateLimit({
        windowMs: 1, // 1 sec
        max: user.concurrency, 
        standardHeaders: true, 
        legacyHeaders: false, 
      });
      router.use(limiter);
      }
      }
      })

CodePudding user response:

We can use a function to define the max value.

I think it can be implemented like this

const express = require('express')
const rateLimit = require('express-rate-limit')
const app = express()

const PORT = 3000

// Create a function to define the max limit
const getUserConcurrency = async (user) => {
    if (user.plan == "PLANTYPE" && user.requests < user.quota) {
        return user.concurrency
    }
}

// Setup the rate limiter
const limiter = rateLimit({
    windowMs: 1,
    max: async (request, response) => {
        return await getUserConcurrency(request.user)
    },
    standardHeaders: true,
    legacyHeaders: false,
})

// Pass the rate-limit in the get request
app.get('requestURL', limiter, function (req, res) {
    return res.send('Hello World')
})

app.listen(PORT, () => {
    console.log(`server started on port ${PORT}`)
})

For more detail, you can check their documentation here

  • Related