HttpOnly Cookies: Keep Secrets from JavaScript
The HttpOnly flag makes cookies inaccessible to client-side JavaScript, preventing theft via XSS attacks. Use it for session tokens the server needs but the UI doesn't.
WHY IT EXISTS HttpOnly cookies were created to mitigate a specific, common attack: stealing sensitive data via Cross-Site Scripting (XSS). If a malicious script is injected into a webpage, it can access and exfiltrate data from cookies, such as session tokens, allowing an attacker to impersonate the user.
THE MENTAL MODEL Think of the HttpOnly flag as a lock on a cookie jar that only the server has the key for. The browser can receive the cookie and send it back to the server with every request, but it forbids any client-side JavaScript running on the page from opening the jar and seeing what's inside. The cookie is for the server's eyes only.
HOW IT WORKS When a server sets a cookie, it uses the Set-Cookie HTTP response header. To enable this protection, the server simply adds the HttpOnly flag to the header string, like this: Set-Cookie: session_id=abc123; HttpOnly; Secure. When the browser sees this flag, it makes the cookie inaccessible to the document.cookie API and other client-side script access.
WHEN TO USE IT Use the HttpOnly flag for any cookie that contains sensitive information your client-side code doesn't need to read. This is the standard, secure way to handle session identifiers, authentication tokens (like JWTs), and any other secret data that is only relevant for server-side processing. It's a fundamental security practice for modern web applications.
WHEN NOT TO USE IT Only omit the HttpOnly flag if your client-side JavaScript genuinely needs to read a cookie's value. For instance, you might store a non-sensitive user preference like 'theme=dark' in a regular cookie so your React app can immediately apply the theme on load without waiting for a server call. For anything related to authentication or session state, HttpOnly is almost always the right choice.
ONE CANONICAL EXAMPLE After a user logs in, the server generates a JSON Web Token (JWT) and sends it back to the browser in an HttpOnly cookie. For every subsequent API call the React app makes, the browser automatically attaches this cookie. The server receives the request, reads the JWT from the cookie, and verifies the user's session. A potential XSS vulnerability in the React app could not steal this JWT, because the browser prevents JavaScript from accessing the cookie's value.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.