javascriptnode.jsexpressroutes

How to pass a parameter to middleware function in Express JS?


// state edit route
app.get("/map/:symbol/edit", isLoggedIn, function(req, res){
  State.findOne({symbol: req.params.symbol}, function(err, state){
    if(err){
      console.log(err);
    } else
    {
      res.render("edit", {state: state});
    }
  });
});

In the above code snippet, isLoggedIn is the middleware function to check for authentication. Its definition is given below:

// middleware function
function isLoggedIn(req, res, next){
  if(req.isAuthenticated()){
    return next();
  }
  res.redirect("/admin");
}

So, the question is, how to pass a parameter like a string, an integer or a path variable to the middleware function so that it can be used in the routing url ?


Solution

  • I had the same requirement and this approach works for me.

    Middleware file validate.js

    exports.grantAccess = function(action, resource){
        return async (req, res, next) => {
            try {
                const permission = roles.can(req.user.role)[action](resource);
                // Do something
                next();
            }
            catch (error) {
                next(error)
            }
        }
    }
    

    Use of middleware in route file. grantAccess('readAny', 'user')

    router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
        // Do something     
    });