HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope
HTTP cookies are small values a server asks the browser to store and send back, which is how logins, carts and preferences survive between requests. Learn the Set-Cookie header, every important attribute, how scope and expiry work, and a secure session cookie recipe, with a local server we ran.
- HTTP cookies are set with the
Set-Cookieresponse header and returned in theCookierequest header. - Attributes control scope and safety:
Path,Domain,Max-Age,Secure,HttpOnlyandSameSite. - In our test, a
Securecookie was stored but never sent over plain HTTP, and aPath=/admincookie was sent only to admin pages. - A safe session cookie:
__Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax.
HTTP itself is stateless: every request stands alone, and the server does not remember you between page loads. Yet you stay logged in, your cart keeps its items and the site remembers dark mode. HTTP cookies make that possible. They are also a favourite target for attackers, so the handful of attributes that control them matter for every web developer and tester.
To see cookies on the wire, we wrote a small Python server (Python 3.13.6, standard library only) and a client that stores and returns cookies with http.cookiejar, which follows the same scope and expiry rules as browsers for the attributes it supports. Browser-only behaviour such as SameSite and HttpOnly enforcement follows MDN and the cookie specification and was not run in a browser here.
What are HTTP cookies?
A cookie is a small name-value pair, such as theme=dark, that a server asks the browser to keep. The browser then attaches it to later requests to the same site. Common uses:
- Session management: login sessions, carts, CSRF tokens.
- Personalisation: language, theme, recently viewed items.
- Tracking and analytics: remembering a visitor across visits or sites, which is where privacy law comes in.
How cookies flow between server and browser
Browser Server
| GET /login |
|------------------------------->|
| 200 OK |
| Set-Cookie: session=abc123 |
|<-------------------------------|
| GET /products |
| Cookie: session=abc123 |
|------------------------------->|
The server sends one Set-Cookie header per cookie. The browser sends all matching cookies back in a single Cookie header, separated by semicolons. Only name and value travel back; the attributes are instructions for the browser and are never returned.
What our test server showed
On /login, our server set five cookies:
Set-Cookie: session=abc123; Path=/; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000
Set-Cookie: secure_token=xyz; Path=/; Secure; HttpOnly
Set-Cookie: admin_pref=1; Path=/admin
Set-Cookie: flash=saved; Path=/; Max-Age=1
All five landed in the cookie jar. Then the client visited more pages over plain HTTP, and the server logged what came back:
/login Cookie: None
/products Cookie: session=abc123; theme=dark; flash=saved
/admin/users Cookie: admin_pref=1; session=abc123; theme=dark; flash=saved
/cart Cookie: session=abc123; theme=dark (after 1.2 s wait)
/logout Cookie: session=abc123; theme=dark
/after-logout Cookie: theme=dark
secure_tokenwas stored but never sent, because the connection was not HTTPS.admin_prefappeared only under /admin, because of its Path.flashexpired after one second and disappeared from/cart.sessionvanished after/logoutsentMax-Age=0.
The rest of this guide explains each of those behaviours.
Set-Cookie attributes at a glance
| Attribute | Purpose |
|---|---|
Expires / Max-Age |
When the cookie expires; without them it is a session cookie |
Path |
URL path prefix the cookie is sent to |
Domain |
Host the cookie is sent to, including subdomains when set |
Secure |
Only send over HTTPS |
HttpOnly |
Hide from JavaScript |
SameSite |
Control sending on cross-site requests: Strict, Lax or None |
Partitioned |
Keep a third-party cookie separate per top-level site (CHIPS) |
Session cookies vs persistent cookies
A cookie without Expires or Max-Age is a session cookie: the browser deletes it when the session ends, although modern browsers that restore tabs may keep it longer. A persistent cookie lives until its expiry. Max-Age is a number of seconds from now and wins if both are present; Expires is an absolute date. Our theme cookie used one year (31,536,000 seconds) and flash just one second. Browsers also cap very long lifetimes; Chrome limits new cookies to about 400 days.
Path and Domain: who receives the cookie
Path=/admin means the cookie is sent to /admin and everything below it, such as /admin/users, as our test showed. Path=/ covers the whole site.
Without a Domain attribute, a cookie is host-only: sent back only to the exact host that set it. Setting Domain=example.com widens it to every subdomain, such as shop.example.com and blog.example.com. That is convenient but risky, because any subdomain, including a forgotten or compromised one, can read and overwrite it. Leave Domain off unless you need sharing.
Path is not a security boundary: scripts on other paths of the same origin can still reach cookies that are not HttpOnly through tricks such as iframes.
Secure: HTTPS only
A Secure cookie is only sent over encrypted connections, so attackers on the network cannot read it. Our secure_token proves the rule: stored, but never sent to the plain-HTTP server. Browsers also refuse to let a plain-HTTP page set or overwrite a Secure cookie, with an exception for localhost during development. Every cookie on an HTTPS site should be Secure.
HttpOnly: hidden from JavaScript
HttpOnly cookies are sent with requests but cannot be read through document.cookie. If an attacker injects a script into your page (cross-site scripting), they cannot steal the session token directly. HttpOnly limits the damage but does not fix XSS: the injected script can still send requests as the logged-in user. Use it on every cookie your front-end code does not need to read.
Tip: store session tokens in HttpOnly cookies rather than localStorage, which any script on the page can read.
SameSite: cross-site requests and CSRF
| Value | Sent on cross-site requests? | Typical use |
|---|---|---|
Strict |
Never, not even when following a link from another site | Banking, admin actions |
Lax |
Only on top-level navigations with safe methods, such as clicking a link | Most session cookies; the default in Chrome when unset |
None |
Always; requires Secure |
Embedded widgets, single sign-on, payment iframes |
SameSite is a strong defence against cross-site request forgery (CSRF), where another site tricks the browser into sending a request with your cookies. With Lax, a hidden form on an attacker’s page that POSTs to your bank will not carry the session cookie. Keep CSRF tokens for sensitive actions anyway, as defence in depth. “Site” here means the registrable domain, so app.example.com and api.example.com are same-site but cross-origin, which is why SameSite and CORS solve different problems.
Cookie prefixes: __Host- and __Secure-
Name prefixes make browsers enforce rules:
__Secure-: the cookie must be set withSecurefrom an HTTPS page.__Host-: also requiresPath=/and noDomain, locking the cookie to one exact host so subdomains cannot plant a fake one.
For session cookies, __Host- is the strongest simple choice available.
Deleting a cookie
Set-Cookie: session=; Path=/; Max-Age=0
There is no delete header. You overwrite the cookie with an expiry in the past or Max-Age=0, using the same name, Path and Domain it was set with. A mismatch creates a second cookie instead of removing the first, a common logout bug. In our test the session cookie disappeared right after /logout. Remember to invalidate the session on the server too; deleting the cookie alone does not revoke a stolen copy.
Working with cookies in Python
from http.cookies import SimpleCookie
c = SimpleCookie()
c["session"] = "abc123"
c["session"]["httponly"] = True
c["session"]["secure"] = True
c["session"]["samesite"] = "Lax"
c["session"]["path"] = "/"
c["session"]["max-age"] = 3600
print(c.output())
# Set-Cookie: session=abc123; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure
p = SimpleCookie(); p.load("session=abc123; theme=dark; lang=en-IN")
print({k: v.value for k, v in p.items()})
# {'session': 'abc123', 'theme': 'dark', 'lang': 'en-IN'}
c2 = SimpleCookie(); c2["note"] = "hello world; semicolon"
print(c2.output())
# Set-Cookie: note="hello world\073 semicolon"
The last line shows why special characters need care: semicolons separate attributes, so Python quoted and escaped the value. Safer still is to keep values simple, or URL-encode or Base64-encode them first. For testing APIs that use cookies, the Python requests library keeps a cookie jar in each Session.
Size limits and privacy
- Browsers support at least about 4 KB per cookie and dozens of cookies per domain; exceed them and cookies are silently dropped.
- Every cookie is sent with every matching request, including images and scripts, so large cookies slow every page. Keep them small and store data server-side.
- Third-party cookies are blocked or restricted by most major browsers, so cross-site tracking increasingly relies on other methods.
- In the EU and many other regions, non-essential cookies need user consent.
For tokens that must travel between services rather than browsers, compare cookies with JWTs.
A secure session cookie recipe
Set-Cookie: __Host-session=<random 32 bytes>; Path=/; Secure; HttpOnly; SameSite=Lax
- Use a long random value, not user data, and look the session up on the server.
- Rotate the session ID after login to prevent session fixation.
- Expire sessions on the server after inactivity, not just in the cookie.
- Test logout: the cookie is gone and the old value no longer works.
- Check headers in API tests; our API testing with Python guide shows how.
Final thoughts
HTTP cookies are simple key-value pairs with powerful rules attached. Path, Domain and Max-Age decide where and how long a cookie travels; Secure, HttpOnly and SameSite decide how safely. Our local test showed each rule in action, from a Secure cookie that never left the jar over HTTP to a flash message that expired on time. Use the secure recipe for sessions, keep cookies small, and test logout properly. For how browsers reuse responses, see HTTP caching.
Frequently asked questions
What is an HTTP cookie?
It is a small name and value pair that a server stores in the browser with the Set-Cookie header. The browser sends it back with later requests, which lets sites remember logins, carts and settings.
What does HttpOnly mean on a cookie?
HttpOnly stops JavaScript from reading the cookie through document.cookie. It is still sent with requests, so it protects session tokens from being stolen by injected scripts.
What is the difference between SameSite Lax and Strict?
Strict never sends the cookie on requests that start from another site. Lax sends it only when the user follows a normal link to your site, which keeps people logged in while still blocking most cross-site forgery.
How do I delete a cookie?
Send a Set-Cookie header with the same name, path and domain and either Max-Age set to 0 or an expiry date in the past. The browser then removes it.
What is the difference between a session cookie and a persistent cookie?
A session cookie has no expiry and is removed when the browser session ends. A persistent cookie has Max-Age or Expires and stays until that time passes.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.