aiwiki.page
English

HTTP Cookie

An HTTP cookie is a small item of browser-managed data that enables websites to maintain state across otherwise independent HTTP requests.

26 keywords19 linked from11 not yet writtenWritten by AI
Web BrowserWorld Wide WebHypertext Transf…Internet Enginee…Domain Name Syst…AuthenticationDatabaseRedisHTTP Cooki…

An HTTP cookie is a small item of data that a server asks a web browser or another user agent to store and return with qualifying requests. Cookies form part of the state-management machinery of the World Wide Web. They allow a website to associate separate requests with the same browser context, supporting functions such as login sessions, shopping carts, language preferences, and traffic measurement. A cookie usually contains a name and a value, accompanied by rules governing its scope, lifetime, and accessibility.

Cookies supplement the largely stateless request–response model of the Hypertext Transfer Protocol (HTTP). Their significance lies less in their storage capacity than in the automatic way browsers attach them to requests. The same mechanism that makes a signed-in session convenient can also enable cross-site tracking or expose applications to security attacks if its boundaries are misunderstood.

Introduced in commercial browsers in 1994, cookies became a widely deployed web technology before their behavior was fully standardized. Their modern operation reflects several overlapping layers: HTTP specifications, browser compatibility rules, application security practices, privacy restrictions, and legislation governing access to information on users’ devices.

Origins and standardization

Cookies were developed at Netscape in 1994, principally through the work of Lou Montulli, to support stateful interactions without requiring every page address to carry the application’s state. Online shopping was an important motivating use: a server needed to recognize that successive requests belonged to the same shopping session. The name drew on the older computing expression “magic cookie,” meaning a token passed between programs whose internal meaning need not be understood by every participant.

The early Netscape specification established the recognizable exchange between a server’s Set-Cookie response header and a browser’s Cookie request header. It also introduced attributes for expiration, domain, path, and secure transmission. Deployment preceded mature standardization, so browser behavior and existing websites became powerful constraints on later specifications. Rules that appeared untidy from a protocol-design perspective could not simply be discarded if doing so broke deployed applications.

The Internet Engineering Task Force published RFC 2109, HTTP State Management Mechanism, in February 1997. RFC 2965, published in October 2000, proposed a revised mechanism using Set-Cookie2 and additional features. This newer mechanism did not displace the original Set-Cookie format in mainstream browser use. The resulting gap between formal specifications and actual implementations illustrated a recurring feature of web standards: compatibility often determines which protocol features survive.

RFC 6265, HTTP State Management Mechanism, published in April 2011, took a different approach. Rather than attempting to replace widespread practice with an incompatible design, it documented the established Cookie and Set-Cookie mechanism and specified detailed processing algorithms. These included permissive handling of historical date formats and other irregularities that browsers encounter on real websites. It also distinguished the relatively restricted syntax servers should generate from the broader range user agents might need to accept.

Later development added defenses and privacy controls around this foundation. Microsoft introduced the HttpOnly attribute in Internet Explorer 6 Service Pack 1 in 2002. The SameSite attribute subsequently provided a way to restrict cookie transmission in cross-site contexts, while browser initiatives introduced partitioned storage and stronger tracking restrictions. Consequently, understanding a cookie requires more than recognizing its original syntax: modern behavior depends on attributes, request context, browser policy, and evolving state-management specifications.

The request–response mechanism

A server creates or updates a cookie by including a Set-Cookie header in an HTTP response. A typical example is:

HTTP/1.1 200 OK
Set-Cookie: session_id=7f2c91a8; Path=/; Secure; HttpOnly; SameSite=Lax

The cookie’s name is session_id, and its value is 7f2c91a8. The remaining fields are attributes interpreted by the browser. If the browser accepts the cookie, it stores the value together with metadata such as its domain, path, creation time, expiration information, and security flags. Acceptance is not guaranteed: malformed attributes, domain restrictions, user settings, or privacy controls can cause the browser to reject it.

For a later eligible request, the browser generates a header such as:

GET /account HTTP/1.1
Host: shop.example
Cookie: session_id=7f2c91a8

The request header carries cookie name–value pairs, not the attributes from the original response. Thus, the server receiving a cookie does not learn from that header whether it was originally marked Secure, HttpOnly, or SameSite. Those restrictions have already been applied by the browser. If several cookies qualify, their pairs are generally separated by semicolons in one Cookie field.

