Skip to main content
#nodebeginnerJavaScriptNode NewbsNode.jsWeb Dev

Conditionally render a navbar items in an EJS template with res.locals in express.js

By August 12, 2019July 19th, 2022No Comments

This snippet is to conditionally render navbar items based on whether a user is logged in OR not in an EJS template.  So toggle the ‘Login’ button to ‘Logout’ if the user is already logged in and vice versa. I admit it took more time that I had anticipated. Primarily because in the beginning I insisted on using a global variable in express to manage the user’s ‘isAuthenticated’  state so as to pass values to an EJS  partial. So  I declared and initialized with the keywords ‘global’ and then global.varName = boolean. And then in the  routes I changed the value of the ‘isLoggedIn’ global variable to true/false depending on whether the user was logged in or not. Also I was leaving res.locals alone so that others could extend the functionality if need be themselves.

Then I deployed to Heroku and broke the app. So I finally decided to just use res.locals which I had looked at initially. Here it is with

In app.js

//sessions
app.use(session({
secret: require("./bin/config").sessionSecret,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 300000
}
}));

// middleware to make 'user' available to all templates
app.use(function (req, res, next) {
if(req.session.userId !== undefined){
res.locals.loggedIn = req.user;
} else{
res.locals.loggedIn = null;
}
next()
})

In navbar.ejs

 

Leave a Reply