JAVASCRIPT
Implement Secure Session Management in Node.js Express
Set up secure server-side session management in Node.js Express using 'express-session', ensuring proper configuration for secrets, cookie security (httpOnly, secure, sameSite), session storage, and fixation prevention.
const express = require('express');
const session = require('express-session');
const RedisStore = require('connect-redis').default; // Example using Redis for session store
const { createClient } = require('redis');
const app = express();
// Initialize redis client
let redisClient = createClient();
redisClient.connect().catch(console.error);
// Initialize store. Requires redisClient to be connected first.
let redisStore = new RedisStore({
client: redisClient,
prefix: "myapp:",
});
app.use(session({
store: redisStore, // Use a production-ready session store (e.g., Redis, MongoDB)
secret: process.env.SESSION_SECRET || 'aVeryStrongSecretKeyThatShouldBeAtLeast32CharactersLong',
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: {
httpOnly: true, // Prevent client-side JS from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Send cookie only over HTTPS in production
maxAge: 24 * 60 * 60 * 1000, // 24 hours (in milliseconds)
sameSite: 'Lax', // Protect against CSRF attacks, 'Strict' or 'Lax' are good choices
}
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Views: ${req.session.views}. Session ID: ${req.sessionID}`);
} else {
req.session.views = 1;
res.send('Welcome, first visit!');
}
});
app.get('/login', (req, res) => {
// Simulate successful login
req.session.userId = 'user123';
req.session.isAdmin = true;
req.session.lastActivity = Date.now();
// Regenerate session ID after login to prevent session fixation attacks
req.session.regenerate(err => {
if (err) return res.status(500).send('Session regeneration failed');
res.send('Logged in and session regenerated!');
});
});
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) return res.status(500).send('Failed to destroy session');
res.send('Logged out!');
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement secure server-side session management in a Node.js Express application using the `express-session` middleware. It emphasizes critical security configurations: using a strong `secret` for signing session IDs, employing a production-ready session store (like Redis), and configuring secure cookie options (`httpOnly`, `secure`, `maxAge`, `sameSite`). It also includes `saveUninitialized: false` and `resave: false` for efficiency and security, and shows how to regenerate the session ID after authentication to prevent session fixation attacks.