'req.isAuthenticated() returns true only after passport.authenticate. Any other route will return false value

here's my registration route:

(I use passport-local-mongoose)

router.post("/register", (req,res)=>{
    console.log(req.body);
    User.register({
            username: req.body.username,
            mail: req.body.email
        }, req.body.password, (err, user)=>{
            err ? console.log(err) : passport.authenticate("local")(req, res, () => {
                console.log(user.username + " registered and logged in.");
                // console.log(user);
                res.send(req.isAuthenticated());
                console.log(req.user);

              })

        })
    
});

After user get created and authenticated, everything is fine. I have req.user object, I have isAuthenticated as true (I tried to log it with interval of 1 sec - always returns true). But, if I try to check if user is authenticated, from some different route, for example:

router.get("/getUser", (req, res)=>{
  res.send(req.user);
  console.log(req.isAuthenticated());
})

I immediately get false in the console and undefined from req.user. Any ideas? Looks like the problem is - any request to the server after authentication just removes req.user



Sources

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

Source: Stack Overflow

Solution Source