What is an HttpOnly Cookie?
Last Updated: August 24, 2020
HttpOnly is a tag added to a browser cookie that prevents client-side scripts from accessing data. It provides a gate that prevents the specialized cookie from being accessed by anything other than the server. Using the HttpOnly tag when generating a cookie helps mitigate the risk of client-side scripts accessing the protected cookie, thus making these cookies more secure.
The example below shows the syntax used within the HTTP response header:
Set-Cookie: `=“[; “=“]` `[; expires=“][; domain=“]` `[; path=“][; secure][; HttpOnly]`
If the HttpOnly flag is included in the HTTP response header, the cookie cannot be accessed through the client-side script. As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits the flaw, the browser will not reveal the cookie to the third-party.
Here’s an example – let’s say a browser detects a cookie containing the HttpOnly flag. If the client-side code attempts to read the cookie, the browser will return an empty string as a result. This helps prevent malicious (usually cross-site scripting (XSS)) code from sending the data to an attacker’s website.