Express.js: Can't redirect after using session middleware

Problem

I am writing an authentication middleware and it is supposed to redirect to previously visited page after successful login our logout. Here's the complete config block:

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: '__YouDontKnow__', store: new RedisStore }));
  app.use(authCheck.run);
  app.use(express.methodOverride());
  app.use(app.router);
});

Now when app.use(authCheck.run) is under app.use(express.session), Express throws error: Error: Can't set headers after they are sent.

If I move this call above app.use(express.session), it throws a 500 error saying that session is undefined. And my auth function depends on the session object.

What can I do?

EDIT: here's the authCheck function:

exports.run = function (req, res, next) {
  var urlparser = GLOBAL.urlparser,
      url = req.urlp = urlparser.parse(req.url, true),

      goToLastPage = function() {
        var redirectUrl = (req.session.lastVisitedPage) ? req.session.lastVisitedPage : '/';
        console.log("goToLastPage(%s)", redirectUrl);
        res.redirect(redirectUrl);
        return;
      }

  // Log out
  if (url.pathname == '/user/logout') {
    req.session.destroy();
    console.log('User has logged out');
    goToLastPage();
  }

  // Log in
  if (url.pathname == '/user/login' && req.method == 'POST') {
    var email = req.body.login.email,
        password = req.body.login.password;

    req.session.auth = true;
    req.session.userId = 1;

    console.log('User has logged in');

    goToLastPage();
  }

  next();
  return;
}
Problem courtesy of: mvbl fst

Solution

Put a return after you call goToLastPage(). You're still calling next() after you have called res.redirect which calls the next piece of middleware in the chain, likely eventually ending up hitting one of your routes, which then tries to set a header and fails.

Solution courtesy of: jimr

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.