Dave Kalu
Dave Kalu

Reputation: 1595

Choosing which middleware to run based on request in Express JS

I would like to know how to choose between two different middleware functions, depending on the request for the endpoint. It could look something like this:

router.post("/findAvailableAgents", middleware1 || middleware2, (req, res) => {
  // endpoint body
})

Upvotes: 5

Views: 3165

Answers (3)

ykit9
ykit9

Reputation: 493

There is two ways of achieve optional middleware behaviour:

1) Create another middleware, that checks condition and then passes all the parameters into the desired middleware. Example:

const middlewareStrategy = (req,res,next) => {
    if(req.body.token1){
        return middleware1(req,res,next);
    }
    return middleware2(req,res,next);
};

router.post("/findAvailableAgents", middlewareStrategy, handler);

2) Make middleware logic execution in a condition-driven manner. Example:

const middleware1 = (req,res,next) => {
    if(req.body.token){
        // execute some logic, then
        return next();
    }
    // skip this middleware
    next();
};

router.post("/findAvailableAgents", middleware1, middleware2, handler);

Upvotes: 3

Waseem
Waseem

Reputation: 121

You could use another middleware which decides whether to choose middleware1 or middleware2

const decideMiddleware = (req, res, next) => {
    if(condition) {
        return middleware1(req, res,next)
    } else {
        return middleware2(req, res,next)
    }
}

And use it in your code

router.post("/findAvailableAgents", decideMiddleware, (req, res))

Upvotes: 7

Prasanta Bose
Prasanta Bose

Reputation: 674

Now you can add multiple middleware using a below peice of code

app.get('/',[middleware.requireAuthentication,middleware.logger], function(req, res){
    res.send('Hello!');
});

Upvotes: 0

Related Questions