0

I'm wondering if there is a way to put user data available in session, in response of routes by default. For example writing something like this:

app.get("/someRandomPath",PutUserData,function(req,res,next)
{
  res.render("myView",{title:"my page title"})
}

function PutUserData(req,res,next)
{
  if(auth)
  {
   res.send({user:session.user}
   next()
  }
  else next()
}

or even better do something in application level such as app.use(...) ? The reason I want to do this is I want to avoid checking if user is Authed or not in every single route and render views with different data. I'd appreciate your help.

Hirad Roshandel
  • 2,175
  • 5
  • 40
  • 63

1 Answers1

1

Check out res.locals from the Express documentation. That could work for you.

http://expressjs.com/en/api.html#res.locals

Also, see this answer for help understanding how res.locals works.

 app.use(function(req, res, next){
   res.locals.user = session.user;
   next();
 });

front-end (jade template but you can use whatever templating engine you want)

extends layout

block content   
  p user was set to #{user}
Community
  • 1
  • 1
Mike
  • 10,297
  • 2
  • 21
  • 21