title: express-session: Why is redirect executed before my session info is set?
body: <p>Yet another "I've just started learning node.js/express and now I stuck" person here. I've tried looking everywhere for answers but I've reached a dead end. This is my first Stackoverflow question, so please tell me if I have done something wrong or unconventional.</p>
  
  <p>I'm trying to create a POST request that saves a User-object to an express-session (on MongoDB), and redirects you to a URL that handles your session information.</p>
  
  <p>The problem is, that the user is redirected before the header is set, and I am given the following:
  <code>Error: Can't set headers after they are sent.</code></p>
  
  <p>Here is my code. I know it's a lot.. Im sorry.</p>
  
  <h3>router.post()</h3>
  
  <pre><code>// Handler for POST requests from root page (/)
  router.post('/', function(req, res) {
      console.log("Router: A POST request for: \"/\" has been called!");
  
      var username = req.body.username;
      var password = req.body.password;
  
      // Connect to database
      mongoose.connect(dbAddress);
      var db = mongoose.connection;
  
      // Report if error in connection
      db.on('error', console.error.bind(console, 'Database: Connection error..'));
  
      // Callback function on 'open'
      db.once('open', function() {
          console.log("Database: Connection successful!");
          console.log("Database: User supplied username: " + username);
          console.log("Database: User supplied password: " + password);
  
          // Find User object with a userId of req's username
          User.findOne({ 'userId' : username.toUpperCase() }, function(err, userObj) {
  
              if (err)
                  return console.err(err);
  
              // Disconnect when done retrieving user object
              mongoose.disconnect();
  
              if ( userObj ) {
                  console.log("Database: Returned password from MongoDB:");
                  console.log(userObj.password);
  
                  var db_password = userObj.password;
  
                  if (password === db_password) {
                      console.log("Database: User Authenticated");
  
                      // Set 'req.session.user' as cookie
                      req.session.user = userObj;
  
                      // Redirect to homepage, with new cookie set
                      res.redirect('/');
  
                  } else { // If passwords don't match
                      res.render('index', {
                          showError: true
                      });
                  }
              } else { // If userObj is null
                  res.render('index', {
                      showError: true
                  });
              }
  
          });
      }); 
  });
  </code></pre>
  
  <p>Note the 'req.session.user = userObj' part. Here I am trying to set 'user' in the session to the user object retrieved from MongoDB. In the next line, I am redirecting the user back to the GET request handler for '/' which handles the user based on the session information. </p>
  
  <p>For some reason, these aren't happening in order. The GET request handler doesn't find req.session.user.</p>
  
  <p>I understand that node.js is all about asynchronisation, but from other examples I've found online, this is supposed to work. What am I missing here?</p>