'req.isAuthenticated() is always returning false even when user is authenticated

I am creating an application with node.js, express.js, passport.js, ejs and MongoDB.

here is my code:

app.post('/login', function(req, res){
  const user = new User({
    username: req.body.email,
    fname: req.body.fname,
    lname: req.body.lname,
    password: req.body.password
  })
  req.login(user, function(err){
  if(err){
    console.log(err)
    res.redirect('/signup')
  }
  else{
    passport.authenticate('local', function(error, user, info){
      req.session.save(function(){
        res.redirect('/secretPage');
      })
    })(req, res)
  }
})
})

app.get('/secretPage', function(req, res){
  if(req.isAuthenticated()){
    res.render('page')
    console.log('user authenticated');
  }
  else{
    res.redirect('/login')
    console.log('user not authenticated');
  }
  console.log(req.isAuthenticated());
})

here is my express-session setup:

const session = require('express-session')

app.use(session({
  secret: process.env.ENCRYPTION_KEY,
  resave: false,
  saveUninitalized: false,
}));

For some reason, even though the user gets successfully authenticated on the /login route, when the user is redirected to /secretPage req.isAuthenticated() is still false. Please help solve this problem.



Sources

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

Source: Stack Overflow

Solution Source