5
votes

Understanding passport serialize deserialize

In cobbling together my first node app from an array of guides and SO posts i have now stumbled across the serialize and deserialize passport functions...

I kind of understand their functionality.. but something doesn't seem right.

http://toon.io/understanding-passportjs-authentication-flow/:

passport.deserializeUser is invoked on every request by passport.session. 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.

This means that every single request runs a db request to retrieve the user object? My app definitely does not require a db request to aquire the full userobject on every single request.. in fact i cannot think of an app that would require this..

Thus, if i only register a serialize function and not a deserialize function.. is this the best practice to stop passport assigning the entire user object/mongo doc to session whilst at the same time reducing the db read count per page/api request?

1

1 Answers

0
votes

passport.session is the middleware that actually calls deserialize function, so the better strategy would be to strategically place that middleware where you want:

app.get('/', ...);
app.use(passport.session());
app.get('/user', ...)

That way you can choose which routes the user object will be loaded or not.

But generally the practice is indeed that the user object is restored from database upon each request. The cost is virtually nothing (~1ms) so I wouldn't really worry about it.