Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js - Error: failed to serialize user into session

It looks like you didn't implement passport.serializeUser and passport.deserializeUser. Try adding this:

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

If you decide not to use sessions, you could set the session to false

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

Sounds like you missed a part of the passportjs setup, specifically these two methods:

passport.serializeUser(function(user, done) {
    done(null, user._id);
    // if you use Model.id as your idAttribute maybe you'd want
    // done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

I added the bit about ._id vs. .id but this snippet is from the Configure Section of docs, give that another read and good luck :)


Here an working but still lazy way to use sessions and still "serialisize" the values.

var user_cache = {};

passport.serializeUser(function(user, next) {
  let id = user._id;
  user_cache[id] = user;
  next(null, id);
});

passport.deserializeUser(function(id, next) {
  next(null, user_cache[id]);
});

in case or weird errors just ask yourself: "Do I rlly set '_id' in my user object?" - in most cases you dont. So use a proper attribute as key.


Make sure you have used async and await when getting user data.

passport.serializeUser((user, done) => {
   done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
  const USER = await User.findById(id);
  done(null, USER);
});

passport.use(
  new GoogleStrategy(
    {
      // options for google strategy
      clientID: keys.google.clientID,
      clientSecret: keys.google.clientSecret,
      callbackURL: "/auth/google/redirect",
    },
    async (accessToken, refreshToken, profile, done) => {
      //   passport callback function

      //   check if user already exist in our db
      const oldUser = await User.findOne({ googleId: profile.id });
      if (oldUser) {
        return done(null, oldUser);
      } else {
        const newUser = await new User({
          username: profile.displayName,
          googleId: profile.id,
        }).save();
        return done(null, newUser);
      }
    }
  )
);