This snippet is to conditionally render navbar items based on whether a user is logged in OR not. 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
Join 7000+ other code newbies
Last year 7000 newbies learned how to code with me! Totally project oriented.
Subscribe and you'll get access to my classes, coupon codes for tech conferences and totally valuable article on jump-starting your career as a developer.