JAVASCRIPT
Secure Cookies with HttpOnly, Secure, and SameSite Attributes
Discover how to properly secure your session and authentication cookies against XSS and CSRF by setting HttpOnly, Secure, and SameSite attributes in Node.js Express applications.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
// A simple route to set cookies
app.get('/login', (req, res) => {
const userToken = 'a_secure_jwt_token'; // In a real app, this would be generated after authentication
// GOOD: Setting secure cookie attributes
res.cookie('auth_token', userToken, {
httpOnly: true, // Prevents client-side JavaScript access
secure: process.env.NODE_ENV === 'production', // Send only over HTTPS in production
sameSite: 'Lax', // Protects against some CSRF attacks
maxAge: 3600000, // 1 hour expiration
path: '/',
});
// Another cookie for non-sensitive data, potentially accessible by client-side JS
res.cookie('display_name', 'JohnDoe', {
maxAge: 3600000,
path: '/',
});
res.send('Cookies set successfully! Check your browser dev tools.');
});
app.get('/logout', (req, res) => {
res.clearCookie('auth_token');
res.clearCookie('display_name');
res.send('Cookies cleared.');
});
app.get('/', (req, res) => {
res.send(`
<h1>Cookie Security Example</h1>
<p>Auth Token: ${req.cookies.auth_token ? 'Exists (HttpOnly, Secure, SameSite)' : 'Not set'}</p>
<p>Display Name: ${req.cookies.display_name || 'Not set'}</p>
<p><a href="/login">Login (Set Cookies)</a></p>
<p><a href="/logout">Logout (Clear Cookies)</a></p>
<p>Remember to view in browser dev tools under Application -> Cookies.</p>
${process.env.NODE_ENV !== 'production' ? '<p>Note: For `secure: true` to fully work, access via HTTPS.</p>' : ''}
`);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Current NODE_ENV: ${process.env.NODE_ENV}`);
});
How it works: This Node.js Express snippet demonstrates how to secure cookies by setting the `HttpOnly`, `Secure`, and `SameSite` attributes. The `HttpOnly` attribute prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. The `Secure` attribute ensures cookies are only sent over HTTPS, protecting them from interception. The `SameSite` attribute (e.g., 'Lax', 'Strict', 'None') helps protect against CSRF attacks by controlling when cookies are sent with cross-site requests. Setting these attributes is crucial for safeguarding sensitive information like session tokens and authentication credentials.