JAVASCRIPT
Setting Secure and HTTPOnly Cookies in Express
Learn to set secure HTTPOnly and SameSite cookies in Node.js with Express to protect session data and prevent XSS attacks from accessing sensitive cookie information.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session'); // For session cookies
const app = express();
app.use(cookieParser());
// --- Example 1: Setting a simple secure cookie ---
app.get('/set-secure-cookie', (req, res) => {
// Set a cookie with essential security flags
res.cookie('mySecureData', 'secretValue123', {
httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
secure: process.env.NODE_ENV === 'production', // Send cookie only over HTTPS in production
sameSite: 'Lax', // Helps prevent CSRF attacks
maxAge: 3600000, // Cookie expires after 1 hour (in milliseconds)
path: '/', // Cookie is valid for all paths
});
res.send('Secure cookie "mySecureData" set.');
});
// --- Example 2: Using express-session with secure options ---
// Make sure to use a strong, random, and unique secret for sessions
app.use(session({
secret: process.env.SESSION_SECRET || 'a_very_strong_random_secret_string',
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: {
httpOnly: true, // Prevents JavaScript access
secure: process.env.NODE_ENV === 'production', // Only send over HTTPS in production
sameSite: 'Lax', // 'Strict' is more secure but can impact user experience
maxAge: 24 * 60 * 60 * 1000 // 1 day in milliseconds
}
}));
app.get('/login', (req, res) => {
req.session.user = { id: 1, name: 'John Doe' };
res.send('Logged in and session cookie set securely.');
});
app.get('/profile', (req, res) => {
if (req.session.user) {
res.send(`Welcome, ${req.session.user.name}! Your ID is ${req.session.user.id}.`);
} else {
res.status(401).send('Please log in.');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
How it works: This snippet demonstrates how to properly set secure cookies in an Express.js application. It covers using `res.cookie()` for arbitrary cookies and configuring `express-session` for session management. Key security flags include `httpOnly: true` to prevent client-side JavaScript access, `secure: true` (used conditionally for production) to ensure cookies are only sent over HTTPS, and `sameSite: 'Lax'` (or 'Strict') to mitigate CSRF attacks. These practices are crucial for protecting sensitive user data stored in cookies from various web vulnerabilities.