How to Set Secure Cookie Flags
What is this?
Cookie security flags control how browsers handle cookies. The three essential flags are Secure (only sent over HTTPS), HttpOnly (not accessible via JavaScript), and SameSite (controls cross-site sending behavior).
Why it matters
- Security: Without
HttpOnly, cookies can be stolen via XSS attacks. WithoutSecure, they can be intercepted over HTTP. - Privacy:
SameSiteprevents cookies from being sent in cross-site requests (CSRF protection) - Compliance: GDPR and PCI DSS require appropriate cookie security measures
How to fix it
Node.js / Express
app.use(session({
cookie: {
secure: true, // Only send over HTTPS
httpOnly: true, // Not accessible via document.cookie
sameSite: 'lax', // Prevents CSRF while allowing top-level navigation
maxAge: 86400000 // 24 hours
}
}));
PHP
// php.ini settings
session.cookie_secure = 1
session.cookie_httponly = 1
session.cookie_samesite = Lax
// Or at runtime
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Lax');
Django
# settings.py
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
Go
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: token,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Path: "/",
})
Common mistakes
- Setting
Secureon a development environment without HTTPS. Use conditional logic to disable it in dev. - Using
SameSite=Nonewithout theSecureflag. Browsers require both when usingNone. - Forgetting to set flags on all cookies, not just the session cookie.
Test your fix
After updating your cookie flags, audit your site on BeaverCheck to check the Security tab.