Reputation: 13
In my React + Node.js app, when a user is logged in, they can interact with the website, visit various pages, and everything works well - as long as the user stays on the same tab. Once opening a new tab (there are links on the website designed to open in a new tab), the user is redirected to the public home page, as if they are not logged in. Based on debugging, the redirection is done by a middleware, which is called on every authenticated route:
function checkLoggedIn(req, res, next) {
if (req.session && req.session.username) {
next();
} else {
res.redirect("/");
}
}
The issue is with req.session, that is not preserved when opening a new tab. I tried to log the req.sessionID, and it seems that the id is preserved when viewing other pages and doing various actions, but when opening a new tab - a new sessionID is set, and then when the user is redirected to the public home page, the original sessionID is printed again.
I should mention that in localhost this works fine. However, in production - it doesn't.
For sessions I use express-session.
Opening the new tab is done on the frontend using the following function:
const visitPage = (username) => {
window.open(`/details/${username}`, "_blank", "noopener,noreferrer");
};
Relevant code from app.js:
const port = process.env.PORT || 8000;
app.use(
cors({
origin: `${process.env.REACT_APP_URL}`,
credentials: true, // Allow (cookies) to be sent
})
);
/* ... route requires ... */
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
secure: true,
sameSite: "None",
maxAge: 1000 * 60 * 60,
},
})
);
/* ... routes ... */
I'd appreciate any advice regarding getting the new tab to preserve the session, and keep the user in the logged in area of the website.
Thanks in advance
Upvotes: 0
Views: 14