JAVASCRIPT
Secure Session Management with HTTP-Only and SameSite Cookies
Configure secure session cookies in Node.js/Express using `express-session` with `HttpOnly`, `Secure`, and `SameSite` attributes to protect against XSS and CSRF attacks targeting session tokens.
const express = require('express');
const session = require('express-session');
const helmet = require('helmet'); // For general security headers
const app = express();
// Use Helmet for basic security headers (optional, but recommended)
app.use(helmet());
app.use(session({
secret: process.env.SESSION_SECRET || 'a_very_strong_and_long_secret_key_that_is_at_least_32_characters_long_and_randomized',
name: 'sessionId',
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something stored
cookie: {
httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
maxAge: 24 * 60 * 60 * 1000, // 24 hours (in milliseconds)
sameSite: 'Lax', // Protect against CSRF attacks. Options: 'Lax', 'Strict', 'None'
}
}));
// Example route that uses session
// app.get('/login', (req, res) => {
// req.session.userId = 'user123';
// res.send('Logged in');
// });
// app.get('/profile', (req, res) => {
// if (req.session.userId) {
// res.send(`Welcome, user: ${req.session.userId}`);
// } else {
// res.status(401).send('Not authenticated');
// }
// });
// app.listen(3000, () => {
// console.log('Server running on port 3000');
// });
How it works: This snippet configures secure session management in an Express.js application using `express-session`. The key to secure cookies lies in their attributes:
* `secret`: A strong, long, randomized string used to sign the session ID cookie. It should be stored as an environment variable.
* `httpOnly: true`: Prevents client-side JavaScript from accessing the cookie, significantly mitigating the impact of XSS attacks by making it harder for attackers to steal session tokens.
* `secure: true`: Ensures the cookie is only sent over HTTPS connections. This prevents the session ID from being intercepted by attackers over unencrypted HTTP. It's conditionally set for production environments.
* `maxAge`: Sets an expiration time for the session, preventing indefinite sessions.
* `sameSite: 'Lax'`: Provides a significant defense against Cross-Site Request Forgery (CSRF) attacks by telling browsers when to send the cookie with cross-site requests. 'Lax' generally provides a good balance between security and user experience, while 'Strict' is even more secure but can disrupt legitimate cross-site links. 'None' requires `secure: true` and should be used cautiously.