title: Redirecting to previous page after authentication in node.js using passport.js
body: <p>I'm trying to establish a login mechanism using node.js, express and passport.js. The Login itself works quite nice, also sessions are stored nicely with redis but I do have some troubles with redirecting the user to where he started from before being prompted to authenticate.</p>
  
  <p>e.g. User follows link <code>http://localhost:3000/hidden</code> is then redirected to <code>http://localhost:3000/login</code> but then I want him to be redirected again back to <code>http://localhost:3000/hidden</code>.</p>
  
  <p>The purpose of this is, if the user access randomly a page he needs to be logged in first, he shall be redirected to the /login site providing his credentials and then being redirected back to the site he previously tried to access.</p>
  
  <p>Here is my login post</p>
  
  <pre><code>app.post('/login', function (req, res, next) {
      passport.authenticate('local', function (err, user, info) {
          if (err) {
              return next(err)
          } else if (!user) { 
              console.log('message: ' + info.message);
              return res.redirect('/login') 
          } else {
              req.logIn(user, function (err) {
                  if (err) {
                      return next(err);
                  }
                  return next(); // &lt;-? Is this line right?
              });
          }
      })(req, res, next);
  });
  </code></pre>
  
  <p>and here my ensureAuthenticated Method</p>
  
  <pre><code>function ensureAuthenticated (req, res, next) {
    if (req.isAuthenticated()) { 
        return next();
    }
    res.redirect('/login');
  }
  </code></pre>
  
  <p>which hooks into the <code>/hidden</code> page</p>
  
  <pre><code>app.get('/hidden', ensureAuthenticated, function(req, res){
      res.render('hidden', { title: 'hidden page' });
  });
  </code></pre>
  
  <p>The html output for the login site is quite simple</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;form method="post" action="/login"&gt;
  
    &lt;div id="username"&gt;
      &lt;label&gt;Username:&lt;/label&gt;
      &lt;input type="text" value="bob" name="username"&gt;
    &lt;/div&gt;
  
    &lt;div id="password"&gt;
      &lt;label&gt;Password:&lt;/label&gt;
      &lt;input type="password" value="secret" name="password"&gt;
    &lt;/div&gt;
  
    &lt;div id="info"&gt;&lt;/div&gt;
      &lt;div id="submit"&gt;
      &lt;input type="submit" value="submit"&gt;
    &lt;/div&gt;
  
  &lt;/form&gt;
  </code></pre>