Freelance JavaScript developer

On passport.js, specific use cases

In the previous post, I talked about the authentication flow and the flow for subsequent requests using passportjs. This post will cover some specific use cases.

What user information to store in the session and what not?

It's best to keep the session information small and only attach user information you actually need (note: some user info should be kept - like for instance the user ID, otherwise passport cannot use its Session Strategy).

However, if you use the deserializeUser method to go and load the user from the db based on the user ID attached to the session, it's better to store the entire user object in the session. This will prevent a roundtrip to the database on every request just to fetch user information.

How to split up passportjs configuration between multiple files?

In the example, all password configuration and Local Strategy definition was specified in the main app.js file.

The passport instance we get back from require('passport') is a singleton. So we can just configure express to use the passport middleware in app.js while configuring passport in another file. They all need to require('passport').

There's no need to pass the password instance around.

What if my form elements are named email and password instead of username and password?

Configure which values passport should use from the request body by the options object passed while configuring the Local Strategy.