i want to use express-rate-limiter in a middleware of my node.js app. how can i? in a usuall app, it's in the server.js but i want to blcok user in a middleware.
thanks for your responses
const express=require('express');
const app=express();
const jwt = require("jsonwebtoken");
const rateLimit = require('express-rate-limit');
// limit user logins
const tokenLimiter = rateLimit({
windowMs: 3 * 60 * 1000,
max: 3,
statusCode: 200,
message: {
status: 429,
error: 'block msg'
},
handler: function (req, res) {
res.status(429).json({ msg: 'block msg' });
},
});
module.exports = function (req, res, next) {
let token = req.cookies.authorization;
if (!token) {
token = req.headers.authorization;
}
if (!token) return res.status(401).json({ msg: 'please login' });
try {
const verified = jwt.verify(token, process.env.THE_TOKEN_SECRET);
req.user = verified;
next();
} catch (e) {
app.use(tokenLimiter);
res.status(200).json({ router: "login" });
}
};
You shouldn't be doing this, this voilates the idea of rate limitter. Express executes middlewares sequentially.You should be calling your middleware right after the rate limiter in server.js. I would use something like below in my server.js
Or you could also chain them like Chaining multiple pieces of middleware for specific route in ExpressJS
But if you really want to do it, one workaround is in your code on catch you are redirecting to login, you can add the rate limitter just at login as a middleware.