'Get access to req.user outside of google auth routes

I am using passportjs google auth to login users and right now I am trying to get access to req.user in another route instead of my google auth route.

The reason why i want access to req.user is because I am trying to figure out who is currently logged as the current user in another route, lets call the other route userRoute.js.
I know I can get access to req.user inside:

router.get("/login/success", (req, res) => {
  if (req.user) {
    res.status(200).json({ success: true, message: "success", user: req.user });
  }
});

however, I need access to req.user in another route. How can I achieve this?

my google auth route


//Google auth routes
router.get(
  "/google",
  passport.authenticate("google", { scope: [`profile`, `email`] })
);

router.get(
  "/google/callback",
  passport.authenticate("google", {
    successRedirect:
      environment === "development"
        ? "http://localhost:3000"
        : "https://asdasdasd.heroku.com",
    failureRedirect: "/login/failed",
    session: true,
  })
);

router.get("/login/success", (req, res) => {
  if (req.user) {
    res.status(200).json({ success: true, message: "success", user: req.user });
  }
});

router.get("/login/failed", (req, res) => {
  res.send("login failed");
});

router.get("/logout", (req, res) => {
  req.logout();
  res.redirect(
    environment === "development"
      ? "http://localhost:3000"
      : "https://asdasdasd.herokuapp.com"
  );
});


Solution 1:[1]

Passport doesn't provide the session management, you will need to store the user login success in a session management system like express-session or a jwt.

Typical workflow for express-session

  1. On login, after passport, store the user id in req.session.userId
  2. On any other route until the cookie is expired, access the user Id via req.session.userId

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 Musinux