Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Passport logs the user in but fails while saving it to the session

ErrorError: Failed to serialize user into session

Short 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.

  • Applies to Passport, express-session, Express 5, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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);
    });
  2. 2Match what you see, then jump to its fix

    1. 1The 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. 2The 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

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_modules

2Fix

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

Did this fix it?

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

Did this fix it?

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

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.