title: How to pass session into views in Node/Express?
body: <p>I am playing around with Node/Express 3.0. But I am not sure how to get session out. Especially I am not sure if I am doing right with the following in routes/session.js.</p>
  
  <pre><code>app.use(function(req, res, next) {
    res.locals.session = req.session;
    next();
  });
  </code></pre>
  
  <p>The followings are more details.</p>
  
  <p>I have this in app.js</p>
  
  <pre><code>var express = require('express')
    , routes = require('./routes')
    , http = require('http')
    , path = require('path')
    ;
  
  var app = express();
  
  app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser('testtest'));
    app.use(express.session({
      secret: 'testtest',
      maxAge: 3600000
    }));
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
  });
  ...
  require ('./routes/session')(app);
  ...
  http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
  });
  </code></pre>
  
  <p>And in routes/session.js</p>
  
  <pre><code>module.exports = function(app) {
  
    app.use(function(req, res, next) {
      res.locals.session = req.session;
      next();
    });
  
    app.get('/session/new', function(req, res) {
      res.render('session/new', {title: "Log in"});
    });
  
    app.post('/session', function(req, res) {
      if (users[req.body.username] &amp;&amp; 
        users[req.body.username].password === req.body.password) {
          req.session.user = users[req.body.username];
          res.redirect('/users');
        } else {
          res.redirect('/session/new')
        }
    });
  
    app.del('/session', function(req, res, next) {
      req.session.destroy();
      res.redirect('/users');
    });
  
  };
  </code></pre>
  
  <p>I have this in view. </p>
  
  <pre><code>- if (session.user) {
  
    p
      span Hello&amp;nbsp;
      span= session.user.name
      span= session
      span !
    p
      form(method="POST", action="/session")
        input(type="hidden", name="_method", value="DELETE")
        input(type="submit", value="Log out")
  
  - } else {
  
    p
      a(href="/session/new") Login
      span &amp;nbsp;or&amp;nbsp;
      a(href="/users/new") Register
  
  - }
  </code></pre>
  
  <p>But this does not pick up session and gives an error. </p>
  
  <pre><code>1| &gt; 2| - if (session.user) { 3| 4| p 5| span Hello  session is not defined
  </code></pre>