Passport logs the user in but fails while saving it to the session
Error: Failed to serialize user into sessionShort answer
After a successful login Passport asks your serializeUser functions what to store in the session. This error appears when none is registered, or when every one calls back with an empty value. Register passport.serializeUser, and make it return a real identifier such as the user's id.
Fix it fast
1Find out which cause you have
Check that serializeUser is registered before the first request, and print what it receives and what it hands back.
passport.serializeUser((user, done) => { console.log('serializing', user); done(null, user.id); });2Match what you see, then jump to its fix
- 1
The log line from the first step never prints, because the function does not exist or its file is never loadedNo serializeUser function is registeredFix - 2
The log shows the user object, then the error comes anyway; user.id, or whatever you return, is undefinedThe serializer calls back with an empty valueFix
- 1
What does the error look like?
Error: Failed to serialize user into session
Cause 1 of 2
No serializeUser function is registered
1Check
Passport walks the list of registered serializers. With an empty list, it reports the error straight away. A serializer defined in a file that is never required counts as not registered.
grep -rn "serializeUser\|deserializeUser" --include=*.js . | grep -v node_modules2Fix
Register both functions once, at start-up, before routes: serializeUser decides what goes into the session, deserializeUser turns it back into req.user. Add session support first.
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
app.use(passport.session());
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
try {
done(null, await User.findById(id));
} catch (err) {
done(err);
}
});3Verify
Log in again. The request completes, and a following request has req.user.
app.get('/me', (req, res) => res.json(req.user ?? null));Confirmed by passportjs.org
Cause 2 of 2
The serializer calls back with an empty value
1Check
Passport accepts the first serializer result that is truthy (0 is also accepted). A serializer that returns undefined, null or an empty string counts as passing, and with no serializer left the error is raised. With MongoDB the key is often _id, so user.id can be missing on plain objects.
console.log(Object.keys(user), user.id, user._id);2Fix
Return a value that exists on that object, and convert it to a string when it is an ObjectId.
passport.serializeUser((user, done) => {
done(null, String(user._id ?? user.id));
});3Verify
Log in again. The id is stored and deserializeUser receives it.
passport.deserializeUser((id, done) => { console.log('id from session', id); done(null, { id }); });Confirmed by raw.githubusercontent.com
How do I stop it coming back?
- Keep Passport setup in one file that the app always loads, so the serializers cannot be skipped.
- Store only the user id in the session and load the full user in deserializeUser.
- Add a login test that follows the redirect and then reads a protected route.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Passport logs the user in but req.isAuthenticated() returns false on the next request
req.user is undefined on the next request
req.isAuthenticated() only checks that req.user is set.
4 causes, each with a fixBack end
req.session is undefined in an Express route
TypeError: Cannot set properties of undefined (setting 'user')
express-session only attaches req.session when its middleware runs first and can reach its store.
3 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fix