Passport.js failing to serialize user Passport.js failing to serialize user express express

Passport.js failing to serialize user


First you must understand what serialize and deserialize are meant for.

1) serializeUser take a user object and store any information you want in the session, when you return done(null, user), as per your first question.

2) deserializeUser take the information stored in the session (sent by cookieSession in every request) and checks if the session is still valid for a user, and if(!err) done(null,user) is true, keeps the user in the session, where else done(err,null) removes it from the session, redirecting you to whatever your app.get('/auth/:provider/callback') sends the user to after checking if the session is timed out or not. This should clarify things for your second question.


I still do not understand why the problem came about but I have solved it by doing the following.

Changing

  app.use(express.cookieSession({ secret: 'tobo!', cookie: { maxAge: new Date(Date.now() +     3600000), }}));

to

app.use(express.cookieSession({ secret: 'tobo!', maxAge: 360*5 }));

I think that serializing the entire user object should work since deserializeUser will just pass back the passed cookie. But by not serializing the entire user object it is working.

passport.serializeUser(function(user, done) {    console.log('serializeUser: ' + user._id)    done(null, user._id);});passport.deserializeUser(function(id, done) {    db.users.findById(id, function(err, user){        console.log(user)        if(!err) done(null, user);        else done(err, null)      })});

I have had zero issues since I did this.


//app.use(session(...)) must comes before app.user(passport.session())//other wise items will not be save or serialize to sessionapp.use(  session({    secret: process.env.SESSION_SECRET,    resave: false,    saveUninitialized: false,  }));app.use(passport.session());