Why does accessing the session object make Express-Session work?

My sessions suddenly stopped being saved, and cookies stopped being set. All routes were working, and Postman was also not receiving cookies (so I ruled out cors). I discovered that accessing the session object immediately after the middleware fixed the issue. So this code was all that was needed:
app.use((req, res, next) => {
req.session.init = "init";
next();
});
app.use((req, res, next) => {
req.session.init = "init";
next();
});
in app.js. Remove this and again, no sessions are saved and no cookies set.
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);

const app = express();

const options = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
};

const sessionStore = new MySQLStore(options);

app.use(session({
name: process.env.SESSION_NAME,
secret: process.env.SESSION_SECRETS,
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
sameSite: 'strict',
maxAge:600000
}
}));
app.use((req, res, next) => {
req.session.init = "init";
next();
});

require('./startup/headers')(app);
require('./startup/routes')(app);

app.use((error, req, res, next) => {

const status = error.statusCode || 500;

res.status(status).json({ message: `Error`});
});

module.exports = app;
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);

const app = express();

const options = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
};

const sessionStore = new MySQLStore(options);

app.use(session({
name: process.env.SESSION_NAME,
secret: process.env.SESSION_SECRETS,
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
sameSite: 'strict',
maxAge:600000
}
}));
app.use((req, res, next) => {
req.session.init = "init";
next();
});

require('./startup/headers')(app);
require('./startup/routes')(app);

app.use((error, req, res, next) => {

const status = error.statusCode || 500;

res.status(status).json({ message: `Error`});
});

module.exports = app;
I can't see anything in the docs saying that the session object needs to be accessed? Does anyone know what's going on here?
1 Reply
JWode
JWode2y ago
Ugh... It's because saveUninitialized and resave are false. I thought they applied to current sessions, but unless you alter a new session that session is also never saved