HttpOnly Cookie Flag Explained
The HttpOnly cookie flag tells the browser to hide a cookie from JavaScript. A cookie set with HttpOnly cannot be read through document.cookie, which means that even if an attacker injects a malicious script through cross-site scripting (XSS), that script cannot steal the session cookie. It is one of the simplest and highest-value protections for a login session.
What is the HttpOnly flag?
Defined in the cookie specification (RFC 6265), HttpOnly is set in the Set-Cookie header. Normally any script running on the page can read all of the page's cookies via document.cookie — including the session cookie. That is exactly what an XSS payload does when it exfiltrates a session. HttpOnly removes the cookie from the JavaScript-visible set, so the browser still sends it on requests automatically, but scripts can neither read nor modify it.
Example Set-Cookie with HttpOnly
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/
How HttpOnly limits XSS damage
An XSS vulnerability lets an attacker run JavaScript in a victim's browser. The classic payoff is reading the session cookie and sending it to the attacker, hijacking the session. With HttpOnly set, document.cookie simply does not contain that cookie, so this specific theft fails. HttpOnly does not fix the XSS itself — an attacker can still perform actions in the page — but it removes the most damaging outcome, session theft, from the table.
How to check the HttpOnly flag
Inspect a site's Set-Cookie headers to confirm session cookies are marked HttpOnly (and Secure and SameSite) with the free HTTP headers checker.
Common mistakes
- Needing to read the cookie in JavaScript. If your front-end reads the session token via
document.cookie, you cannot use HttpOnly on it — which is a sign the token should be handled differently (server-set, HttpOnly). Design around it rather than dropping the flag. - Setting HttpOnly but not Secure. HttpOnly stops script access, but without Secure the cookie can still leak over plaintext HTTP. Use both.
- Assuming HttpOnly fixes XSS. It only blocks cookie theft. You still have to eliminate the underlying XSS.
Related guides
HttpOnly is one of three cookie security flags, with Secure and SameSite. It is a key mitigation for cross-site scripting.
Frequently asked questions
What does the HttpOnly flag do?
It hides a cookie from JavaScript, so scripts cannot read it via document.cookie. The browser still sends the cookie on requests, but an XSS payload cannot steal it.
Does HttpOnly prevent XSS?
No. It prevents the theft of the cookie via XSS, which is the most damaging outcome, but the XSS vulnerability itself must still be fixed.
Should all cookies be HttpOnly?
Every cookie holding a session or other sensitive value should be. The only cookies that should not be are ones your front-end code genuinely needs to read in the browser.