What is an HttpOnly cookie?
An HttpOnly cookie is a cookie with a security flag that is inaccessible to JavaScript in the browser.
In simple terms: an HttpOnly cookie cannot be read or changed through JavaScript code on the page.
Why HttpOnly is needed
The main goal is protection against XSS attacks.
If a site has a vulnerability and an attacker injects JavaScript code:
- a regular cookie can be stolen
- an HttpOnly cookie cannot be stolen through JavaScript
This is very important for protecting authorization.
How this works
- The server sends a cookie with the HttpOnly flag
- The browser stores the cookie
- The browser:
- sends the cookie to the server with HTTP requests
- does not give JavaScript access to the cookie
The cookie works, but is hidden from JS.
What you can and cannot do with an HttpOnly cookie
You can:
- use it for sessions
- use it for authorization tokens
- have it sent automatically to the server
You cannot:
- read it through
document.cookie - change it through JavaScript
- pass it to third-party JS code
A common interview question
If JavaScript cannot see an HttpOnly cookie, how does the server recognize the user?
The answer: the browser itself sends the cookie to the server with every request, JavaScript is not needed for that at all.
HttpOnly + Secure, best practice
HttpOnly is usually used together with other flags:
- HttpOnly - protection against XSS
- Secure - transfer only over HTTPS
- SameSite - protection against CSRF
For session cookies, this is the standard.
Real-life example
An HttpOnly cookie is like:
- a pass kept in a closed pocket
- you get through automatically with it
- but you cannot show it to just anyone
Short answer for an interview
Remember this wording:
An HttpOnly cookie is a cookie with a security flag that is inaccessible to JavaScript and is used to protect sensitive data, such as sessions, from XSS attacks.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.