Search code examples
javascriptexpressoauth-2.0passport.jsexpress-session

req.session.returnTo is undefined


I am using using passport to authenticate my users using discord oauth2. I want them to be redirected back to the same page they came from instead of to the home page or a dashboard.

I tried storing the URL in the session like described here, but it doesn't persist to the next request.

Middleware for my pages that need authentication:

module.exports = (req, res, next) => {
  if (req.user) {
    next();
  }
  else {
    req.session.returnTo = req.originalUrl;
    res.redirect('/auth');
  }
};

Auth route:

router.get("/auth", passport.authenticate("discord"));

router.get("/auth/redirect", passport.authenticate("discord", {
  failureRedirect: "/auth/forbidden"
}), (req, res) => {
  console.log(req.session); // doesnt have returnTo inside anymore ?
  res.redirect(req.session.returnTo || '/');
  delete req.session.returnTo;
});

The console.log shows the user successfully authenticated, but the returnTo field is no longer there.


Solution

  • Hi I ran into the same problem. Try adding keepSessionInfo: true to passport.authenticate.

    router.get("/auth", passport.authenticate("discord", {
        failureRedirect: "/auth/forbidden", keepSessionInfo: true
    }), (req, res) => {
        console.log(req.session); // doesnt have returnTo inside anymore ?
        res.redirect(req.session.returnTo || '/');
        delete req.session.returnTo;
    });