JAVASCRIPT
Implement Secure HTTP-Only and SameSite Cookies in Express
Protect user sessions and prevent XSS/CSRF attacks by implementing HTTP-only, secure, and SameSite cookies in your Express.js application for enhanced security.
const express = require('express');
const cookieParser = require('cookie-parser'); // npm install cookie-parser
const app = express();
app.use(cookieParser());
// Middleware to set a secure session cookie after successful login
app.post('/login', (req, res) => {
// In a real app, validate user credentials here
const userId = 'user_abc_123'; // Example user ID
// Set a secure session cookie
res.cookie('session_token', 'some_secret_jwt_token_or_session_id', {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
sameSite: 'Lax', // Helps prevent Cross-Site Request Forgery (CSRF)
maxAge: 3600000, // Cookie expiration in milliseconds (1 hour)
path: '/', // Path for which the cookie is valid
});
res.status(200).json({ message: 'Login successful!', userId });
});
// Middleware to read a cookie
app.get('/dashboard', (req, res) => {
const sessionToken = req.cookies.session_token;
if (sessionToken) {
// In a real app, verify the session token and fetch user data
res.status(200).json({ message: `Welcome to the dashboard! Your session token (not directly readable by JS): ${sessionToken.substring(0, 10)}...` });
} else {
res.status(401).json({ message: 'Unauthorized. Please log in.' });
}
});
// Middleware to clear a cookie
app.post('/logout', (req, res) => {
res.clearCookie('session_token', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Lax',
path: '/',
});
res.status(200).json({ message: 'Logged out successfully.' });
});
app.get('/', (req, res) => {
res.send('<h1>Express App with Secure Cookies</h1><p>Try POSTing to /login and then GETting /dashboard.</p>');
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log('Use tools like Postman or browser dev tools to test cookie setting/reading.');
});
How it works: This Node.js Express snippet demonstrates how to set and manage cookies securely to protect against common web vulnerabilities like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). By setting the `httpOnly: true` flag, client-side JavaScript is prevented from accessing the cookie, mitigating XSS risks. The `secure: true` flag ensures the cookie is only sent over HTTPS, protecting against man-in-the-middle attacks. The `sameSite: 'Lax'` attribute helps prevent CSRF by instructing browsers to only send the cookie with same-site requests or top-level navigations, restricting its exposure during cross-site requests.