Cookie Security: HttpOnly, Secure, and SameSite Explained
Three cookie flags that can prevent session hijacking and CSRF attacks.
Cookies store sensitive session data. Without proper security flags, they're easily stolen.
The three flags
HttpOnly
Prevents JavaScript from accessing the cookie. This stops XSS attacks from stealing session tokens.
Secure
Only sends the cookie over HTTPS. Without this, cookies are sent in plaintext over HTTP.
SameSite
Controls when cookies are sent with cross-site requests. SameSite=Strict or SameSite=Lax prevents CSRF attacks.
How to set them
PHP: session_set_cookie_params(['secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
Node.js: res.cookie('name', value, {secure: true, httpOnly: true, sameSite: 'strict'});
Without these flags, a single XSS vulnerability can lead to full account takeover.