Honchar Denys
Honchar Denys

Reputation: 1508

Nodejs Global middleware

How can we add middleware to app.use() and use that middleware only when we call it. At the moment i have this code:

function ensureUser(req,res,next){
   if(req.isAuthenticated()) next();
   else res.send(false);
}
app.get('/anything', ensureUser, function(req,res){
    // some code
})

And i am trying to add that ensureUser to all files where i have routes. I came with a solution of add that file to one file and require that file in every file where i have routes. Is there a way to add that function to app.use or app.all or something like that, in the way i don't have to include that function in every file.

Upvotes: 3

Views: 2722

Answers (1)

Francisco Presencia
Francisco Presencia

Reputation: 8841

Yes, adding an app.use() before any of your routes without a first argument and that one should be called always:

app.use(function(req, res, next){
  if(req.isAuthenticated()) next();
  else res.send(false);
});

// routing code
app.get('/', function(req, res){});
app.get('/anything', function(req,res){})
//...

In this way you don't have to include it in every file. However, in this way also you require that every file is authenticated, so you probably want to add some exceptions (at least the authentication page). For this you can include the method in the url with a wildcard:

app.use('/admin/*', function(req, res, next){
  if(req.isAuthenticated()) next();
  else res.send(false);
});

Or to add a whitelist inside the function:

app.use(function(req, res, next){
  // Whitelist
  if(['/', '/public'].indexOf(req.url) !== -1
     || req.isAuthenticated())
    next();

  else
    res.send(false);
}

Upvotes: 8

Related Questions