6

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?

Community
  • 1
  • 1
  • This question is very very very old.. anyone finding it now should research JWT and ditch session data. JWT bypasses this whole concept and all its issues. –  Feb 07 '22 at 11:46

1 Answers1

0

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.

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
  • ~1ms... OK. Coming from an SQL background I am naturally trying to limit the db calls. But thanks for the tip –  Jul 07 '15 at 20:19
  • I have a page that loads 40 images and each of those image is a GET request mapped a route. So the user is serialized (Mongoose) lookup 40 times for each page view. Separating the routes would be the way forward but, I wonder if passport.session could have be configured in such a way to apply only to those routes that need authentication rather than to all requests that are handled by a route file. – Raf Dec 15 '15 at 00:07
  • You can use express static for those and move express static above passport middleware. This will solve your problem. https://www.airpair.com/express/posts/expressjs-and-passportjs-sessions-deep-dive – Suraj Jain Aug 15 '18 at 21:47
  • This question is very very very old.. anyone finding it now should research JWT and ditch session data. JWT bypasses this whole concept and all its issues. –  Feb 07 '22 at 11:46