HTTP cookies are small pieces of data that a server sends to a user’s browser. The browser stores the data and returns it to the same server with later requests. Cookies allow servers to maintain state across the otherwise stateless HTTP protocol.
Whenever a server wants to keep information on the client’s end, it includes a Set-Cookie header in its HTTP response. The browser saves the cookies as per the attributes supplied with them.
Cookies are defined in RFC 6265 (HTTP State Management Mechanism). They remain the primary mechanism for session management, personalization, and certain forms of tracking on the web.
How Do HTTP Cookies Work?
The cookie mechanism involves two headers and a set of storage and matching rules implemented by the user agent, which is usually a web browser.
- The server starts sending one or more Set-Cookie headers in an HTTP response.
- The browser parses each header, saves up the cookie name-value pair together with its relevant attributes, and applies any security or scope restrictions.
- For the requests that match the origin, path, and scheme later on, the browser includes the relevant cookies in a Cookie request header.
- The server reads the Cookie header and uses the values to restore session state or other information.
Here’s usually what an exchange looks like:
Server → Browser
text
Set-Cookie: sessionId=31d4d96e407aad42; Path=/; Secure; HttpOnly; SameSite=Lax
Browser → Server (later request)
text
Cookie: sessionId=31d4d96e407aad42
The browser decides which cookies to send based on the request URL, the cookie’s Domain and Path attributes, the Secure flag, and the SameSite policy.
Cookies that have expired or been deleted are never sent. Cookies are origin-oriented by default. A cookie that’s set by https://example.com isn’t automatically available to https://other.example.com unless the Domain attribute explicitly allows it.
Key Cookie Attributes
Every single cookie has a name-value pair plus optional attributes that control its lifetime, scope, and security.
Name and Value
The name and value form the core of the cookie. Names and values are restricted to a certain set of characters defined in the specification. A cookie is uniquely identified by the combination of its name, domain, and path (and, in newer implementations, its partition key).
Expires and Max-Age
These attributes control how long the browser keeps the cookie.
- Expires takes an absolute HTTP-date.
- Max-Age takes a number of seconds from the moment the browser receives the cookie.
If both of these are there, Max-Age takes precedence. If neither is there, the cookie is a session cookie and is deleted when the browsing session ends.
Domain and Path
- The Domain field determines which hosts can be allowed to accept the cookie. When absent, the cookie is restricted to only the host from which it was set (host-only), and will not be sent to subdomains.
- The Path field sets the limit on the cookie based on URL path prefixes. The default is the path of the request setting the cookie.
Secure
If Secure is defined, then the browser will send the cookie over an encrypted connection only. A cookie that is tagged as Secure cannot be set and transmitted over HTTP except for localhost testing purposes.
HttpOnly
HttpOnly prevents client-side JavaScript from reading the cookie through the document. or the Cookie Store API. The cookie is still sent automatically with the HTTP requests. This reduces the impact of cross-site scripting (XSS) attacks that attempt to steal session tokens.
SameSite
The SameSite attribute determines when the cookie will be included in cross-site requests. The value for SameSite can either be:
- Strict – which is included in same-site requests.
- Lax – included in same-site requests and top-level navigations such as clicking on a link. This is the default value in most browsers if the attribute is not specified.
- None – included in same-site requests and cross-site requests but must include the Secure attribute.
The SameSite attribute protects against cross-site request forgery (CSRF).
Cookie Name Prefixes
The majority of modern browsers have additional compliance for cookies whose name starts with certain phrases and prefixes:
- __Secure- — requires the Secure attribute and must be set over HTTPS.
- __Host- — requires Secure, Path=/, and no Domain attribute. This creates a cookie locked to a single host.
These prefixes allow servers to declare stronger guarantees that the browser will enforce.
Session Cookies and Persistent Cookies
Cookies fall into two major lifetime categories.
Session cookies have no Expires or Max-Age attribute. The browser deletes them when the session ends, usually when the browser or tab is closed.
Persistent cookies include an Expires date or a Max-Age value. The browser stores them on disk and returns them until they expire or are explicitly deleted.
The decision to use either a session cookie or a persistent cookie is based on how long the information needs to be stored. The typical application of a session cookie is an authentication token that must expire if the browser is closed.
Common Uses of HTTP Cookies
HTTP cookies support multiple well-established web functions.
Session Management
The server assigns a session ID to the cookie once the user is authenticated. Any future requests will have the session ID automatically sent with the request, enabling the server to identify which user session the request belongs to without any authentication required.
Personalization
User preferences are stored in cookie files so that they can be retained by websites on subsequent visits.
Stateful Interactions
Shopping carts, multi-step forms, and similar features that need to remember client-side choices across page loads are dependent on cookies when server-side storage isn’t sufficient.
Cookies stay appropriate when the data is available to the server on every request. For purely client-side storage that shouldn’t be sent to the server, other browser APIs like localStorage or sessionStorage are usually preferred.
Limitations and Security Considerations
Cookies have inherent constraints and security implications that developers should account for.
Size and Quantity Limits
There are restrictions that browsers place on the maximum number of cookies that can be set per domain, and also on the size of individual cookies (typically about 4 KB for name and value).
Automatic Transmission
Since cookies are sent with the matching requests, they increase the request size. Storing large amounts of data in cookies is inefficient compared with the modern client-side storage APIs.
Security Risks
- Unsecure cookies can be accessed without encryption.
- Cookies that do not have HttpOnly set can be accessed by any malicious script when an XSS attack is possible.
- Cookies with large domain/path attributes or the SameSite=None attribute are vulnerable to cross-site attacks.
- Cookie values can be seen by a server and anyone else who is able to access traffic or browser storage.
Proper use of the Secure, HttpOnly, SameSite, and prefix attributes significantly reduces these risks, but does not eliminate them. Cookies should never store sensitive information in plaintext.
Privacy and Third-Party Cookies
Third-party cookies have been used over time for cross-site tracking. Browser vendors have restricted or planned to phase out unrestricted third-party cookies, and feature partitioned cookies (CHIPS) to provide more privacy-preserving alternatives for legitimate embedded use cases.