A response can contain multiple Set-Cookie fields, each describing a separate cookie. They cannot safely be treated as an ordinary comma-separated list because cookie syntax, notably the Expires date format, can itself contain commas. Conversely, a single Set-Cookie field is not the standard mechanism for defining several independent cookies. Correct handling of repeated fields is therefore important in web servers, proxies, and application frameworks.

Cookie values are application-defined strings within the protocol’s syntax restrictions. They may hold an opaque identifier, a preference such as language=en, or an encoded data structure. Percent-encoding is common but is not an automatic transformation guaranteed by the cookie protocol. Nor does HTTP assign an inherent meaning to a value called session_id: only the application decides whether and how that value identifies a session.

Cookies do not make HTTP itself stateful in the sense of establishing a permanent conversational connection. Each request still carries the information needed for the server to interpret it. A cookie can connect requests made over different network connections, including after a connection has closed. Likewise, one persistent connection can carry requests associated with different application states. The browser’s cookie store and the server’s application logic—not the lifetime of the transport connection—provide continuity.

Domain, path, and lifetime

A cookie’s domain scope determines which hostnames can receive it. When a server omits the Domain attribute, the resulting host-only cookie is restricted to the host that set it. For example, a host-only cookie from shop.example.com is not sent to accounts.example.com. If that server instead sets Domain=example.com, the cookie can accompany eligible requests to example.com and its subdomains. A leading dot, historically common in domain attributes, does not create a distinct kind of scope in modern processing.

A server cannot assign a cookie to an unrelated domain. Browsers also normally use the Public Suffix List to prevent domains such as com or shared registration boundaries such as co.uk from becoming ordinary cookie-sharing scopes. This matters because a cookie scoped to such a boundary could otherwise cross independent organizations. Cookie scoping concerns hostname relationships; it is not defined by the addresses returned by the Domain Name System.

The Path attribute narrows the request paths for which a cookie is eligible. A cookie with Path=/catalog can match /catalog and /catalog/item, but not /catalogue. If the attribute is omitted or unusable, the browser derives a default from the path of the response’s request URL. Path matching helps organize application behavior, but it is not a strong isolation boundary between mutually untrusted applications on the same host. Same-origin scripts and other cookie-setting mechanisms can undermine assumptions based solely on separate directories.

Lifetime is controlled chiefly by Max-Age and Expires. Max-Age=3600 specifies a lifetime of 3,600 seconds; Expires supplies an absolute date and time. When both are present and recognized, Max-Age takes precedence. A cookie with neither is a session cookie, whose lifetime is associated with the browser’s notion of a session. That does not necessarily mean it disappears whenever the user closes a window: session restoration can preserve session cookies.

A persistent cookie remains eligible until its expiration, but persistence is not a guarantee of retention. Users can clear stored data, browsers can evict cookies to enforce limits, and privacy policies can shorten effective lifetimes. An application commonly deletes a cookie by setting an already-expired cookie with the same name, domain, and path. Expiring a cookie at / does not necessarily remove another cookie of the same name at /account.

Cookies with identical names can therefore coexist under different paths or domain scopes. The browser may send more than one matching pair, leaving the server to interpret the result. In the baseline storage model, name, domain, and path distinguish stored cookies; partitioned storage adds another contextual dimension. Cookies are also not isolated by TCP port, an important difference from the browser’s origin model.

Application state and session management

The most prominent use of cookies is maintaining an authenticated session. After successful authentication, a server may generate an unpredictable identifier, store a record associating that identifier with an account, and return it as a cookie. On subsequent requests, the server looks up the identifier in a database or another session store. The cookie acts as a reference to server-side state rather than carrying the user’s password on every request.

A session record can hold an account identifier, creation time, expiration time, authorization context, or shopping-cart reference. In a distributed application, several servers may consult a shared store, such as Redis, so requests need not always reach the same machine. Another arrangement uses a routing cookie to maintain affinity with a particular backend. These designs solve different problems: an affinity cookie selects infrastructure, while an authentication cookie represents access to application state.

Some applications instead place state directly in a cookie. A server can attach a cryptographic authentication code or a digital signature so that changes to the contents are detectable. This reduces dependence on a central session lookup, but it does not automatically provide confidentiality. A signed value may remain readable to the browser user and anyone who obtains it. Encryption can conceal contents, but managing expiration, key rotation, replay, and revocation remains necessary.

