Stateless JWT Authentication with Passport.js: Skip Sessions and SerializeUser
Learn how to configure Passport.js for stateless JWT authentication by disabling sessions and skipping serializeUser/deserializeUser, with a working example and security considerations.
15 Nov 2025, 07:35 UTC

Problem: sessions interfere with JWT stateless auth
Passport expects serializeUser and deserializeUser to manage a session cookie. When you add the JWT strategy those callbacks still run unless you disable sessions, causing Passport to create a cookie even though you only want token validation.
Configure passport‑jwt for stateless use
Disable sessions, extract the token from the Authorization header, and supply your secret. With passport‑jwt v4+ you must use explicit extraction.
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
clockTolerance: 5
};
passport.use(new JwtStrategy(opts, async (payload, done) => {
try {
const user = await findUserById(payload.sub);
if (!user) return done(null, false);
return done(null, user);
} catch (err) {
return done(err, false);
}
}));
// No serializeUser/deserializeUser needed
Worked example: protecting a route
Register the strategy then protect endpoints with session:false.
app.get('/api/profile',
passport.authenticate('jwt', { session: false }),
(req, res) => res.json({ id: req.user.id, email: req.user.email })
);
Test with a valid Bearer token; no Set‑Cookie header should appear.
Trade‑off: token revocation
Stateless JWT scales well but tokens stay valid until expiry. Mitigate with short lifetimes and a refresh‑token rotation or deny list.
Actionable closing
Turn off sessions, skip serializeUser/deserializeUser, use explicit header extraction, and protect routes with session:false. Verify by checking that responses lack a Set‑Cookie header.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.