JAVASCRIPT
Configure Secure and HttpOnly Cookies in Express
Enhance session security by setting `HttpOnly`, `Secure`, and `SameSite` flags on cookies in Express.js, protecting against XSS attacks and CSRF.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session'); // npm install express-session
const app = express();
app.use(cookieParser());
// Configure session middleware with secure options
app.use(session({
secret: process.env.SESSION_SECRET || 'a-very-secret-key-that-should-be-in-env', // MUST be a strong, random string
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something stored
name: 'sessionID', // Custom name for the session cookie
cookie: {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Send cookie only over HTTPS in production
maxAge: 3600000, // Session expiration time in milliseconds (1 hour)
sameSite: 'Lax', // Protects against CSRF attacks. Options: 'Strict', 'Lax', 'None'
}
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`You visited this page ${req.session.views} times.`);
} else {
req.session.views = 1;
res.send('Welcome to the session demo! Refresh to see the count.');
}
});
app.get('/set-custom-cookie', (req, res) => {
res.cookie('mySecureCookie', 'someValue', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 600000, // 10 minutes
sameSite: 'Strict'
});
res.send('Custom secure cookie set!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
How it works: This snippet demonstrates how to configure cookies with essential security flags (`HttpOnly`, `Secure`, and `SameSite`) in an Express.js application, both for session cookies and custom cookies. `HttpOnly` prevents client-side JavaScript access, mitigating XSS risks. `Secure` ensures cookies are only sent over HTTPS. `SameSite` protects against CSRF by controlling when cookies are sent with cross-site requests. These settings are crucial for robust web security.