'Error: Failed to serialize user into session || This error is coming while I am trying to log in

I got a problem with the Passport.js module and Express.js. This is my code and I just want to use a hardcoded login for the first try. I always get the message: I searched a lot and found some posts in stackoverflow but I didnt get the failure.

Code of my app.js

require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const mongoose = require('mongoose')
const session = require('express-session')
const passport = require('passport')
const passportLocalMongoose = require('passport-local-mongoose')



const app = express();
const port = process.env.PORT

app.use(express.static('public'))
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended:true}))

app.use(session({
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: false,
}))

app.use(passport.initialize())
app.use(passport.session())



mongoose.connect("mongodb://localhost:27017/userDB")

const userSchema = new mongoose.Schema({
    username: String,
    password: String,
})
userSchema.plugin(passportLocalMongoose)


const User = new mongoose.model("User",userSchema)

passport.use(User.createStrategy())

passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())

//Home Route
app.get('/',(req,res)=>{
    res.render('home')
})



//Login Route
app.route('/login')
.get((req,res)=>{
    res.render('login')
})
.post((req,res)=>{

    const user = new User({
        username: req.body.username,
        password: req.body.password
      });
    
      req.login(user, function(err){
        if (err) {
          console.log(err);
        } else {
          passport.authenticate("local")(req, res, function(){
            res.redirect("/secrets");
          });
        }
      });


})


//Register route

app.route('/register')
.get((req,res)=>{
    res.render('register')
})
.post((req,res)=>{

    User.register({username: req.body.username}, req.body.password,(err,user)=>{
        if(err){
            console.log(err);
            res.redirect('/register')
        }
        else{
            passport.authenticate("local")(req,res,()=>{
                res.redirect("/secrets")
            })
        }
    })
      
})


app.route('/secrets')
.get((req,res)=>{
    res.set('Cache-Control', 'no-store');
    if(req.isAuthenticated()){
        res.render("secrets")
    }
    else{
        res.redirect("/login")
    }
})


app.listen(port,()=>console.log("server started at port "+port))

But its giving this error:

Error: Failed to serialize user into session
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:278:19)        
    at serialized (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:283:7)   
    at D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport-local-mongoose\index.js:212:7
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:291:9)
    at Authenticator.serializeUser (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:296:5)
    at SessionManager.logIn (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\sessionmanager.js:14:8)

This problem is occuring only in case of login. register is working fine.



Solution 1:[1]

This error means passport is not able to hash (serialize) your users. Try to implement your own User.serializeUser() function using the user's _id.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ysb