wesbos
wesbos

Reputation: 26317

Passport JS "Can't set headers after they are sent"

Getting this error when I successfully log in with passport JS. Trying to redirect to the home page once I log in.

Code that does it:

app.post('/login', 
  passport.authenticate('local', {failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Full Error:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:644:11)

Am I missing something? Not sure why this error is happening. I'm still able to use the app, I just dont want the error.

Upvotes: 11

Views: 12083

Answers (2)

tozlu
tozlu

Reputation: 4865

You are redirecting the user so serializeUser function is being called twice. And in

 passport.use(new FacebookStrategy({
 ...

be sure to add this else or it gets called twice, thus sending the headers twice and causing error. Try this:

passport.use(new FacebookStrategy({
...
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {

  // To keep the example simple, the user's Facebook profile is returned to
  // represent the logged-in user.  In a typical application, you would want
  // to associate the Facebook account with a user record in your database,
  // and return that user instead.
    User.findByFacebookId({facebookId: profile.id}, function(err, user) {
        if (err) { return done(err); }
        if (!user) {
            //create user User.create...
            return done(null, createdUser);
        } else { //add this else
            return done(null, user);
        }
    });
  });
 }
));

Upvotes: 20

user1207456
user1207456

Reputation:

According to the PassportJS guide, you're supposed to let their middleware do all of the redirects.

app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                failureRedirect: '/login' }));

My guess is that the middleware is calling Express' res.redirect method just like you are in your example above, but has an error in its implementation (calling next when it shouldn't) and then your method is trying to call res.redirect again, and that causes the error to be thrown because you can only send a response to the client once in the HTTP protocol.

Upvotes: 4

Related Questions