← Back to Node.js, page 9

nodejs-0162 · Medium mid

How does Passport work with express-session: strategies, serializeUser and deserializeUser, and logout?

Passport is authentication middleware with pluggable strategies. A strategy (for example passport-local) checks credentials and calls done(null, user). With sessions, serializeUser stores a small identifier in the session at login and deserializeUser loads the full user from that identifier on later requests, which sets req.user. Protect routes by checking req.isAuthenticated(), and call req.logout with a callback to end the session.

Full answer

Passport separates three things

  • Strategies: how to verify a login (local username and password, OAuth providers such as Google, JWT, and many more).
  • Session support: after a successful login, remember the user for later requests.
  • Your routes: what to do with req.user.

Flow with passport-local

  1. app.use(session(...)), app.use(passport.initialize()), app.use(passport.session()). Order matters: session first.
  2. The strategy function receives (username, password, done). Look up the user, compare the password hash in constant time, then done(null, user) on success, done(null, false) on failure, and done(err) on a server error.
  3. passport.authenticate('local') on the login route runs the strategy. On success, Passport calls req.login, which runs serializeUser(user, done). Store only the id: done(null, user.id).
  4. On every later request, passport.session() reads the id from the session and calls deserializeUser(id, done), which loads the user and sets req.user. A failed lookup (user deleted) should clear the login.
  5. Logout: req.logout((err) => ...) in Passport 0.6 and later (it is asynchronous because it regenerates the session).

Security notes

  • Passport 0.6 and later regenerates the session id at login, which prevents session fixation.
  • Use HttpOnly, Secure and SameSite cookies, a production session store (Redis), and CSRF protection for cookie sessions.
  • Do not store the whole user object in the session. It becomes stale and large.
  • For APIs consumed by other services prefer token strategies; for plain apps, sessions are fine.
javascript
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const { Strategy: LocalStrategy } = require('passport-local');
const crypto = require('node:crypto');

const hash = (password) => crypto.scryptSync(password, 'demo-salt', 32);
const users = [{ id: 1, name: 'asha', passwordHash: hash('s3cret-pass') }];

passport.use(new LocalStrategy((username, password, done) => {
  const user = users.find((u) => u.name === username);
  if (!user || !crypto.timingSafeEqual(user.passwordHash, hash(password))) return done(null, false);
  done(null, user);
}));
passport.serializeUser((user, done) => done(null, user.id));                              // store only the id
passport.deserializeUser((id, done) => done(null, users.find((u) => u.id === id) || false));

const app = express();
app.use(express.json());
app.use(session({ secret: 'demo-secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

app.post('/login', passport.authenticate('local'), (req, res) => res.json({ user: req.user.name }));
app.get('/me', (req, res) => (req.isAuthenticated() ? res.json({ user: req.user.name }) : res.status(401).json({ error: 'not logged in' })));
app.post('/logout', (req, res, next) => req.logout((err) => (err ? next(err) : res.json({ ok: true }))));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const send = (path, { cookie, body, method = 'GET' } = {}) => fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(cookie && { cookie }) }, body: body && JSON.stringify(body) });

  console.log('/me before login          :', (await send('/me')).status);
  console.log('login, wrong password     :', (await send('/login', { method: 'POST', body: { username: 'asha', password: 'nope' } })).status);
  const ok = await send('/login', { method: 'POST', body: { username: 'asha', password: 's3cret-pass' } });
  const cookie = ok.headers.get('set-cookie').split(';')[0];
  console.log('login, right password     :', ok.status, JSON.stringify(await ok.json()));
  console.log('/me with the cookie       :', (await send('/me', { cookie })).status);
  console.log('logout                    :', (await send('/logout', { cookie, method: 'POST' })).status);
  console.log('/me after logout          :', (await send('/me', { cookie })).status);
  server.close();
});

A local strategy with a scrypt hash, a session cookie and a logout. The cookie is kept by hand because Node's fetch has no cookie jar. Install first with npm install express express-session passport passport-local (run here with express 5.3.0, express-session 1.19.0, passport 0.7.0, passport-local 1.0.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): /me before login : 401 login, wrong password : 401 login, right password : 200 {"user":"asha"} /me with the cookie : 200 logout : 200 /me after logout : 401

Key points

  • Strategies verify credentials; sessions remember the user.
  • serializeUser stores an id, deserializeUser loads the user into req.user.
  • Session middleware must come before passport.session().
  • req.logout takes a callback in current Passport versions.
  • Passport regenerates the session at login.

Common mistakes

  • Putting passport.session() before the session middleware.
  • Storing the whole user in the session.
  • Comparing password hashes with ===.
  • Using req.logout() without a callback in new versions.
  • Skipping CSRF protection for cookie sessions.

Follow-ups

  • What does deserializeUser run on, and how often?
  • How would you add Google login with the same app?
  • How do you share sessions across several instances?

Tips

  • Explain strategy, serialize, deserialize.
  • Say that order matters.
  • Mention session fixation protection.