Garmaine Staff asked 2 years ago

I have been stuck on this problem now for several days. From what I can conclude after leaving the backend port:5000 and redirecting to port:3000 (my frontend's homepage) the authentication session stops.

What I am doing: clicking a sign in to google button, login with good account, redirect to my front end homepage where a fetch request runs and gets the logged in user profile information.

I am running a sign in with google oAuth with passport.js. Mongoose saves the session and user profile info. req.isAuthenticated() should equal true on all routes until logged out. instead Everything works until the very last point where I res.redirect to the front end home page.

  passport.authenticate("google", { scope: ["profile", "email"] })

  passport.authenticate("google", { failureRedirect: "/new" }),
  (req, res) => {
    console.log(` Authentication Status: ${req.isAuthenticated()}`); // READS AS TRUE
    console.log(` User? : ${req.user}`); /// SHOWS USER INFO
    console.log("end of user status before redirect.");


On the last function from what I can tell everything works as it is supposed to right up until the res.redirect. unless I put in the command req.logout() It should be able to keep track of my session and on the backend req.isAuthenticated should equal true. Instead in other routes where I have conditionals setup req.isAuthenticated is reading false.

// quick fetch request I run on front end to show user as logged in and profile info.
app.get("/getuser", (req, res) => {
  console.log("user CHECK :", req.user); // READS UNDEFINED HERE
  console.log(`is authenticated:`, req.isAuthenticated()); // READS FALSE HERE
  if (req.isAuthenticated()) {
    const user = req.user;
    console.log("user:", req.user);
    res.json({ user: user, isAuthenticated: true });
  } else {
    const user = false;
    console.log("user:", req.user);
    res.json({ user: false, isAuthenticated: false });

It gets stranger…

My browser receives the connect.sid cookie and my database saves the user and session.

from chrome browser cookies on localhost: from chrome browser cookies on localhost

screenshot of saved account created from session in my database screenshot of saved account created from session in my database

I have been stuck on this problem for more than three days and have checked quite a few stack threads already on this. All of them did not seem to help me. Any help would be greatly appreciated. Thank you so much in advance and I will do my best to explain anything confusing.