title: Node.js - Issue with res.redirect in middleware
body: <p>I'm trying to use a authenticateUser() middleware before loading all of my pages. Instead of including it in each call (as in app.get('/', authenticateUser, function()...)), I tried setting it with app.use(authenticateUser) right before calling app.use(app.router).</p>
  
  <p>This didn't work, however. authenticateUser is basically:</p>
  
  <pre><code>if (req.session.loginFailed) {
    next()
  else {
      if (req.session.user_id) {
          ... 
          if (userAuthenticated) {
              next();
          } else {
              req.session.loginFailed = true;
              console.log('setting loginFailed to true');
              res.redirect('/login');
          }
       }
  }
  </code></pre>
  
  <p>And then in app.get('/login') I set req.session.loginFailed to be false;</p>
  
  <p>This should work, but I only want to call it on an app.get() or app.post() etc. for one of my actual pages. I think its getting called lots of times for many different requests (because upon loading one page, 'setting loginFailed to true' is called many times)</p>
  
  <p>Is there a better way to do this? Or should I simply be calling it before every page on my site?</p>