Ron I
Ron I

Reputation: 4250

Node 101: Changing the nav bar when a user is logged in

Hello I am new to Node/Express/Jade and wanted to know a good design pattern for changing the nav bar when a user is logged in (rather than me guessing).

As an example, let's say my template 'nav_home.jade' is a simple nav bar which has 'sign in' and 'home' as the only two links. When the user is logged in I would like the 'sign in' button to be changed to 'sign out'.

I was going to take the approach of creating a different layout using a different template (say 'nav_loggedIn.jade) and then updating the route to something like:

router.get('/', function(req, res) {
  res.render('dashboard', { layout: 'layout_loggedIn' });
});

Is this a good design pattern? Or are there better ways to go about showing different views for logged in users?

Thanks for the help!

Upvotes: 2

Views: 2204

Answers (1)

George Otieno
George Otieno

Reputation: 546

In you main js file you could assign res.locals.user the object that you set after user performs login process e.g. req.user Then in your Jade template you can make a check to see if a user is logged in and display the relevant link

// index.js or server.js
app.use(function(req,res,next){
if (req.user) {
    res.locals.user = req.user;
}
next();
});

// Jade template
if (user) 
   a(href="/logout") Logout
else 
   a(href="/login") Login

Upvotes: 2

Related Questions