JAVASCRIPT
Secure Cookie Management in Express.js
Learn to secure your application's cookies by setting HttpOnly, Secure, and SameSite attributes in Express.js, protecting against XSS and CSRF attacks.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/set-secure-cookie', (req, res) => {
// Setting a secure, httpOnly, and SameSite cookie
res.cookie('session_token', 'your_secure_session_id',
{
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: true, // Ensures the cookie is sent only over HTTPS
sameSite: 'Lax', // Protects against some CSRF attacks
maxAge: 3600000, // Cookie will expire in 1 hour (in milliseconds)
path: '/', // The path for which the cookie is valid
}
);
res.send('Secure cookie set!');
});
app.get('/get-cookie', (req, res) => {
res.send(`Session token: ${req.cookies.session_token || 'Not found'}`);
});
app.listen(3000, () => {
console.log('App listening on port 3000!');
});
How it works: This snippet demonstrates how to set secure cookies in an Express.js application using `res.cookie()`. The key security attributes are: `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks; `secure: true` ensures the cookie is only sent over encrypted HTTPS connections; and `sameSite: 'Lax'` (or `'Strict'`) protects against certain Cross-Site Request Forgery (CSRF) attacks by restricting when the cookie is sent with cross-site requests. `maxAge` and `path` define the cookie's lifespan and scope. For session management, consider using libraries like `express-session` which provide these options by default.