Programming

How do HttpOnly cookies work with AJAX requests

25 September 2026 · 10 min read

How do HttpOnly cookies work with AJAX requests

In the evolving landscape of web development, security is paramount. As applications become more dynamic and interactive, powered largely by asynchronous JavaScript and XML (AJAX) requests, understanding how different security mechanisms interact is crucial. One such mechanism is the HttpOnly cookie, designed to mitigate a significant class of web vulnerabilities. Developers often wonder: How do HttpOnly cookies work with AJAX requests? This question delves into the fundamental interplay between client-side scripting, server-side session management, and browser security models. Far from being a hindrance, HttpOnly cookies play a vital role in enhancing the security posture of modern web applications, ensuring sensitive information remains protected even when sophisticated client-side operations are underway.

Understanding HttpOnly Cookies

HttpOnly is an attribute that can be added to a cookie when it’s set by the server. Its primary purpose is to prevent client-side scripts, such as JavaScript, from accessing the cookie’s value. This restriction is a powerful defense against Cross-Site Scripting (XSS) attacks. In an XSS attack, malicious scripts injected into a legitimate web page can attempt to steal sensitive information, including user session cookies, which could then be used to hijack a user’s session.

When a cookie is marked as HttpOnly, the browser ensures that the document.cookie API and other client-side methods cannot read, modify, or delete that cookie. This means that even if an attacker successfully injects a malicious script onto your page, they won’t be able to exfiltrate the HttpOnly session cookie, thereby preventing session hijacking. This attribute doesn’t prevent the cookie from being sent with HTTP requests; rather, it controls its accessibility from the client-side scripting environment. It’s a critical component of secure session management, distinguishing it from standard cookies that are fully exposed to JavaScript.

For instance, imagine a banking website using HttpOnly cookies for session authentication. If a minor XSS vulnerability exists, an attacker might inject a script. However, because the session cookie is HttpOnly, the script cannot read the cookie and send it to the attacker’s server. This significantly reduces the impact of the XSS vulnerability, demonstrating why HttpOnly is considered a fundamental security best practice for any cookie containing sensitive data, such as session IDs or authentication tokens. For more in-depth knowledge on web security, consider exploring resources on secure coding practices.

The Nature of AJAX Requests

AJAX, short for Asynchronous JavaScript and XML, refers to a set of web development techniques that allow a web page to update asynchronously by exchanging small amounts of data with the server behind the scenes. This means that parts of a web page can be updated without reloading the entire page, enhancing user experience and application responsiveness. Modern web applications heavily rely on AJAX, using technologies like the XMLHttpRequest object or the newer Fetch API to make these requests.

When an AJAX request is initiated by the browser, whether it’s a GET, POST, or another HTTP method, the browser automatically includes all relevant cookies that are valid for the domain and path of the request. This behavior is fundamental to how session management works on the web. If a user has an active session cookie for a particular domain, every subsequent request, including AJAX calls, will automatically send that cookie to the server. This allows the server to identify the user and maintain their session state without requiring explicit cookie handling in the client-side JavaScript code.

The Same-Origin Policy is a crucial browser security mechanism that dictates how documents or scripts loaded from one origin can interact with resources from another origin. While it generally restricts cross-origin interactions to prevent malicious data access, cookies are an exception. Cookies are typically sent with requests to their originating domain, regardless of whether the request is initiated by a full page load or an AJAX call. Cross-Origin Resource Sharing (CORS) becomes relevant when AJAX requests are made to a different origin, requiring specific HTTP headers to allow such interactions while respecting security boundaries. However, even with CORS, the browser’s automatic inclusion of HttpOnly cookies remains consistent for the relevant domain.

Infographic here
HttpOnly and AJAX: The Interaction ----------------------------------

The core principle of HttpOnly cookies is their inaccessibility via client-side scripts. This restriction, however, does not impede their functionality in HTTP requests. When an AJAX request is made from a browser to a server, the browser, following standard HTTP protocol, automatically appends all cookies that are valid for the request’s domain and path. This includes HttpOnly cookies. The server receives these HttpOnly cookies just as it would receive any other cookie, allowing it to process session information, authentication tokens, or any other data stored within them.

