I'm using an express app with passport.js and express-sessions to authenticate users and store their data in a PostgreSQL database. Everything works as expected in development but after I publish it on Heroku, when I clear site data via the browser or even log out of an account, the session and cookie won't be reset upon redirection to the login page and the app won't work anymore.
This is how I'm setting express-session (I'm using Connect PG Simple as store):
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 604800,
secure: isProduction ? true : false,
sameSite: isProduction ? "none" : "lax",
},
store: new pgSession({
pool: db,
createTableIfMissing: true,
}),
})
);
Here is my logout logic which will destroy the session and clear the cookie (It does set a new cookie after redirection in my development environment):
// Logout
usersRouter.post("/logout", checkNotAuthenticated, (req, res) => {
req.logout();
req.session.destroy((err) => {
if (err) throw err;
res.clearCookie("connect.sid");
res.redirect("/users/login");
});
});
Now all of the problem is occurring on Heroku but I managed to find two ways to fix it:
app.set("trust proxy", 1);Am I missing something here? Why does enabling a "trust proxy" fix this issue?