I am using express, node and handlebars to create a web app with passport being the authentication library. I am trying to set a variable in res.locals
to render a navigation bar based on user state. The issue I am having is that when setting res.locals.isUser
or res.locals.isAdmin
using middleware, the variable does not seem to be passed around or at least it does not appear to be. Code is below (watered down for simplicity).
app.js
var app = require('express)();
app.use(function(req, res, next){
res.locals.isUser = false;
if(req.user && req.user.role === 'user'){
res.locals.isUser = true;
}
next();
});
// Admin logic same as above but isAdmin instead of isUser
var passport = require('./lib/auth/passport.js')(app);
require('./routes.js');
layout.handlebars
{{#if isUser}}
{{> userNav}}
{{else if isAdmin}}
{{> adminNav}}
{{else}}
<nav>
// Render normal nav
</nav>
{{/if}}
{{{body}}}
What is happening is when the user logs in the nav bar changes, but when the user logs out, sometimes, the nav bar stays as {{> userNav}}
. Refreshing the page seems to fix the issue. Furthermore, once the user is logged out, and the nav bar stays as {{> userNav}}
, clicking on a link in the nav bar sends me to a 404. This assured me that the passport logout mechanism is working fine. I placed a console.log('...')
in the middleware just to see if it is being called on every request, and sure enough it is. I moved the middleware into the routes.js
file, issue still persists. I have racked my brain and have no idea why this is the case. It seemed to work fine a few days ago, or at least I never noticed this issue before. Am I doing something wrong? Any help would be greatly appreciated. Thanks all!
Using...
- Express
- Express-Handlebars
- Passport
- MongoDB
Some related posts...