JAVASCRIPT
Configure Secure Session Management in Node.js Express
Set up robust and secure session management in Node.js Express applications, leveraging `express-session` with essential HttpOnly, Secure, and SameSite cookie flags.
const express = require('express');
const session = require('express-session');
const helmet = require('helmet'); // Recommended for general security headers
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = 3000;
// Apply Helmet for general security headers (not directly part of session, but good practice)
app.use(helmet());
// Configure express-session with secure options
app.use(session({
secret: process.env.SESSION_SECRET || 'a_fallback_secret_for_dev_only', // Use a strong, environment-specific secret key
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Ensure cookies are only sent over HTTPS in production
maxAge: 24 * 60 * 60 * 1000, // 24 hours (in milliseconds)
sameSite: 'lax', // Protects against some CSRF attacks; 'strict' for stronger protection
},
name: 'my_app_session_id' // Customize session cookie name to avoid default 'connect.sid'
}));
// Middleware to add user data to session (example)
app.get('/login', (req, res) => {
// In a real app, this would involve authenticating the user
req.session.user = { id: 1, username: 'testuser' };
req.session.isAuthenticated = true;
res.send('Logged in! Session created.');
});
// Middleware to check if user is authenticated
app.get('/dashboard', (req, res) => {
if (req.session.isAuthenticated) {
res.send(`Welcome to the dashboard, ${req.session.user.username}!`);
} else {
res.status(401).send('Unauthorized. Please log in.');
}
});
app.get('/', (req, res) => {
res.send(`Homepage. Session ID: ${req.session.id || 'Not set'}`);
});
// Example: Accessing a route without logging in
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.redirect('/dashboard');
}
res.clearCookie('my_app_session_id'); // Clear the session cookie
res.send('Logged out!');
});
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log('Try visiting /login, then /dashboard. Then /logout.');
});
/*
To test 'secure: true' locally without actual HTTPS, you can use:
app.set('trust proxy', 1);
// And set secure: true in session config.
// This tells express-session that it is behind a proxy that handles SSL/TLS.
// For production, ensure your server is actually running over HTTPS.
*/
How it works: This snippet demonstrates secure session management in a Node.js Express application using the `express-session` middleware. Key security practices include using a strong, environment-specific `secret` for session signing, and configuring `cookie` options: `httpOnly: true` prevents client-side JavaScript access, `secure: true` ensures cookies are only sent over HTTPS (critical in production), `maxAge` limits session duration, and `sameSite: 'lax'` (or `'strict'`) mitigates CSRF attacks by controlling when cookies are sent with cross-site requests. Customizing the `name` avoids default session cookie names that might be targeted by attackers.