1

I have a Node Js + Express 4 + express-handlebars app. I am using Passport for local authentication. I want to show the logged in username on the top of the page. Right now I have to define it on each page render.

res.render('somePage', {
    title : 'My page',
    userName : req.user.Name,
});

I did some research and found a similar StackOverflow question (two year old question where he was using Express3) where the suggested solution was to use app.locals to set res.locals username variable.

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

{{user.Name}}

I tried that but it did not work for me.

How can I set the username once after login so I do not have to include it on every page render?

1 Answer 1

1

try adding .user after locals

res.locals.user = {user: req.user};

Hope this helps :)

Sign up to request clarification or add additional context in comments.

5 Comments

and in your view file use {{user.user}}
hmmm, i think its better if you use session instead of locals.
because i think, if you use locals if you get redirected or page is refreshed. the locals will also get erased. :)
So what is the solution on this one? Can I use app.locals ?
Found the solution in this question after it was updated recently: stackoverflow.com/questions/22039970/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.