how server-side sessions work in Express
express-session setup, session store mechanics, session ID cookie, req.session object, session middleware configuration, secret signing of session ID
Server-Side Sessions in Express
Server-side sessions store user data on the server and give the client an opaque ID. The client proves identity by presenting that ID — the server does the lookup.
const session = require('express-session');
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24 hours in ms
}
}));After this middleware runs, req.session is available in all routes. It persists automatically between requests for the same session ID.
// Login
app.post('/login', async (req, res) => {
const user = await findUserByEmail(req.body.email);
const valid = await bcrypt.compare(req.body.password, user.hash);
if (!valid) return res.status(401).json({ error: 'Bad credentials' });
req.session.userId = user.id;
req.session.role = user.role;
res.json({ success: true });
});Key config options: resave: false prevents unnecessary writes if the session was not modified. saveUninitialized: false does not create a session until something is stored — required for GDPR compliance and efficient resource use. The session secret signs the session ID cookie to prevent forgery; it is not used to encrypt session data.
