title: Express4. What's the difference between app.locals, res.locals and req.app.locals?
body: <p>I am so confused while using express 4. I use <em>express-generator</em> to generate my project. And there are <strong>app.js</strong> in root and <strong>index.js</strong> in router file. However, the tutorial on internet about express are using router directly in <strong>app.js</strong>. So when I want to set some variables in <strong>index.js</strong>(in router file), I use app.locals, but it doesn't work. But when I change to the other two, my ejs template works... I am very confused. Anybody can tell me the difference between them and how to use correctly, please?</p>
  
  <pre><code>&lt;!-- language: index.js in router file --&gt;
  
      var app = require('express');
      var router = express.Router();
  
      ....
  
  router.get('/', function(req, res, next) {
      var _user = req.session.user;
      if (_user) {
        //does't work!!
        //app.locals.user=_user;
        //I am not sure about which usage is correct below
        //1.
        req.app.locals.user = _user;
        //2.
        // res.locals.user=_user;
      }
  }
  
  &lt;!-- language: lang-ejs --&gt;
  
      &lt;% if (user) { %&gt;
        &lt;li&gt;&lt;a class="navbar-link"&gt;Welcome &lt;%= user.name %&gt;&lt;/a&gt;
        &lt;/li&gt;
        &lt;span&gt;&amp;nbsp;|&amp;nbsp;&lt;/span&gt;
        &lt;li&gt;&lt;a href="/logout" class="navbar-link" id="logoutBtn"&gt;Logout&lt;/a&gt;
        &lt;/li&gt;
        &lt;% } else { %&gt;
          &lt;li&gt;&lt;a href="#" class="navbar-link" data-toggle="modal" data-target="#signinModal"&gt;登录&lt;/a&gt;
          &lt;/li&gt;
          &lt;span&gt;&amp;nbsp;|&amp;nbsp;&lt;/span&gt;
          &lt;li&gt;&lt;a href="#" class="navbar-link" data-toggle="modal" data-target="#signupModal"&gt;注册&lt;/a&gt;
          &lt;/li&gt;
        &lt;% } %&gt;
  </code></pre>