JAVASCRIPT
Configure Secure Session Cookies with HttpOnly, Secure, and SameSite
Learn to configure secure session cookies in an Express.js application by setting HttpOnly, Secure, and SameSite attributes to enhance protection against XSS and CSRF attacks.
// Install express and express-session: npm install express express-session
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: process.env.SESSION_SECRET || 'a-very-secret-key-that-should-be-in-env', // Should be a strong, random string from environment variables
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: process.env.NODE_ENV === 'production', // Ensures cookie is sent only over HTTPS in production
maxAge: 1000 * 60 * 60 * 24, // 1 day in milliseconds
sameSite: 'Lax', // Protects against CSRF attacks. 'Strict' is more secure, 'None' requires 'Secure'.
}
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Views: ${req.session.views}`);
} else {
req.session.views = 1;
res.send('Welcome, first visit!');
}
});
// app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This code configures `express-session` with crucial security settings for session cookies. `httpOnly: true` prevents client-side scripts from accessing the cookie, mitigating XSS risks. `secure: true` ensures the cookie is only sent over HTTPS, protecting against interception. `sameSite: 'Lax'` helps prevent Cross-Site Request Forgery (CSRF) by restricting when the browser sends the cookie with cross-site requests. The `secret` should be a long, random, and securely stored value from environment variables.