JAVASCRIPT
Implement Secure and HttpOnly Cookies in Express.js
Understand how to set HttpOnly, Secure, and SameSite attributes for cookies in Express.js to protect sensitive session data from XSS and CSRF attacks.
const express = require('express');
const app = express();
app.get('/login', (req, res) => {
// Assume successful authentication
const userId = 'user123';
const sessionId = 'some_secure_session_id';
res.cookie('session_id', sessionId, {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Only send over HTTPS in production
sameSite: 'Lax', // Protects against some CSRF attacks
maxAge: 3600000, // 1 hour expiration in milliseconds
path: '/', // The path for which the cookie is valid
});
res.send('Logged in successfully! Cookie set.');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How it works: This Express.js snippet demonstrates how to set a secure cookie for session management. The 'httpOnly: true' attribute prevents client-side JavaScript from accessing the cookie, largely mitigating XSS attacks that attempt to steal session tokens. 'secure: true' ensures the cookie is only sent over HTTPS, protecting it from interception during transmission. 'sameSite: 'Lax'' helps prevent Cross-Site Request Forgery (CSRF) attacks by restricting when the browser sends the cookie with cross-site requests. 'maxAge' defines the cookie's expiration, and 'path' specifies its scope within the domain.