Therefore, the answer to “How do HttpOnly cookies work with AJAX requests?” is straightforward: HttpOnly cookies are indeed sent with AJAX requests by the browser, but they remain inaccessible to JavaScript code running in the browser’s environment. This design is a deliberate security measure. The server-side application can read and utilize the HttpOnly cookie for operations like user authentication or session validation, while the client-side JavaScript cannot directly manipulate or steal it. This separation of concerns ensures that even if a sophisticated XSS attack compromises the client-side, the critical session identifier remains protected from exfiltration.

This means that developers don’t need to write special JavaScript code to include HttpOnly cookies with their AJAX calls; the browser handles it automatically. The security benefit comes from the fact that a malicious script, even if injected, cannot read the document.cookie property to gain access to the HttpOnly cookie’s value. This significantly reduces the attack surface for session hijacking, making HttpOnly cookies an essential part of a robust web security strategy. For further reading on the specifications of HTTP cookies, refer to the Mozilla Developer Network (MDN) documentation on HTTP Cookies.

Best Practices and Security Considerations

While HttpOnly cookies offer a strong defense against XSS-based session hijacking, they are not a silver bullet. A comprehensive security strategy involves combining HttpOnly with other crucial cookie attributes and security measures. The Secure attribute ensures that the cookie is only sent over HTTPS connections, protecting it from eavesdropping during transit. The SameSite attribute, gaining increasing importance, helps mitigate Cross-Site Request Forgery (CSRF) attacks by controlling when cookies are sent with cross-site requests. Using SameSite=Lax or SameSite=Strict can significantly enhance protection against CSRF, even for HttpOnly cookies.

For applications heavily reliant on AJAX, especially those dealing with sensitive user actions, implementing robust CSRF protection is vital. While HttpOnly prevents scripts from reading the cookie, it doesn’t prevent the browser from sending it with a forged request if the attacker can trick a user’s browser into making one. A common approach is to use synchronizer tokens, where the server issues a unique, Question & Answer :

JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site?

Edit: Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?

Edit 2: Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of HttpOnly?

Edit 3: Here is a quote from Wikipedia:

When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The HttpOnly flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].

I understand that document.cookie is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only?

In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.

<script type="text/javascript"> var req = null; try { req = new XMLHttpRequest(); } catch(e) {} if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} req.open('GET', 'http://stackoverflow.com/', false); req.send(null); alert(req.getAllResponseHeaders()); </script> 

Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated…

Final Edit: Ahh, apparently both sites are wrong, this is actually a bug in FireFox. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.

To reiterate everything I’ve learned:

  • HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)
  • HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.
  • XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.

edit: This information is likely no longer up to date.

Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest’s request to the server.

In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don’t know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the “vote” controller method.

More generally, cookies are not required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.

However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.

In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.

XmlHttpRequest won’t make cross-domain requests (for exactly the sorts of reasons you’re touching on).

You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it’s inaccessible.

Unless you had compromised StackOverflow.com on the server side, you wouldn’t be able to steal my cookie.

Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?

Consider this scenario:

  • I find an avenue to inject JavaScript code into the page.
  • Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.
  • Jeff submits a stellar answer to your question.
  • Because he submits it with my cookie data instead of his, the answer will become mine.
  • You vote up “my” stellar answer.
  • My real account gets the point.

With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.

Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated…

That’s correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.

However, if you go back to my example scenario, you can see where HTTP-Only does successfully cut off the XSS attacks which rely on modifying the client’s cookies (not uncommon).

It boils down to the fact that a) no single improvement will solve all vulnerabilities and b) no system will ever be completely secure. HTTP-Only is a useful tool in shoring up against XSS.

Similarly, even though the cross domain restriction on XmlHttpRequest isn’t 100% successful in preventing all XSS exploits, you’d still never dream of removing the restriction.