JAVASCRIPT
Secure Cookie Configuration with HttpOnly, Secure, and SameSite in Node.js
Enhance web application security by properly configuring cookies in Node.js Express with HttpOnly, Secure, and SameSite attributes to prevent common attacks like XSS and CSRF.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 3000;
app.use(cookieParser());
app.get('/', (req, res) => {
// Setting a secure session cookie
res.cookie('session_id', 'some_secure_session_token', {
httpOnly: true, // Prevents client-side JavaScript access to the cookie
secure: true, // Ensures cookie is only sent over HTTPS
sameSite: 'Lax', // Mitigates CSRF by restricting cross-site requests
maxAge: 3600000, // Cookie expiration in milliseconds (1 hour)
path: '/', // Path for which the cookie is valid
});
// Setting another example cookie
res.cookie('user_preference', 'dark_mode', {
maxAge: 86400000, // 24 hours
sameSite: 'Lax',
});
res.send('Cookies set securely!');
});
app.get('/read-cookies', (req, res) => {
res.json(req.cookies);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to set cookies with critical security attributes. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. `secure: true` ensures the cookie is only sent over HTTPS, protecting it from eavesdropping. `sameSite: 'Lax'` or `'Strict'` helps prevent CSRF by instructing browsers not to send cookies with cross-site requests. These flags are crucial for safeguarding user sessions and sensitive data.