HttpOnly and Secure Cookie Flags
What you'll learn: How two simple cookie flags can dramatically reduce XSS and man-in-the-middle attack risks.
When an attacker successfully injects malicious JavaScript through XSS (as you've learned), one of their primary targets is session cookies. If they steal your session cookie, they can impersonate you completely. Cookie security flags are your first line of defense.
What Are These Flags?
Cookies can be set with special attributes that control how they behave:
HttpOnly Flag: When set, this flag prevents JavaScript from accessing the cookie through document.cookie. It's like putting your valuables in a safe that only the server can open—client-side scripts are locked out entirely.
Secure Flag: This ensures the cookie is only transmitted over HTTPS connections, never over plain HTTP. Think of it as requiring an armored truck for transport instead of a regular car—eavesdroppers on the network cannot intercept it.
Why They Matter
Even if an XSS vulnerability exists in your application, an HttpOnly cookie cannot be stolen via JavaScript injection. The attacker's <script>document.cookie</script> payload will come up empty-handed for those cookies.
The Secure flag protects against network-level attacks. If someone is monitoring unencrypted traffic (like on public WiFi), they won't see cookies marked as Secure being transmitted.
Setting Them
When setting a cookie server-side, include both flags:
Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict
These are defense in depth measures—they don't stop XSS, but they dramatically limit what an attacker can do with it.
Key Takeaway: Always use HttpOnly to prevent JavaScript cookie theft and Secure to enforce HTTPS-only transmission—these simple flags stop most session hijacking attacks cold.