Setup I run two docker containers locally. One express backend and one next.js frontend. My database is on a remote server.
Backend snippet:
const corsOptions = {
origin: '*',
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.static("public"));
app.use(express.json()); // lets us interpret(parse) post requests and returns an Object
app.use(express.urlencoded({ extended: true }));
// import (own) database config
const database = require("./database");
// session middleware
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const sessionStore = new MySQLStore({}, database);
sessionStore.all(function(error, sessions) {
console.log('all sessions:', sessions);
});
// setting up session middleware
app.use(session({
secret: 'asdasdcads',
createDatabaseTable: true,
store: sessionStore,
resave: false,
saveUninitialized: false,
expiration: 600000,
cookie: {
sameSite: 'lax',
domain: 'localhost'
},
secure: false
}));
When I open the site in localhost:80 (docker container mapped 80:3000), the sessions get created with IDs and when saveUninitialized is set to true the sessions are even stored in my db. The last step, setting the cookie in the browser fails. Instead, if I refresh the site, a new session is created. I guess the session middleware is not adding a Set-Cookie to the response but I really wonder why and how I can look into it more deeply. I asked chatGPT and added a bunch of stuff to the cookie and session config to make it work, like you can see, but no success. ChatGPT also recommended to set cors after session but later reverted that.