'My auth app does not save data to session

Creating Auth application using express mongoose and passport js. after adding mail verification using nodemailer server sptoped adding user from req.user to res.locals.currentUser can be seen from middleware. before adding email verification it was functioning correctly.

    app.use(express.urlencoded({ extended: true }));
app.use(session(sessionObject));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));

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

app.use((req, res, next) => {
  res.locals.currentUser = req.user;
  res.locals.success = req.flash("success");
  res.locals.error = req.flash("error");
  next();
});
app.get("/", (req, res) => {
  console.log(res.locals);
  res.render("index");
});
app.get("/login", (req, res) => res.render("login"));
app.post(
  "/login",
  passport.authenticate("local", {
    failureFlash: true,
    failureRedirect: "/login",
  }),
  (req, res) => {
    req.flash("success", "Welcome Back!");
    res.redirect("/");
    console.log(req.user);
  }
);

source code



Solution 1:[1]

The problem was: I was working in a local environment and had set the session cookie to secure.

Since Localhost runs on HTTP and not HTTPS, the browser was not sending the session cookie to the Application after the App redirected, which prevented Passport from loading the session data and creating the req.user key.

Solution 2:[2]

Everything in req and res expires at the end of the request, only req.session is written to the session store (sessionObject) and from there carried over to the next request.

If you want to keep the current user in the session, write it to req.session.currentUser. Then you need passport.js and req.user only during the first request, where the session is established.

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 My wife made me join
Solution 2 Heiko Theißen