0

In most of the examples on passportjs, it is recommended that the look up to the application user store be made a the deserializUser method, like:

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

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

I traced and found that the deserializeUser method is called on every page, whereas serializeUser is called only once after authentication.

Wouldn't it be more efficient to query the database at serializeUser and pass whatever details required as an object, and then deserializeUser can pass it along to req.user?

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Old Geezer
  • 14,854
  • 31
  • 111
  • 198

1 Answers1

0

The serializeUser and deserializeUser are used to create a mapping between the actual user object and whatever is on the user's session.

So, when the user logs in, you need to create a session for it, so the user object would be passed to serializeUser, it decides what to store in the session so it can retrieve the user back later. In your case, it just uses the id of the user.

After that, for each request, first the id of the user would be retrieved from session, then using deserializeUser function, it would get transformed to the actual user object to be stored in req.user.

You can also write your serialization functions in a way doesn't need DB queries. For example you can serialize the whole user object into the session:

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

passport.deserializeUser(function (user, done) {
    done(err, JSON.parse(user));
});

But remember, if anything in the user object changes after he logs in, it would not be reflected on the req.user.

The DB query overhead for serialization function is usually nothing compared to the actual application logic. I'd suggest use what you already have. It's less likely it causes any performance issues.

I have the same thing in couple of in production projects and never ran into any issues.

Also read: Understanding passport serialize deserialize.

Community
  • 1
  • 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52