When is the serialize and deserialize passport method called? What does it exactly set? When is the serialize and deserialize passport method called? What does it exactly set? mongoose mongoose

When is the serialize and deserialize passport method called? What does it exactly set?


Serialization and deserialization are important concept. To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object.

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.

Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

In the code that you have written, only the user ID is serialized to the session. When subsequent requests are received, this ID is used to find the user, which will be restored to req.user.

In order to give developers freedom to user whichever database they want, whatever data they want to serialize, they can do it in their own way, the serialization and deserialization logic is left to us to implement.


serializeUser is the method that is called on the login request(during the authentication) and if login is successful then it decides what user information should get stored in the session and a cookie is sent to the browser for the same to maintain the session.

// Only during the authentication to specify what user information should be stored in the session.passport.serializeUser(function (user, done) {    console.log("Serializer : ", user)    done(null, user.id);});

The above snippet will save the user.id field to the session and cookie.

deserializeUser is the method that is called on all subsequent request and is called by the passport.session middleware. It enables us to load additional user information on every request. This user object is attached to the request as req.user making it accessible in our request handling.

Here is the article that explains it flow very well