I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard.
Even though I tried saving the URL in the session as mentioned here, it seems that the information is not retained for the next request.
This is the middleware for pages requiring authentication:
module.exports = (req, res, next) => {
if (req.user) {
next();
}
else {
req.session.returnTo = req.originalUrl;
res.redirect('/auth');
}
};
Authentication route:
router.get("/auth", passport.authenticate("discord"));
router.get("/auth/redirect", passport.authenticate("discord", {
failureRedirect: "/auth/forbidden"
}), (req, res) => {
console.log(req.session); // why is returnTo no longer present?
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
});
The console log confirms successful authentication, but the returnTo field is missing.