With Passport in an Express app, what do serializeUser and deserializeUser each do, and when does each one run?
answer
- one hook writes, one hook reads
- login time versus every request
- where the stored value lives
- what false from the reader means
basics
~10 sserializeUser runs once at login and picks what Passport stores in the session, usually the user id at req.session.passport.user; deserializeUser runs on each request through passport.session() and turns that value back into req.user.
solid answer
~40 s`serializeUser` runs inside `req.login()`, so once per login: Passport regenerates the session, calls my serializer, stores what it passes to `done` at `req.session.passport.user` and saves. `deserializeUser` runs on every request that goes through `passport.session()` and finds that value; it loads the user and sets `req.user`. If it calls `done(null, false)` because the account is gone, Passport removes the login data and the request continues anonymously; `done(err)` goes to error middleware. I store just the id, so role changes and disabled accounts take effect on the next request, at the cost of one lookup per request. Authenticating with `{ session: false }` itself calls neither hook.
code
javascript · 15 linesconst passport = require('passport');
async function findUserById(id) {
// look the user up in your data layer; resolve undefined when absent
}
// Runs once per login, inside req.login(): store only the id
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Runs on every request that passes through passport.session()
passport.deserializeUser((id, done) => {
findUserById(id).then((user) => done(null, user || false), done);
});go deeper
Recall that one hook stores a value at login and the other rebuilds req.user from it on later requests, and that the stored value is normally the user id.
Explain where the value lives, req.session.passport.user, when each hook runs, and what done(null, false) and done(err) do in the deserializer.
Discuss the per-request lookup cost, stale data when whole objects are stored, deleted accounts, and what happens when the user lookup itself is down.
Weigh freshness against load: an id plus a lookup makes revocation immediate, a cached or embedded user is cheaper but delays it, and the team should choose that deliberately.
## Two hooks, two moments Passport keeps a user signed in across requests by storing something in the **session** (the server-side record that express-session loads for each request from its cookie) and turning it back into a user later. The two halves are functions the application supplies: - `passport.serializeUser(fn)` decides **what to store** when a user logs in. - `passport.deserializeUser(fn)` decides **how to rebuild** the user from that value on later requests. Authenticating with `{ session: false }`, as a bearer-token API route does, calls neither hook; the deserializer still runs on such a route only if `passport.session()` also sits in front of it. ## The login side: serializeUser `serializeUser` runs inside `req.login()`, which `passport.authenticate()` calls after a strategy succeeds unless the route passed `session: false`. In Passport 0.7, `req.login()` with sessions on: 1. regenerates the session, giving it a new id and dropping the pre-login contents unless `keepSessionInfo: true` is passed, 2. calls your serializer with the user, 3. stores whatever the serializer passes to `done` at `req.session.passport.user`, 4. saves the session, then calls the login callback. So the serializer runs **once per login**, not once per request. A typical one is `done(null, user.id)`. ## The request side: deserializeUser `passport.session()` is middleware that runs Passport's built-in `'session'` strategy. On every request that passes through it: - If `req.session.passport.user` holds a value, Passport calls your deserializer with that value. - `done(null, user)` sets `req.user`, and `req.isAuthenticated()` returns `true`. - `done(null, false)` or `done(null, null)` means the stored user no longer exists: Passport deletes `req.session.passport.user` and the request continues **unauthenticated**. - `done(err)` forwards the error to error middleware, so an outage of the user lookup turns every signed-in page into a 500. - If the session holds no login data, Passport calls `next()` without running the deserializer. The `'session'` strategy never responds 401 on its own. A route that requires a user must check `req.isAuthenticated()` or `req.user` itself. And `passport.session()` needs session middleware ahead of it: without `req.session` it fails with ``Login sessions require session support. Did you forget to use `express-session` middleware?``. ## What to store | Stored value | Session size | Freshness of roles and status | Cost per request | |---|---|---|---| | The user id | Small and fixed | Reloaded on every request | One lookup in the deserializer | | The whole user object | Grows with the object | Stale until the next login | No lookup | Storing the id is the usual default because a role change or a disabled account takes effect on the user's very next request. Caching inside the deserializer is the lever when that lookup becomes expensive. The general question of what belongs in a session at all, as opposed to being re-derived per request, is covered with framework session state. ## Details that come up in interviews - **Chains of hooks.** Each call to `serializeUser` or `deserializeUser` adds a function to a chain, and Passport tries them in order until one produces a value. Calling `done('pass')` hands over to the next function in the chain. - **Access to the request.** A hook declared with three parameters receives `(req, user, done)` or `(req, id, done)`, which helps when the lookup depends on the host or tenant. - **Missing hooks.** If no serializer produces a value, login fails with `Failed to serialize user into session`. If no deserializer produces an answer for a request carrying login data, that request fails with `Failed to deserialize user out of session`. - **Callback style.** Both hooks report through `done`. An `async` function that returns the user without ever calling `done` leaves the request hanging. ## Debugging a sign-in that does not stick When users sign in successfully but appear anonymous on the next page, walk the two hooks in order: 1. Check that the sign-in response sets the session cookie and that the browser sends it back. 2. Inspect the stored session record: after a real login it holds a `passport` object with a `user` value. If it does not, the serializer never ran, typically because the route passed `session: false` or used a custom callback without calling `req.login()`. 3. Confirm that `passport.session()` runs on the failing route, after the session middleware. 4. Confirm that the deserializer calls `done(null, user)` for that stored value, and not `done(null, false)` because of an id type mismatch such as a number stored and a string looked up.
- An account is deleted while its owner is still signed in; what happens on that browser's next request?`passport.session()` finds the old id and calls the deserializer, which finds no user and calls `done(null, false)`. Passport deletes `req.session.passport.user` and calls `next()` with no `req.user`, so the request is anonymous. Nothing responds 401 automatically; routes that require a user redirect or refuse because `req.isAuthenticated()` is now false.
- Why does a serializer sometimes take three parameters?Passport checks the function's declared parameter count. With three it calls `(req, user, done)` instead of `(user, done)`, and the same applies to `deserializeUser` with `(req, id, done)`. That gives the hook the request, for example to pick a tenant's user table from the host name.
- Does deserializeUser run on a route guarded by passport.authenticate('jwt', { session: false })?Not because of that guard: the JWT strategy never touches the session. It runs only if `passport.session()` also sits earlier in that request's middleware chain and the session holds login data, which is one reason to mount session support only on the routes that use it.
A hotel key card that holds only a room number: the desk writes it once at check-in, and every door reader looks up the current booking from that number, so a cancelled booking stops opening doors at once.
- serializeUser runs on every request to write the user back into the session.
- deserializeUser runs once at login and its result is cached for the session.
- Storing the whole user object in the session is the recommended default.
- When deserializeUser finds no user, Passport answers 401 automatically.
- passport.session() rejects a request whose session holds no login data.