What exactly does serialization and depreciation do in passport and expression sessions?

I only have the most vague idea of ​​what sessions do, and the official documentation doesn't help much as it assumes that I know what sessions are and therefore also know why users should be serialized and deserialized.

Here's what I think I know: The session is like a note placed on the server refrigerator that says, "The custom bean is awesome. Let it be." Every time a new request comes from bob, the server checks the post-it node and says, "Yes, Bob is still cool."

So serialization writes a post-it note, and deserialization takes it. Here's what I don't understand: how does this code write the post-it node, what should I do?

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


And how does the following code discard the post-it message? findByID accesses the array where I store my users. Why does it need to be received if the "post-it-note" is just thrown away?

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


What exactly is the flow here?

The rest of the code for these examples is here


source to share

1 answer

You're halfway there with the refrigerator analogy. Sessions do resemble a sticky note, but you write what you want from them. Serialization is part of writing and deserialization is part of reading.

So your user is logged in. You don't want to store all of your information in the session because it is already in your database. But in subsequent queries, you want to remember who he is. So, all you need to write down on your post is its ID, say 1234. By calling upon completion, you tell the passport that this is what you want to stock in the session.

On a subsequent call, the passport returns your message and says, "Okay, I know this guy, his ID is 1234". findById is the method you call to retrieve all of its information, like its name. When you call here, you say "ok, here's information about this user. His name is Bob."

If you are wondering why you are calling and not just returning a value, it is because both your serialization and deserialization can be asynchronous. If you need more information on asynchronous code, I highly recommend editing Node correctly , as this is the core concept of Node.js.

Hope it helps.



All Articles