JAVASCRIPT
Configure Secure and HttpOnly Session Cookies in Node.js
Learn to configure web application session cookies with `HttpOnly`, `Secure`, and `SameSite` attributes to prevent XSS, CSRF, and man-in-the-middle attacks, enhancing session security.
const express = require('express');
const session = require('express-session');
const app = express();
const PORT = 3000;
// Configure express-session middleware
app.use(session({
secret: 'a_very_strong_and_long_secret_key_that_should_be_in_env_variable',
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't save new sessions that have no data
name: 'sessionId', // Custom name for the session ID cookie
cookie: {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
maxAge: 1000 * 60 * 60 * 24, // Cookie valid for 24 hours (in milliseconds)
sameSite: 'Lax', // Protects against CSRF attacks. Can be 'Strict', 'Lax', or 'None'
// 'Strict': Prevents cookie from being sent with cross-site requests.
// 'Lax': Sends cookie for top-level navigations and safe (GET) HTTP methods.
// 'None': Sends cookie with all cross-site requests but requires 'Secure' attribute.
}
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`You have visited this page ${req.session.views} times.`);
} else {
req.session.views = 1;
res.send('Welcome to the session demo! Visit again.');
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
How it works: This Node.js snippet demonstrates how to configure secure session cookies in an Express.js application using the `express-session` middleware. Key security attributes are set on the `cookie` object:
- `httpOnly: true`: Prevents client-side JavaScript from accessing the session cookie, mitigating XSS attacks.
- `secure: true`: Ensures the cookie is only sent over HTTPS, protecting against man-in-the-middle attacks (enabled based on `NODE_ENV`).
- `sameSite: 'Lax'` (or 'Strict'/'None'): Helps prevent Cross-Site Request Forgery (CSRF) attacks by controlling when the browser sends the cookie with cross-site requests.
- `maxAge`: Sets an expiration time for the session, limiting the window of opportunity for session hijacking. Always use a strong, unique `secret` key stored in an environment variable.