I put my node express server into production. In development, express-session worked fine (it stored session into cookies with MemoryStore). But now it creates a new session ID into MongoStore every time I refresh or make a request. Also, it doesn't create a cookie in the browser anymore (idk if it's a good or a bad thing)
Most StackOverflow queries on this topic tell me to do things that I've already done so no help there
Here is my express and session setup:
const app = express()
const apiPort = process.env.PORT || process.env.API_PORT
app.use(cors({credentials: true, origin: process.env.ORIGIN_URL}))
mongoose.connection.on('error', (err) => {
console.error(err);
console.log('MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
});
const sessionMiddleware = session({
resave: false,
saveUninitialized: false,
secret: process.env.SECRET,
// secure: true,
cookie: {
sameSite: true,
httpOnly: true,
secure: true,
maxAge: 1000 * 60 * 60 * 24 * 30
},
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI
})
})
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.post('/auth/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) { return next(err); }
if (info) {
return res.status(401).json({error: info.msg})
}
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.status(200).send(user);
});
})(req, res, next);
});
app.get('/auth/logout', (req, res) => {
req.logout()
res.sendStatus(200)
});
app.get('/checkToken', authCheck, (req, res) => {
res.status(200).send({accountType: res.accountType});
})
Additional info that might be handy for this problem: the front-end is on a separate domain, the aforementioned server is on Heroku, and the DB is in MongoDB cloud.
Turns out all I was missing was app.set('trust proxy', 1)
in my setup and sameSite: 'none'
in cookie: {}
in session middleware.