title: Setting res.locals using middleware in Express is not getting passed around on every request?
body: <p>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 <code>res.locals</code> to render a navigation bar based on user state.  The issue I am having is that when setting <code>res.locals.isUser</code> or <code>res.locals.isAdmin</code> 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).</p>
  
  <p>app.js</p>
  
  <pre><code>var app = require('express)();
  
  app.use(function(req, res, next){
     res.locals.isUser = false;
     if(req.user &amp;&amp; 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');
  </code></pre>
  
  <p>layout.handlebars</p>
  
  <pre><code> {{#if isUser}}
       {{&gt; userNav}}
   {{else if isAdmin}}
       {{&gt; adminNav}}
   {{else}}
       &lt;nav&gt;
           // Render normal nav
       &lt;/nav&gt;
   {{/if}}
  
   {{{body}}}
  </code></pre>
  
  <p>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 <code>{{&gt; userNav}}</code>. Refreshing the page seems to fix the issue. Furthermore, once the user is logged out, and the nav bar stays as <code>{{&gt; userNav}}</code>, 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 <code>console.log('...')</code> 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 <code>routes.js</code> 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!</p>
  
  <p>Using...</p>
  
  <ul>
  <li>Express</li>
  <li>Express-Handlebars</li>
  <li>Passport</li>
  <li>MongoDB</li>
  </ul>
  
  <p>Some related posts...</p>
  
  <p><a href="https://stackoverflow.com/questions/13758207/why-is-passportjs-in-node-not-removing-session-on-logout">Why is PassportJS in Node not removing session on logout</a></p>
  
  <p><a href="https://stackoverflow.com/questions/10199400/expressjade-local-variable-not-available-in-view">Express+jade: local variable not available in view</a></p>