I am building a public API with a pricing plan. I want to limit API requests to each account and its plan. I use NodeJS and ExpressJS
These code cannot run properly, i cannot next() after return the data. How to solve this middlerware?
const rateLimit = require("express-rate-limit"); const freePlan = rateLimit({ windowMs: 1 * 60 * 1000, max: 5, message: { error: "Try again after 1 minute" } }) const premiumPlan = rateLimit({ windowMs: 1 * 60 * 1000, max: 30, message: { error: "Try again after 1 minute" } }) function limiter(req, res, next ) { switch (req.body.plan) { case "free": return freePlan break; case "big": return premiumPlan break; default: break; } next(); } module.exports = limiter;
const express = require('express'); const limiter = require("../middlewares/limiter"); const router = express.Router(); router.get('/', limiter, async (req, res) => { res.send('OK'); }) module.exports = router;
Here is i found answer from github and sharing here..
const rateLimit = require("express-rate-limit");
function isPremium(req) {
//... your logic to return true false based on premium plan or not
}
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
// see https://github.com/nfriedly/express-rate-limit#max
max: function(req, res) {
if (isPremium(req)) {
return 30;
}
return 5;
}
});
// apply to all requests
app.use(limiter);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.