JAVASCRIPT
Configure Secure and HttpOnly Cookies in Node.js Express
Enhance web application security by setting HttpOnly and Secure flags for cookies in Node.js Express, mitigating XSS risks and ensuring cookies are sent only over HTTPS.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/set-secure-cookie', (req, res) => {
// Set a cookie with HttpOnly, Secure, and SameSite=Lax flags
res.cookie('session_id', 'some_secret_value', {
maxAge: 3600000, // 1 hour
httpOnly: true, // Prevents client-side JavaScript access
secure: true, // Ensures cookie is sent only over HTTPS
sameSite: 'Lax',// Protects against some CSRF attacks
path: '/', // Cookie is valid for all paths
});
res.send('Secure cookie set!');
});
app.get('/read-cookie', (req, res) => {
const sessionId = req.cookies.session_id;
if (sessionId) {
res.send(`Session ID: ${sessionId}. (Note: If HttpOnly, cannot be read by client-side JS)`);
} else {
res.send('No session cookie found.');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000 (Use HTTPS in production for `secure: true` to work fully)');
});
How it works: This snippet shows how to set important security flags (`HttpOnly`, `Secure`, `SameSite`) for cookies in a Node.js Express application. `HttpOnly: true` prevents client-side JavaScript from accessing the cookie, significantly reducing the impact of XSS attacks. `Secure: true` ensures the cookie is only sent over HTTPS connections, protecting against man-in-the-middle attacks. `SameSite: 'Lax'` adds a layer of CSRF protection by controlling when cookies are sent with cross-site requests.