title: Why is req.session undefined when I am checking user is logged in so that I can conditionally serve static files?
body: <p>Once the user logs in, I am trying to serve static files. I applied the answer found <a href="https://stackoverflow.com/questions/48616368/what-is-the-best-way-to-conditionally-serve-static-files-in-express">here</a> and I am having difficulty implementing it.</p>
  
  <p>Upon log-in, I have this inside of routes.js:  </p>
  
  <pre><code>app.post('/', function(req, res){
      AM.manualLogin(req.body['user'], req.body['pass'], function(e, o){
          if (!o){
              res.status(400).send(e);
          } else {
              req.session.user = o;
              if (req.body['remember-me'] == 'true'){
                  res.cookie('user', o.user, { maxAge: 900000 });
                  res.cookie('pass', o.pass, { maxAge: 900000 });
              }
              console.log(req.session);
              res.status(200).send(o);
          }
      });
  });
  </code></pre>
  
  <p>where I am setting the user in the request's session.</p>
  
  <p>Inside app.js I have:</p>
  
  <pre><code>var http = require('http');
  var express = require('express');
  var session = require('express-session');
  var bodyParser = require('body-parser');
  var errorHandler = require('errorhandler');
  var cookieParser = require('cookie-parser');
  var MongoStore = require('connect-mongo')(session);
  
  var app = express();
  
  app.locals.pretty = true;
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/app/server/views');
  app.set('view engine', 'pug');
  app.use(cookieParser());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(require('stylus').middleware({ src: __dirname + '/app/public' }));
  
  function isLoggedIn( req, res, next ) {
      console.log(req.session);
      if (typeof req.session.user == undefined) {
          res.redirect('/');
      }
  
      next();
   }
  
  
  app.use(express.static(__dirname + '/app/public'));
  app.use('/home', isLoggedIn, express.static(__dirname + "/app/server/docs"));
  
  app.use(session({
      secret: 'faeb4453e5d14fe6f6d04637f78077c76c73d1b4',
      proxy: true,
      resave: true,
      saveUninitialized: true,
      store: new MongoStore({ url: process.env.DB_URL })
    })
  );
  
  require('./app/server/routes')(app);
  
  http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
  });
  </code></pre>
  
  <p>where I am conditionally trying to render the static files for <code>/home</code>.</p>
  
  <p>The problem resides in <code>isLoggedIn</code> where req.session is always undefined even though it is defined in my router function. Why is this? My log statements show that is is being set, but somehow is lost inside <code>isLoggedIn</code>.</p>