I've been working on a node project for a while and have implemented passport too handle authentication. As with a lot of people I'm confused by the "serializeUser" and "deserializeUser" function that passport uses, from what I have understood these functions are used to store the user id in the session (req.session.passport) and then using that id to fetch the whole object from the database when needed. What I don't understand is why you can't just store the entire object in the session to begin with?
I read a tutorial where these functions where implemented as followed:
passport.serializeUser(function(user, done){
done(null, user);
});
passport.deserializeUser(function(user, done){
done(null, user);
});
After trying it out I found no problems with this method however as so many other people didn't store their entire object but instead only the id I switched to the same approach and now the code looks like this:
passport.serializeUser(function(user, done){
done(null, user.accountID);
});
passport.deserializeUser(function(id, done){
connection.query("SELECT * FROM accounts WHERE accountID = ?", [id], function (err, rows){
done(err, rows[0]);
});
});
This also works but now I wonder, what did I gain by doing things like this? Is storing only the ID more efficient because it seems uneccesary to access the database everytime I need to access my user object. Any clarification is much appreciated :)
After doing some more digging I found this comment left by Max Truxa on Understanding passport serialize deserialize which answered my question. I'll leave it here if anyone else is interested.
You could put the whole user object into the session data, but that is usually not a good idea because it can have other side effects. For example, when the user updates his/her username you have to update the session data too, otherwise you'll get tickets because of "the broken rename feature". That's a relatively harmless example. Same could happen with permission bits or equal sensitive data (Oops...). Essentially the same problems you always run into if you have duplicate data. TL;DR - Don't do it. – Max Truxa Aug 22 '16 at 18:30