JAVASCRIPT
Setting Secure and HttpOnly Session Cookies in Express.js
Enhance web application security by configuring session cookies with `secure` and `httpOnly` flags in Express.js to prevent XSS and man-in-the-middle attacks.
const express = require('express');
const session = require('express-session');
const app = express();
const port = 3000;
app.use(session({
secret: 'a_highly_secure_and_long_random_string_for_signing_cookies', // Use a strong, secret string
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something stored
cookie: {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: true, // Ensures cookie is only sent over HTTPS
maxAge: 24 * 60 * 60 * 1000, // Cookie expiration in milliseconds (1 day)
sameSite: 'Lax', // Protects against CSRF attacks
}
}));
app.get('/login', (req, res) => {
// Simulate successful login
req.session.userId = 'user123';
req.session.username = 'exampleUser';
res.send('Logged in! Session created with secure cookie settings.');
});
app.get('/dashboard', (req, res) => {
if (req.session.userId) {
res.send(`Welcome to the dashboard, ${req.session.username}! Your session is secure.`);
} else {
res.status(401).send('Please log in.');
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}. Make sure to use HTTPS for 'secure' flag to work.`);
});
How it works: This Express.js snippet configures session cookies with critical security flags. The `httpOnly: true` flag prevents client-side JavaScript from accessing the cookie, mitigating certain Cross-Site Scripting (XSS) attacks. The `secure: true` flag ensures the cookie is only sent over HTTPS, protecting it from interception during man-in-the-middle attacks. `sameSite: 'Lax'` adds another layer of CSRF protection.