[Fixed] Error: failed to serialize user into session. Wrong function passed to serializeUser()?


I’m trying to do my first steps with the Express framework for Node. I was trying to implement a tiny authentication example, using Passport. However, I can’t make it work; I keep getting the error: Error: failed to serialize user into session.

I installed node-inspector to try to see what’s going on. Apparently, my serialization function is being called, and it executes done(null, 0) as expected. I tried taking a look at Passport code, but I couldn’t understand what the problem is. This is pretty much my first attempt at a Node application so I’m not familiar with the code. Can someone give me a hint? Thanks.

var express = require('express');
var jade = require('jade');

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var app = express();

 * Settings

    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    app.use(express.session({ secret: 'cat in the bag' }));

    passport.use(new LocalStrategy(
        function(username, password, done) {
            done(null, { id: 0, username: 'juancito' });

    passport.serializeUser(function(user, done) {
        done(null, user.id);

    passport.deserializeUser(function(id, done) {
        done(null, 'juancito');

 * Routes

app.get('/', function(req, res) {
    res.render('index', { title: 'Welcome!' });

app.get('/login', function(req, res) {
    if (req.user)
        return res.redirect('/');

    res.render('login', { title: 'Log in' });

    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login'

app.get('/logout', function(req, res) {

console.log('Listening on port 3000.');


The issue is that 0 is a false-y value in JavaScript, so Passport thinks you haven’t serialized your user.

done(null, 0)  // don't serialize users to a 0 number

I’d recommend starting user IDs at 1 (which happens in SQL databases), or (if you really need integers beginning at 0) serialize them as strings to the session.

done(null, 0.toString())

Leave a Reply

(*) Required, Your email will not be published