JAVASCRIPT
Enhance Session Security with HttpOnly, Secure, and SameSite Cookies in Express
Implement critical cookie flags like HttpOnly, Secure, and SameSite in your Express.js application to protect user sessions from XSS, man-in-the-middle, and CSRF attacks.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/login', (req, res) => {
// In a real app, authenticate user first
const sessionId = 'some_unique_session_id'; // Generate a secure session ID
res.cookie('session_token', sessionId, {
httpOnly: true, // Prevents client-side JavaScript access
secure: process.env.NODE_ENV === 'production', // Only send over HTTPS
sameSite: 'Lax', // Protects against CSRF (also 'Strict' or 'None' with 'Secure')
maxAge: 3600000, // Cookie expires in 1 hour (in milliseconds)
path: '/' // Available across the entire domain
});
res.send('Logged in! Session cookie set securely.');
});
app.get('/logout', (req, res) => {
res.clearCookie('session_token');
res.send('Logged out! Session cookie cleared.');
});
app.get('/dashboard', (req, res) => {
const sessionToken = req.cookies.session_token;
if (sessionToken) {
res.send(`Welcome to your dashboard! Session ID: ${sessionToken}`);
} else {
res.status(401).send('Unauthorized. Please log in.');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How it works: This Express.js snippet demonstrates how to set cookies securely using the `httpOnly`, `secure`, and `sameSite` flags. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. `secure: true` ensures the cookie is only sent over HTTPS, protecting against man-in-the-middle attacks. `sameSite: 'Lax'` helps prevent Cross-Site Request Forgery (CSRF) by restricting when cookies are sent with cross-site requests. These flags are crucial for maintaining the integrity and confidentiality of user sessions.