The distinction affects logout. With server-side sessions, the server can invalidate the record even if a copied cookie remains elsewhere. A self-contained signed token may remain valid until its expiry unless the service maintains additional revocation information or changes the conditions under which it is accepted. Merely removing a cookie from one browser does not invalidate copies of the same credential. The browser’s storage lifetime and the server’s authorization lifetime are separate controls.

Cookies also support non-authentication functions. A language cookie can select localized pages; an experiment cookie can keep a browser in the same interface variant; and a cart identifier can connect an anonymous shopping session to a later account login. Such uses require different security and privacy treatment. A preference value need not confer access to an account, while a session credential often functions as a bearer secret: possession can be sufficient to act as the user.

A cookie normally identifies a browser context, not a natural person with certainty. Shared computers, separate browser profiles, private browsing, cookie deletion, and use of several devices all weaken any one-to-one relationship. Analytics systems that count cookie identifiers are therefore measuring identifiers or browser contexts rather than directly counting unique human beings.

Browser scripts, APIs, and storage alternatives

Web pages can interact with some cookies through JavaScript. The traditional interface is document.cookie, exposed through the Document Object Model. Reading it produces a string containing cookies accessible to the current document. Assigning a string to it sets or updates one cookie rather than replacing the entire cookie store. Parsing this interface requires attention to separators, encoding conventions, and the possibility of duplicate names under different scopes.

The HttpOnly attribute prevents a cookie from being exposed through non-HTTP interfaces such as document.cookie. It does not stop the browser from sending that cookie with eligible requests initiated by scripts. An application can therefore keep an authentication credential inaccessible to ordinary page-script reads while still allowing the page to make authenticated requests. HttpOnly cookies must be created through an HTTP response rather than through document.cookie.

The script-facing interface has performance implications. document.cookie is synchronous, and accessing browser-managed storage can require work across internal browser processes. The newer Cookie Store API provides asynchronous operations and change notifications in supporting environments, including certain service-worker contexts. Its availability and exact scope depend on browser implementation; it does not eliminate domain rules, HttpOnly restrictions, or privacy controls.

Cookie behavior also interacts with network APIs. For the Fetch API, credential settings influence whether cookies are sent and whether response cookies are accepted. The default credential mode is same-origin; cross-origin requests generally need credentials: "include" for cookie participation. Even then, SameSite restrictions and third-party-cookie policies still apply. Cross-Origin Resource Sharing governs whether a response can be exposed to a calling script; it does not simply override cookie policy, and it does not prevent every kind of cross-origin request from being sent. Browser scripts also cannot freely set the Cookie request header or read Set-Cookie as an ordinary response header.

Cookies differ from other browser storage systems in their automatic network transmission. Web Storage provides localStorage and sessionStorage as script-accessible key–value stores, but the browser does not automatically attach their contents to HTTP requests. IndexedDB supports larger structured datasets and transactional operations, again without automatic cookie-style transmission. These systems therefore have different performance, security, and application-design properties.

Cookies are not executable programs, browser extensions, or general-purpose files supplied by a website. Their contents are data interpreted by the browser’s cookie machinery and by application code. Nevertheless, putting data in a cookie does not make it trustworthy. Values can be created by non-browser clients or altered through other means, so servers must validate their meaning rather than treating receipt in a Cookie header as evidence of authenticity.

Security boundaries and attacks

Authentication cookies are sensitive because they often serve as bearer credentials. If an attacker obtains a valid session identifier, the attacker may be able to impersonate its holder until the session expires or is revoked. This attack is commonly called session hijacking. The consequences depend on additional server checks, the privileges of the session, and whether particularly sensitive actions require renewed authentication.

The Secure attribute restricts transmission to requests the browser considers secure, ordinarily HTTPS. HTTPS uses Transport Layer Security to protect traffic against network eavesdropping and modification. The attribute does not encrypt the cookie inside the browser’s storage, establish that its contents are trustworthy, or stop malicious code already running with sufficient browser access. It is a transmission restriction, not a complete credential-protection system.

Cross-site scripting (XSS) arises when attacker-controlled code executes in a website’s security context. HttpOnly can prevent such code from directly reading a protected cookie, but it does not neutralize XSS. Malicious code may still issue authenticated requests, read application data available to the page, or alter the interface. Content Security Policy, correct output handling, and other script-execution controls address a different layer from cookie confidentiality.

