1

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" });
    }
};
soheil
  • 31
  • 4
  • I don't think you can conditionally `app.use` like that inside one middleware; it'll just be added to the end, and multiple times (remember it has app scope). Instead, define a `skip` function in express-rate-limit's options that checks if `req.user` is defined, and add the rate limiter right after the authentication middleware. – Joe Aug 02 '22 at 11:46
  • You could adapt [this example](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#minimal-protection-against-password-brute-force) with `rate-limiter-flexible` package. – Animir Aug 04 '22 at 15:27

1 Answers1

0

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

const rateLimit = require('express-rate-limit')
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
}) // Apply the rate limiting middleware to all requests
app.use(limiter)
app.use(secondMiddleware)

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.