Res.locals.user - how does it work?

Hey, still trying to figure out how to do the user authentication on my app.

I have an example from a tutorial that uses express-session and passportjs. In that example, there is a middleware like this:

app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
  next();
});

From what I understand, it creates some local variables that will be available to the front-end. In the templates, I can use {{user}} to show the user object.

For some reason, I can’t get it to work in my React project. I try doing this:

if(user){
console.log(user)
}

and my code won’t even compile because ‘user’ is not defined.

am I misunderstanding how res.locals works?
Or is it just React being fussy? I really don’t understand what the problem is… if ‘user’ was undefined, it should just not run the console.log and move on, right?

1 Like

res.locals is only available to the view while its being rendered. app.locals behaves as you are expecting.

1 Like

Ah! okay!
thanks!!

I am still having a problem with React. It still sees ‘user’ as undefined and refuses to compile if I have undefined variables. :disappointed:
But at least I am starting to understand that app.locals is on the right track.

1 Like

You need to say if user && if user.length >0…
Its because the page will look for user and if its not there it will crash it.
The .length part will only render user if it has some data in it

1 Like

As said in the previous posts, remember that variables from the back-end (user, in this case) are available only during rendering, not after rendering (usually).

I had a similar problem, but it turns out that setting locals variable should be done after initializing passport. Order of middle wear matters.

I believe you need to use locals.user to get the value displayed.