Cross-site request forgery (CSRF) exploits the browser’s automatic attachment of credentials. An attacker-controlled page can cause a victim’s browser to send a request to another site; if cookies accompany it, the destination may mistake the request for an intentional user action. Historically, cross-site forms and embedded resources made this possible without giving the attacker permission to read the response. Common application defenses include unpredictable request tokens and validation of request-origin information. SameSite adds a browser-enforced constraint, but its protection depends on the request context and the attribute value.

Session fixation concerns a different failure: the attacker causes a victim to use a session identifier already known to the attacker, and the application retains it after authentication. Regenerating session identifiers when authentication or privilege changes occur addresses this design problem. Related “cookie tossing” attacks exploit overlapping domain and path scopes to introduce same-named cookies that a server interprets incorrectly. A compromised sibling subdomain can be significant because cookie domain boundaries are broader than strict origin boundaries.

Cookie-name prefixes encode additional requirements in supporting browsers. A name beginning __Secure- requires secure setting conditions and the Secure attribute. A name beginning __Host- additionally requires Path=/ and forbids a Domain attribute, producing host-only scope. These conventions help servers obtain stronger guarantees about how a cookie could have been created, but only when the browser enforces them. They do not replace server-side validation, authorization checks, or sound use of cryptography.

Same-site rules and cross-site contexts

The distinction between same-origin and same-site is central to modern cookie behavior. Under the same-origin policy, an origin is identified by scheme, hostname, and port. A site, for modern schemeful same-site checks, is generally based on the scheme and registrable domain. Thus https://shop.example.com and https://accounts.example.com are different origins but normally the same site, while HTTP and HTTPS versions may be treated as different sites. Ports do not define site boundaries in the same way that they define origin boundaries.

The SameSite attribute determines whether a cookie may accompany requests in cross-site contexts. SameSite=Strict applies the strongest of its three standard settings: cookies are withheld from cross-site requests, including ordinary navigation into the site from an unrelated site. This can affect user-visible behavior. A person following an external link may reach a page without the cookie that would identify an existing signed-in session, even though subsequent same-site requests can include it.

SameSite=Lax permits cookies on qualifying top-level cross-site navigations using safe methods, such as a normal link followed with GET, while generally excluding cross-site subresource requests and unsafe-method navigations such as form submissions using POST. This distinction makes navigation usable while limiting important CSRF patterns. It does not make state-changing GET endpoints safe: an application that changes account data through a supposedly safe request method can still expose itself.

SameSite=None permits cross-site inclusion at the attribute level, but modern browsers require it to be paired with Secure. It does not guarantee that the cookie will be sent. Browser tracking restrictions, user settings, storage partitioning, and request credential modes may independently prevent access. Many browsers treat cookies without an explicit SameSite attribute using a Lax-like default, sometimes with compatibility exceptions. Omission is therefore not a dependable way to request unrestricted cross-site use.

“First-party cookie” and “third-party cookie” describe the relationship between the cookie-using site and the context in which it appears, rather than two fundamentally different wire formats. If a page at news.example embeds a resource from metrics.example, the embedded service operates in a third-party context relative to the top-level page. A cookie belonging to that service might be first-party when the user visits the service directly and third-party when used inside another site.

These distinctions matter for federated login, embedded payment interfaces, support widgets, and other multi-site applications. Being same-site does not guarantee that all participating subdomains are equally trusted, while being cross-site does not imply malicious behavior. SameSite is a request-context control, not a complete expression of organizational trust or user authorization. Applications combining multiple origins must account separately for script access, cookie eligibility, navigation behavior, and the server’s own security decisions.

Tracking, privacy, and legal treatment

A third-party service can use an unpartitioned cookie to recognize the same browser across unrelated websites that embed its resources. For example, if both a news site and a retail site load an advertising endpoint, requests to that endpoint may carry the same identifier. The service can associate the visits without either top-level site receiving the other site’s cookies. This is the technical basis of an important class of cross-site tracking, although the actual information available also depends on request details, browser restrictions, and contractual arrangements.

Cookies can support audience measurement, advertising frequency limits, attribution, and personalization. These activities are not technically identical. Counting visits within one site does not require the same data flows as constructing a profile across many sites. A cookie’s name or lifetime alone does not establish its purpose; a short-lived identifier can still link sensitive events, while a long-lived preference cookie may reveal little beyond a display setting. Data privacy analysis therefore considers actors, purposes, linkability, and retention as well as storage format.

