An HTTP cookie is a small piece of data that a website asks the browser to store and then send back with later requests to the same site. Cookies are how a site remembers that you are logged in, what is in your cart, or which language you chose, even though HTTP itself treats every request as unrelated to the last.
Lou Montulli invented cookies at Netscape in 1994 to support an online shopping cart. The current standard is RFC 6265 from 2011, which an update known as RFC 6265bis extends with the SameSite attribute.
How a cookie is set
The server sends a Set-Cookie header in its response, with a name, a value and optional attributes. From then on, the browser includes the cookie in the Cookie header of every matching request. JavaScript can also read and write cookies through document.cookie, unless the cookie is marked HttpOnly.
The attributes decide how a cookie behaves:
ExpiresorMax-Agemake it persistent. Without them it is a session cookie, deleted when the browser session ends.DomainandPathlimit which URLs receive it.Securesends it only over HTTPS.HttpOnlyhides it from JavaScript, so a cross-site scripting attack cannot read and steal a session cookie.SameSitecontrols whether it is sent with requests that come from other sites, a defense against CSRF. Chrome and Edge treat a cookie without the attribute asLax.
Browsers limit each cookie to about 4 KB, which is why cookies usually hold an identifier rather than the data itself.
First-party and third-party
A first-party cookie belongs to the site in the address bar. A third-party cookie belongs to another domain whose content is embedded in the page, such as an ad network, and lets that domain recognize the same browser across many sites.
Cookies and consent
Under the ePrivacy Directive, a site may only store or read a cookie that is not strictly necessary on the device of a visitor in the EU after the visitor agrees, wherever the site itself is based, which is why cookie consent banners exist. Cookies needed for a service the visitor asked for, such as a login or a cart, are exempt. Advertising cookies are not, and in most EU countries analytics cookies are not either.