title: PassportJS + NodeJS: Does not redirect after success or fail gives 404 page
body: <p>I'm trying to implement PassportJS local, facebook, twitter &amp; google authentication + saving to online mongolab mongodb database. Registering or log in work fine, as well as saving to the database. As soon as it's a succes it should redirect to /profile page, if it fails it should go back to the /login page or /register page. Neither work, they both give me 404 error page. </p>
  
  <p>The file that it should redirect to ( /profile ) is accessable &amp; works fine. It just won't redirect succes or even when failed.</p>
  
  <p>Any help would be great.</p>
  
  <h1>Passport.js</h1>
  
  <pre><code>// load all the things we need
  var LocalStrategy = require('passport-local').Strategy;
  var FacebookStrategy = require('passport-facebook').Strategy;
  var TwitterStrategy  = require('passport-twitter').Strategy;
  var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
  
  // load up the user model
  var User = require('../data/schema/user');
  
  // load the auth variables
  var configAuth = require('./auth');
  
  module.exports = function(passport) {
  
  
      // used to serialize the user for the session
      passport.serializeUser(function(user, done) {
          done(null, user.id);
      });
  
      // used to deserialize the user
      passport.deserializeUser(function (user, done) {
          User.findById(id, function (err, user) {
              done(null, user);
          });
      });
  
      // =========================================================================
      // LOCAL LOGIN =============================================================
      // =========================================================================
      // we are using named strategies since we have one for login and one for signup
      // by default, if there was no name, it would just be called 'local'
  
      passport.use('login', new LocalStrategy({
              // by default, local strategy uses username and password, we will override with email
              usernameField : 'email',
              passwordField : 'password'
              //passReqToCallback : true // allows us to pass back the entire request to the callback
          },
          function (req, email, password, done)
          {
              // callback with email and password from our form
              process.nextTick(function(){
  
                  // find a user whose email is the same as the forms email
                  // we are checking to see if the user trying to login already exists
                  User.findOne({ 'local.email' : email }, function (err, user) {
                      // if there are any errors, return the error before anything else
                      if (err)
                          return done(err);
  
                      // if no user is found, return the message
                      if (!user)
                          return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
  
                      // if the user is found but the password is wrong
                      if (!user.validPassword(password))
                          return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
  
                      // all is well, return successful user
                      return done(null, user);
                  });
  
              });
  
  
          }));
  
      // =========================================================================
      // LOCAL SIGNUP ============================================================
      // =========================================================================
      // we are using named strategies since we have one for login and one for signup
      // by default, if there was no name, it would just be called 'local'
  
      passport.use('signUp', new LocalStrategy({
              // by default, local strategy uses username and password, we will override with email
              usernameField : 'email',
              passwordField : 'password',
              passReqToCallback : true // allows us to pass back the entire request to the callback
          },
          function(req, email, password, done) {
  
              // asynchronous
              // User.findOne wont fire unless data is sent back
  
              process.nextTick(function() {
  
                  // find a user whose email is the same as the forms email
                  // we are checking to see if the user trying to login already exists
                  User.findOne({ 'local.email' :  email }, function(err, user) {
                      // if there are any errors, return the error
                      if (err)
                          return done(err);
  
                      // check to see if theres already a user with that email
                      if (user) {
                          return done(null);
                      } else {
  
                          // if there is no user with that email
                          // create the user
                          var newUser            = new User();
  
                          // set the user's local credentials
                          newUser.local.email    = email;
                          newUser.local.password = newUser.generateHash(password);
  
                          // save the user
                          newUser.save(function(err) {
                              if (err)
                                  throw err;
                              return done(null, newUser);
                          });
  
                      }
  
                  });
  
              });
  
          }));
  
  
  
      // =========================================================================
      // FACEBOOK ================================================================
      // =========================================================================
      passport.use('facebook',new FacebookStrategy({
  
              // pull in our app id and secret from our authSchema.js file
              clientID        : configAuth.facebookAuth.clientID,
              clientSecret    : configAuth.facebookAuth.clientSecret,
              callbackURL     : configAuth.facebookAuth.callbackURL
  
          },
  
          // facebook will send back the token and profile
          function(token, refreshToken, profile, done) {
  
              // asynchronous
              process.nextTick(function() {
  
                  // find the user in the database based on their facebook id
                  User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
  
                      // if there is an error, stop everything and return that
                      // ie an error connecting to the database
                      if (err)
                          return done(err);
  
                      // if the user is found, then log them in
                      if (user) {
                          return done(null, user); // user found, return that user
                      } else {
                          // if there is no user found with that facebook id, create them
                          var newUser            = new User();
  
                          // set all of the facebook information in our user model
                          newUser.facebook.id    = profile.id; // set the users facebook id
                          newUser.facebook.token = token; // we will save the token that facebook provides to the user
                          newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                          newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first
  
                          // save our user to the database
                          newUser.save(function(err) {
                              if (err)
                                  throw err;
  
                              // if successful, return the new user
                              return done(null, newUser);
                          });
                      }
  
                  });
              });
  
          }));
  
      // =========================================================================
      // TWITTER =================================================================
      // =========================================================================
      passport.use('twitte',new TwitterStrategy({
  
              consumerKey     : configAuth.twitterAuth.consumerKey,
              consumerSecret  : configAuth.twitterAuth.consumerSecret,
              callbackURL     : configAuth.twitterAuth.callbackURL
  
          },
          function(token, tokenSecret, profile, done) {
  
              // make the code asynchronous
              // User.findOne won't fire until we have all our data back from Twitter
              process.nextTick(function() {
  
                  User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
  
                      // if there is an error, stop everything and return that
                      // ie an error connecting to the database
                      if (err)
                          return done(err);
  
                      // if the user is found then log them in
                      if (user) {
                          return done(null, user); // user found, return that user
                      } else {
                          // if there is no user, create them
                          var newUser                 = new User();
  
                          // set all of the user data that we need
                          newUser.twitter.id          = profile.id;
                          newUser.twitter.token       = token;
                          newUser.twitter.username    = profile.username;
                          newUser.twitter.displayName = profile.displayName;
  
                          // save our user into the database
                          newUser.save(function(err) {
                              if (err)
                                  throw err;
                              return done(null, newUser);
                          });
                      }
                  });
  
              });
  
          }));
  
      // =========================================================================
      // GOOGLE ==================================================================
      // =========================================================================
      passport.use('google',new GoogleStrategy({
  
              clientID        : configAuth.googleAuth.clientID,
              clientSecret    : configAuth.googleAuth.clientSecret,
              callbackURL     : configAuth.googleAuth.callbackURL
  
          },
          function(token, refreshToken, profile, done) {
  
              // make the code asynchronous
              // User.findOne won't fire until we have all our data back from Google
              process.nextTick(function() {
  
                  // try to find the user based on their google id
                  User.findOne({ 'google.id' : profile.id }, function(err, user) {
                      if (err)
                          return done(err);
  
                      if (user) {
                          // if a user is found, log them in
                          return done(null, user);
                      } else {
                          // if the user isnt in our database, create a new user
                          var newUser          = new User();
  
                          // set all of the relevant information
                          newUser.google.id    = profile.id;
                          newUser.google.token = token;
                          newUser.google.name  = profile.displayName;
                          newUser.google.email = profile.emails[0].value; // pull the first email
  
                          // save the user
                          newUser.save(function(err) {
                              // if successful, return the new user
                              if (err) throw err;
                              return done(null, newUser);
                          });
                      }
                  });
              });
  
          }));
  
  };
  </code></pre>
  
  <h1>Route.js</h1>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var passport = require('passport');
  
  var Events = require('../data/schema/events.js');
  
  
      // =====================================
      // HOME PAGE (with login links) ========
      // =====================================
      router.get('/', function(req, res) {
          res.render('landing');
      });
  
      // =====================================
      // EVENTS PAGE =========================
      // =====================================
      router.get('/events', function(req, res) {
          res.render('events');
      });
  
      // =====================================
      // GROUPS PAGE =========================
      // =====================================
      router.get('/groups', function(req, res) {
          res.render('groups');
      });
  
      // =====================================
      // PROFILE SECTION =====================
      // =====================================
      // we will want this protected so you have to be logged in to visit
      // we will use route middleware to verify this (the isLoggedIn function)
      router.get('/profile',isLoggedIn, function (req , res) {
          res.render('profile.jade',{ title: 'Profile', user: req.user});
      });
  
      // =====================================
      // LOGIN ===============================
      // =====================================
      // show the login form
      router.get('/login', function(req, res) {
          res.render('login');
      });
  
      // process the login form
      router.post('/login', passport.authenticate('login', {
          successRedirect : 'profile', // redirect to the secure profile section
          failureRedirect : 'login' // redirect back to the signup page if there is an error
      }));
  
      //router.post('/login', function(req, res, next) {
      //    passport.authenticate('local', function(err, user, info) {
      //        if (err) { return next(err); }
      //        // if user is not found due to wrong username or password
      //        if (!user) {
      //            return res.render('login', {
      //                //you can send a message to your view
      //                message: 'Invalid username or password'
      //            });
      //        }
      //        //passport.js has a logIn user method
      //        req.logIn(user, function(err) {
      //            if (err) { return next(err); }
      //
      //            return res.redirect('/');
      //        });
      //    })(req, res, next);
      //});
  
      // =====================================
      // FORGOTPW ============================
      // =====================================
      // show the login form
      router.get('/forgotpw', function(req, res) {
          res.render('forgotpw');
      });
  
      // process the signup form
      router.post('/forgotpw', passport.authenticate('signup', {
          successRedirect : '/profile', // redirect to the secure profile section
          failureRedirect : '/forgotpw' // redirect back to the signup page if there is an error
      }));
  
      // =====================================
      // SIGNUP ==============================
      // =====================================
      // show the signup form
      router.get('/register', function (req, res) {
          res.render('register');
      });
  
  
      // process the signup form
      router.post('/register', passport.authenticate('signUp', {
          successRedirect : '/profile', // redirect to the secure profile section
          failureRedirect : '/register' // redirect back to the signup page if there is an error
      }));
  
      // =====================================
      // LOGOUT ==============================
      // =====================================
  
      router.get('/logout', function(req, res){
          req.logout();
          res.redirect('/');
      });
  
      // =====================================
      // 404 =================================
      // =====================================
  
      router.get('/400',function(req,res){
          res.render('404');
      });
  
      // =====================================
      // 500 =================================
      // =====================================
  
      router.get('/500',function(req,res){
          res.render('500');
      });
  
  // =============================================================================
  // AUTHENTICATE (FIRST LOGIN) ==================================================
  // =============================================================================
  
    // =====================================
    // FACEBOOK ROUTES =====================
    // =====================================
    // route for facebook authentication and login
      router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
  
    // handle the callback after facebook has authenticated the user
      router.get('/auth/facebook/callback',
        passport.authenticate('facebook', {
          successRedirect : '/profile',
          failureRedirect : '/login',
            failureFlash: true
        }));
  
    // =====================================
    // TWITTER ROUTES ======================
    // =====================================
    // route for twitter authentication and login
      router.get('/auth/twitter', passport.authenticate('twitter'));
  
    // handle the callback after twitter has authenticated the user
      router.get('/auth/twitter/callback', passport.authenticate('twitter', {
          successRedirect : '/profile',
          failureRedirect : '/login',
          failureFlash: true
        }));
  
  
    // =====================================
    // GOOGLE ROUTES =======================
    // =====================================
    // send to google to do the authentication
    // profile gets us their basic information including their name
    // email gets their emails
      router.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
  
    // the callback after google has authenticated the user
      router.get('/auth/google/callback',
        passport.authenticate('google', {
          successRedirect : '/profile',
          failureRedirect : '/login',
            failureFlash: true
        }));
  
      // =====================================
      // API EVENTS ROUTES ===================
      // =====================================
  
      router.get('/api/events', function (req, res) {
          Events.find(function (err, events) {
              if (err)
                  res.send(err);
              res.json(events);
          });
      });
  
  
  // route middleware to ensure user is logged in
  function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
      return next();
  
    res.redirect('/');
  }
  
  module.exports = router;
  </code></pre>
  
  <h1>Login.html</h1>
  
  <pre><code>&lt;div class="container-fluid"&gt;
          &lt;div class="row-fluid"&gt;
              &lt;div class="form-body"&gt;
                  &lt;div class="col-md-4  col-md-offset-4"&gt;
                        &lt;h2&gt;Sign in with &lt;/h2&gt;
                        &lt;div class="row"&gt;
                            &lt;div class="col-sm-4"&gt;&lt;a href="/auth/facebook" class="button btn-social facebook span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/span&gt;Facebook&lt;/a&gt;&lt;/div&gt;
                            &lt;div class="col-sm-4"&gt;&lt;a href="/auth/twitter" class="button btn-social twitter span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-twitter"&gt;&lt;/i&gt;&lt;/span&gt;Twitter&lt;/a&gt;&lt;/div&gt;
                            &lt;div class="col-sm-4"&gt;&lt;a href="/auth/google" class="button btn-social googleplus span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-google-plus"&gt;&lt;/i&gt;&lt;/span&gt;Google+&lt;/a&gt;&lt;/div&gt;
                        &lt;/div&gt;
                      &lt;div class="section-divider"&gt;&lt;span&gt;OR&lt;/span&gt;&lt;/div&gt;
                      &lt;form class="loginForm" action="login.html" method="POST"&gt;
                          &lt;div class="form-group"&gt;
                              &lt;label&gt;Email address&lt;/label&gt;
                              &lt;input type="email" class="form-control input-lg" placeholder=" Email Address " required&gt;
                          &lt;/div&gt;
                          &lt;div class="form-group"&gt;
                              &lt;label&gt;Password&lt;/label&gt;
                              &lt;input type="password" class="form-control input-lg"  placeholder=" Password" required&gt;
                          &lt;/div&gt;
                          &lt;div class="checkbox"&gt;&lt;label&gt;&lt;input type="checkbox"&gt; Remember Me&lt;/label&gt;&lt;/div&gt;
                          &lt;div class="login-buttons"&gt;&lt;button type="submit" class="btn btn-success btn-block btn-lg"&gt;Sign me in&lt;/button&gt;&lt;/div&gt;
                          &lt;div class="m-t-20"&gt;
                              &lt;a class="add-info" href="forgotpw.html"&gt;Forgot your Password ?&lt;/a&gt; | &lt;a class="add-info" href="register.html"&gt; Sign Up&lt;/a&gt; | &lt;a class="add-info" href="landing.html"&gt;Home&lt;/a&gt;
                          &lt;/div&gt;
                      &lt;/form&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  
  <h1>Register.html</h1>
  
  <pre><code>&lt;div class="container-fluid"&gt;
          &lt;div class="row-fluid"&gt;
              &lt;div class="form-body"&gt;
                  &lt;div class="col-md-4  col-md-offset-4" ng-controller="valController"&gt;
                          &lt;h2&gt;Sign Up with&lt;/h2&gt;
                          &lt;div class="row"&gt;
                              &lt;div class="col-sm-4"&gt;&lt;a href="#" class="button btn-social facebook span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/span&gt;Facebook&lt;/a&gt;&lt;/div&gt;
                              &lt;div class="col-sm-4"&gt;&lt;a href="#" class="button btn-social twitter span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-twitter"&gt;&lt;/i&gt;&lt;/span&gt;Twitter&lt;/a&gt;&lt;/div&gt;
                              &lt;div class="col-sm-4"&gt;&lt;a href="#" class="button btn-social googleplus span-left btn-block"&gt;&lt;span&gt;&lt;i class="fa fa-google-plus"&gt;&lt;/i&gt;&lt;/span&gt;Google+&lt;/a&gt;&lt;/div&gt;
                          &lt;/div&gt;
                          &lt;div class="section-divider"&gt;&lt;span&gt;OR&lt;/span&gt;&lt;/div&gt;
                          &lt;form name="registerForm" novalidate class="ng-pristine ng-valid-email ng-invalid ng-invalid-required ng-valid-pattern ng-valid-validator"&gt;
                              &lt;div class="form-group"&gt;
                                  &lt;label class="control-label"&gt;Name&lt;/label&gt;
                                  &lt;div class="row"&gt;
                                      &lt;div class="col-md-6"&gt;&lt;input type="text" name="firstName" class="form-control input-lg" placeholder=" First name"&gt;&lt;/div&gt;
                                      &lt;div class="col-md-6"&gt;&lt;input type="text" name="lastName" class="form-control input-lg" placeholder=" Last name"&gt;&lt;/div&gt;
                                  &lt;/div&gt;
                              &lt;/div&gt;
                              &lt;div class="form-group"&gt;
                                  &lt;label&gt;Email&lt;/label&gt;
                                  &lt;input type="email" name="email" placeholder="mail@example.com" required  class="form-control input-lg"&gt;
                              &lt;/div&gt;
                              &lt;div class="form-group"&gt;
                                  &lt;label class="control-label"&gt; Password&lt;/label&gt;
                                  &lt;input type="password" name="password" class="form-control input-lg" placeholder=" Password"&gt;
                              &lt;/div&gt;
                              &lt;div class="form-group"&gt;
                                  &lt;label class="control-label"&gt;Re-enter Password&lt;/label&gt;
                                  &lt;input type="password" name="password" class="form-control input-lg" placeholder=" Re-enter password"&gt;
                              &lt;/div&gt;
  
                              &lt;button type="submit" class="btn btn-block btn-lg"&gt;Sign me Up&lt;/button&gt;
                              &lt;div class="m-t-20"&gt;&lt;a class="add-info" href="landing.html"&gt;Home&lt;/a&gt; | &lt;a class="add-info" href="login.html"&gt;Back to Sign In&lt;/a&gt;&lt;/div&gt;
                          &lt;/form&gt;
  
                      &lt;p&gt;By clicking Sign Up, you agree to our Terms and that you have read our Cookie Use.&lt;/p&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  
  <h1>EDIT</h1>
  
  <p>Some screenshots with morgan logger from node: 
  <a href="http://i.stack.imgur.com/8kVxx.png" rel="nofollow">Login with local strategy</a>
  <a href="http://i.stack.imgur.com/rqN85.png" rel="nofollow">login with google strategy</a></p>