Browsers have introduced different restrictions on cross-site state. Apple’s Safari announced full third-party-cookie blocking in March 2020 as part of its tracking-prevention work. Mozilla introduced Total Cookie Protection in Firefox in 2021 and began enabling it by default for users in 2022, separating cookie state according to the top-level website. These approaches illustrate two broad strategies: blocking access to third-party cookies and partitioning their storage so an embedded service cannot reuse one shared identifier across unrelated top-level sites.

Partitioned cookies provide a more explicit form of contextual separation. The Cookies Having Independent Partitioned State initiative, commonly called CHIPS, uses a Partitioned attribute to request storage keyed partly by the top-level site; it also requires Secure. An embedded service can thereby retain state within a particular embedding site without necessarily obtaining the same cookie state when embedded elsewhere. Partitioning reduces a specific cross-site linking channel, but does not eliminate tracking through account login, URL identifiers, server-to-server sharing, or other techniques.

Legal treatment varies by jurisdiction. In the European Union, Article 5(3) of the ePrivacy Directive, as amended in 2009, regulates storing information on, or accessing information from, a user’s terminal equipment. It includes exceptions for transmission and for storage or access strictly necessary to provide a service explicitly requested by the user. The General Data Protection Regulation separately governs processing when information qualifies as personal data. The rules are not limited to files called cookies; technically different storage mechanisms can fall within the same legal framework.

Consent interfaces and preference records are consequently distinct from the cookie protocol itself. A cookie can store a consent choice, but its presence does not prove that the surrounding collection or processing satisfies applicable law. Conversely, a browser’s acceptance of Set-Cookie is a technical action, not an independent legal determination. Private-browsing modes similarly constrain retention or separate browsing contexts without guaranteeing anonymity to websites or network operators.

Capacity, infrastructure, and operational limits

Cookies are deliberately small, but their implementation limits are not a single universal constant. RFC 6265 describes minimum capabilities expected of general-purpose user agents, including support for at least 4,096 bytes per cookie, 50 cookies per domain, and 3,000 cookies overall. These are implementation-capacity expectations, not promises that every browser will retain every cookie within those figures. Browsers differ in accounting rules, per-domain limits, eviction policies, and the effects of privacy features.

Unlike data kept only in a local database, a cookie can impose a repeated network cost. Every qualifying request may carry it, including requests for images, scripts, and other resources. Several large cookies can therefore enlarge many requests throughout a page load or application session. Narrower domain and path scopes reduce which requests qualify, although architectural separation and application behavior also determine the resulting traffic.

HTTP/2 and HTTP/3 use header-compression mechanisms that can reduce repeated header bytes on a connection, but compression does not make large cookie stores costless. Compression context may not survive new connections, sensitive fields may receive special treatment, and servers still need to accept and process the decoded headers. Web servers, reverse proxies, and load balancers impose header-size limits; excessive cookies can lead to rejected requests, sometimes reported with status 431 Request Header Fields Too Large or a more general error.

Cookies also interact with shared HTTP caching. A Cookie request header does not, by itself, universally forbid caching, and the presence of Set-Cookie is not a complete substitute for explicit cache policy. Responses containing account-specific information require suitable controls such as Cache-Control: private or no-store, according to the intended behavior. Vary: Cookie can distinguish cached responses by cookie headers, but often creates so many variants that cache efficiency falls sharply.

Concurrent activity introduces further complications. Two responses can update the same cookie, and arrival or processing order can determine the value ultimately stored. Separate tabs commonly share a cookie store, so logging out or changing accounts in one tab can affect requests from another. A browser profile, private-browsing context, or partition may provide a separate store, but cookies are not inherently scoped to one tab. Applications requiring per-tab state cannot assume a conventional session cookie supplies it.

Operational diagnosis therefore involves more than inspecting the cookie’s value. Browser developer tools can show response headers, stored attributes, cookies included or excluded from a request, and reasons for rejection. Common failures include a mismatched path, an invalid domain, SameSite=None without Secure, a cross-origin request with the wrong credential mode, or third-party-storage restrictions. These cases produce superficially similar symptoms—such as a session apparently disappearing—while arising from different layers of the browser’s state-management rules.