Search code examples
node.jsexpress

Creating a expressjs middleware that accepts parameters


I am trying to create a middleware that can accept parameters. How can this be done?

example

app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){

})

HasRole = function(role, req, res, next){
   if (role != user.role) {
      res.redirect('/NotInRole');
   }

   next();
}

Solution

  • function HasRole(role) {
      return function(req, res, next) {
        if (role !== req.user.role) res.redirect(...);
        else next();
      }
    }
    

    I also want to make sure that I don't make multiple copies of the same function:

    function HasRole(role) {
      return HasRole[role] || (HasRole[role] = function(req, res, next) {
        if (role !== req.user.role) res.redirect(...);
        else next();
      })
    }