How Cookies Work in HTTP
Follow a cookie from Set-Cookie to the next request and learn what each attribute does for sessions, privacy and security.
Key takeaways
- The server sets a cookie with
Set-Cookie, and the browser sends it back automatically on matching requests. -
DomainandPathdecide where a cookie goes, whileExpiresandMax-Agedecide how long it lasts. -
Secure,HttpOnlyandSameSiteare the attributes that protect sign-in cookies. - Third-party cookies come from a different site than the page you are visiting, and browsers increasingly restrict them.
- Cookies hold only small amounts of data and are not a safe place for secrets in readable form.
A cookie is a small named value that a website asks your browser to keep and send back. The server creates it with a Set-Cookie response header, and the browser returns it in a Cookie request header whenever a later request matches the cookie's rules.
That round trip exists because HTTP forgets everything between requests. Cookies are how a site keeps you signed in, remembers a shopping cart or recalls your language. The same mechanism can follow people across sites, which is why browsers have steadily added limits.
The round trip
Here is a sign-in, reduced to its headers.
The response that creates the cookie might include:
Set-Cookie: sid=Kq3x9vTz; Path=/; Secure; HttpOnly; SameSite=Lax The next request carries only the name and value:
Cookie: sid=Kq3x9vTz The attributes stay in the browser. The server does not get them back, so it cannot tell from the request alone when the cookie expires or which flags it had.
Each cookie needs its own Set-Cookie line, while the browser combines all matching cookies into one Cookie header separated by semicolons. The specification for this behavior is RFC 6265, with later refinements such as SameSite developed in successor drafts and shipped by browsers.
Sessions: identifier or contents
A site can use a cookie in two broad ways.
A server-side session puts only a long random identifier in the cookie. The details live on the server. Signing someone out is easy: delete the record, and the identifier becomes meaningless.
A self-contained token puts the data itself in the cookie, signed so the server can detect tampering. This saves a lookup, but signing is not encryption, so anyone holding the cookie may be able to read it. Revoking it before expiry takes extra machinery. JSON Web Tokens are a common format.
Either way, the cookie is a bearer credential. Whoever has it can usually act as you until it expires, which is why the protective attributes matter so much.
Anatomy of a Set-Cookie header
You can paste any header into the Set-Cookie attribute explainer to check your reading of it.
Scope: where a cookie goes
Without a Domain attribute, a cookie is host-only. One set by app.example.com returns only to that exact host. Adding Domain=example.com widens it to example.com and every subdomain. A server cannot set cookies for an unrelated domain, and browsers use a public suffix list to stop a site from claiming something as broad as .com.
Path narrows by URL prefix. It helps organization but is a weak security boundary, because pages on the same origin can generally reach each other.
Cookies also ignore port numbers: services on different ports of one hostname share them. Keep that in mind when running several applications on one machine.
Lifetime
A cookie with neither Expires nor Max-Age is a session cookie, discarded when the browser session ends. Browsers that restore previous tabs may restore these too, so do not rely on closing the window.
With Expires (a date) or Max-Age (seconds), the cookie persists. If both appear, Max-Age wins. Browsers may cap very long lifetimes and may delete cookies earlier to save space or protect privacy.
To delete a cookie, the server sends it again with the same name, domain and path and a lifetime of zero:
Set-Cookie: sid=; Path=/; Max-Age=0 If the domain or path does not match, you create or expire a different cookie and the original stays.
Security attributes
Secure keeps the cookie off unencrypted connections, where anyone on the path could copy it. Combine it with HSTS.
HttpOnly prevents scripts from reading the cookie. If a page suffers a script injection flaw, the attacker's code cannot simply copy the session value, though it may still act within the page.
SameSite controls requests that start on another site:
| Value | When the cookie is sent cross-site |
|---|---|
Strict | Never, including when following a link in |
Lax | On top-level navigation with safe methods such as GET |
None | Always, and it must also be Secure |
This is a major defense against cross-site request forgery, where another site causes your browser to submit an action using your cookies. Defaults differ between browsers, so set the value explicitly, and keep anti-forgery tokens for sensitive actions.
Two name prefixes add guarantees the browser enforces. A name starting __Secure- is accepted only with Secure from a secure origin. A name starting __Host- must also have Path=/ and no Domain, which ties it to one host.
First-party and third-party cookies
Cookies belong to the site that receives them. When you visit a news page that loads an image or frame from ads.example.net, any cookie that request involves is a third-party cookie. Because the same outside domain can appear on many sites, a consistent identifier lets it connect your visits.
Browsers respond in different ways: some block third-party cookies by default, some partition them so each top-level site gets a separate jar, and some leave the choice to settings. A Partitioned attribute lets an embedded service ask for a per-site cookie. Policies keep changing, so test in the browsers your visitors use. The history and debate are in third-party cookies and their future.
Cookies are also only one storage method. Cookies, pixels and local storage compares them. Privacy laws in many places require notice or consent for non-essential storage, and the rules vary by jurisdiction.
Handling sign-in sessions safely
If you run a site with accounts, a few habits close the common gaps.
- Generate identifiers randomly. Use the session facility of a maintained framework. Never build the value from a user number, a timestamp or an email address.
- Issue a new identifier at sign-in. This defeats session fixation, where a value planted before login would otherwise become authenticated.
- Expire on the server. The browser's expiry is only a request to the browser. Enforce both an idle timeout and a maximum age in your session store.
- Delete on sign-out. Remove the server record as well as clearing the cookie.
- Ask again for sensitive actions. Changing a password or payment detail deserves a fresh check.
- Offer a list of active sessions where the stakes justify it, so people can end ones they do not recognize.
Visitors have a part too. Signing out on shared computers and being careful about browser extensions both reduce the chance that a session is copied. A stolen session cookie can get past a password and even a second factor, because those checks already happened.
When cookies do not arrive
Cookie bugs are common and usually come from one mismatch. Developer tools often explain why a cookie was rejected or withheld, so look there first.
| Symptom | Likely cause |
|---|---|
| Cookie never stored | Secure set over plain HTTP, or an invalid Domain |
SameSite=None ignored | Secure is missing |
| Missing on a subdomain | No Domain, so it is host-only |
| Missing after arriving from another site | SameSite=Strict |
| Missing on script requests to another origin | Credentials not included in the request, or CORS not allowing them |
| Two cookies with one name | Different domain or path values |
Requests made with fetch to another origin send no cookies unless the code asks for credentials and the server allows it. That interaction is explained in CORS explained.
Limits and performance
Browsers restrict both size and number. A common floor is about 4,096 bytes per cookie, with a per-domain count limit. Every matching cookie rides along on every request, including images and stylesheets on the same host, so large cookies slow things down. Store preferences that only scripts need in local storage, and large data on the server.
Cookies and shared caching need care too. A response containing Set-Cookie or personal content should not be stored by a shared cache and handed to someone else. Mark it private or no-store.
Managing cookies as a visitor
In developer tools, the Application or Storage panel lists each cookie with its domain, expiry and flags. Browser settings let you clear cookies for one site or all of them; clearing signs you out. What clearing cookies fixes and erases explains the side effects.
From a terminal, curl can keep a cookie jar for testing your own site:
curl -c jar.txt -b jar.txt -i https://www.example.com/ -b sends cookies from the file and -c writes new ones to it. Treat that file like a password if it holds a real session.
Common questions
Can a cookie run a virus?
No. A cookie is a piece of text that is not executed. The risk is theft or misuse of the value, such as a stolen session.
Why am I signed out at random?
Likely causes include short session lifetimes, a cleaner or privacy setting deleting cookies, a mismatch between www and the bare domain, or several servers that do not share session records.
Do I need cookies for a simple site?
Often not. A static informational site with no sign-in or cart can work without setting any, which also simplifies your privacy obligations.