# Cookie Security Attributes: Secure, HttpOnly, SameSite, and Scope

> Set Secure, HttpOnly, SameSite, Domain, Path, Max-Age, and cookie prefixes correctly, block tossing and CSRF, and verify browser behavior.

**Quick answer:** Cookie security is decided by attributes, not by the value. Set Secure and HttpOnly on session cookies, choose SameSite=Lax by default and None; Secure only for genuine cross-site flows, prefer the __Host- prefix over a Domain attribute, keep sessions short with Max-Age, rotate identifiers after login, and add a CSRF token plus an Origin check for state-changing requests.

## Key takeaways

- Secure protects transport, HttpOnly blocks script reads, SameSite limits cross-site sends, and Domain plus Path define scope; none of them encrypts the value.
- A host-only __Host- cookie is the safest default: it forbids Domain, requires Path=/ and Secure, and cannot be overwritten by a sibling subdomain.
- SameSite=Lax blocks most cross-site writes but not top-level GET navigation, so state-changing requests still need a CSRF token and an Origin check.
- Cookie tossing and subdomain shadowing work because a compromised sibling can set parent-domain cookies; wildcard Domain values are invalid and prefixes close that hole.
- Session identifiers must be rotated at login, stored hashed server-side, bounded by idle and absolute timeouts, and regenerated after privilege changes.

---

Every cookie is a small piece of state that the browser attaches automatically, and its safety comes from attributes rather than from the value inside it. A cookie with no flags travels over plaintext HTTP, is readable by any script on the page, and can be triggered by another site. Each attribute closes one of those doors: `Secure` restricts transport, `HttpOnly` restricts script access, `SameSite` restricts cross-site requests, and `Domain` plus `Path` restrict where the cookie is sent. None of them encrypts anything. The browser enforces what it can, but the server still owns authorization, session validation, and revocation.

## What cookie attributes actually control

A server sends `Set-Cookie` in a response; the browser stores name, value, and attributes, then sends only `Cookie: name=value` on later requests. Attributes are never echoed back, which is why a misconfigured cookie can look correct in server logs while behaving incorrectly in the browser. They divide into five jobs: transport (`Secure`), script visibility (`HttpOnly`), request inclusion (`SameSite`), scope (`Domain`, `Path`), and lifetime (`Max-Age`, `Expires`). Two newer mechanisms, the `__Host-` and `__Secure-` name prefixes and the `Partitioned` attribute, change how the browser stores and accepts a cookie.

Attributes are enforced by the user agent, not by your framework. A server that reads `Cookie` headers must therefore validate the session identifier, check its own expiry record, and never infer identity from a cookie merely being present. Treat the value as an opaque handle to server state, not as a container for roles, prices, or personal data. Anyone with access to the device, a browser extension, or a debugging proxy can read every non-`HttpOnly` cookie and inspect the rest in the profile.

## Secure, HttpOnly, and cookie scope with Domain and Path

`Secure` means the cookie is sent only over HTTPS. It protects against passive network capture and against a downgrade to plaintext, but it does not hide the value from JavaScript, extensions, or server logs. On modern browsers `Secure` is also required for `SameSite=None`; a `None` cookie without `Secure` is rejected outright, which is one of the most common silent login failures.

`HttpOnly` removes the cookie from `document.cookie`. It raises the cost of XSS because injected script cannot exfiltrate the session identifier directly, but the script can still send authenticated requests from the page, so XSS remains a full compromise of the user's session while the tab is open.

`Domain` controls sharing across hosts. With no `Domain`, the cookie is host-only: set by `app.example.com`, returned only to `app.example.com`. With `Domain=example.com`, every subdomain receives it, including a marketing site, a status page, or a forgotten staging host. A leading dot is ignored by modern browsers, and a wildcard such as `Domain=*.example.com` is not valid syntax; browsers reject it or store a literal host, neither of which produces the intended behavior. Omit `Domain` unless sibling hosts genuinely need the cookie.

`Path` sets a prefix match, not an access-control rule. A cookie with `Path=/account` is sent to `/account` and `/account/settings` but not to `/login`. Because any same-origin response can set a cookie for `/`, `Path` cannot protect a cookie from same-origin code, and two cookies with the same name and different paths can coexist, arriving in an order the server may not expect.

| Attribute | What it controls | Safe default | Common failure |
| --- | --- | --- | --- |
| `Secure` | transport | always set | sent over HTTP after a downgrade |
| `HttpOnly` | script access | session cookies only | tokens readable by XSS |
| `SameSite` | cross-site requests | `Lax` | `None` without `Secure` |
| `Domain` | host scope | omitted, host-only | wildcard or parent domain |
| `Path` | request path scope | `/` for the app | used as authorization |
| `Max-Age` | relative lifetime | short for sessions | omitted, so a session cookie |
| `Expires` | absolute lifetime | fallback only | conflicting with `Max-Age` |
| `__Host-` | name-enforced scope | session and CSRF cookies | rejected after adding `Domain` |
| `Partitioned` | storage partition | embedded third-party widgets | assumed to replace `SameSite` |

## SameSite: Lax, Strict, and None in practice

A site is scheme plus registrable domain. `app.example.com` and `www.example.com` are the same site even though they are different origins, so `SameSite` does not separate subdomains from each other. It governs whether a cookie is attached when the request is initiated by another site.

`SameSite=Strict` withholds the cookie on every cross-site request. Following a link from an email to a logged-in dashboard arrives without the session cookie, so the user may see a login page and then a second navigation. `SameSite=Lax` sends the cookie on safe top-level navigation, such as a followed link or a typed URL, but not on cross-site `POST`, `fetch`, iframe loads, or subresource requests. `Lax` is the browser default when the attribute is absent, but relying on an implicit default is fragile because older clients and non-browser agents differ.

`SameSite=None` allows cross-site sending and requires `Secure`. It is correct for SSO callbacks, payment iframes, and embedded widgets, and it must be paired with CSRF defenses because the cookie now travels on requests initiated elsewhere. Do not set `None` to make a broken integration work: the usual cause is a cross-origin XHR that should be proxied through the same site, and widening the cookie exports the session to every embedding page.

## Session cookies, Max-Age, and Expires

A session cookie has neither `Max-Age` nor `Expires`. The browser drops it when the session ends, but session restore and mobile browsers keep it for days, so "session cookie" describes storage behavior, not security. A persistent cookie carries `Max-Age` in seconds or `Expires` as an absolute date. `Max-Age` wins when both are present, and a zero or negative value deletes the cookie immediately.

```http
HTTP/1.1 204 No Content
Set-Cookie: __Host-sid=61f2c9a7d0e84b1f9a3c5e7d2b4a6c8e; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800
Set-Cookie: __Host-csrf=9d41ab7c3e5f8062a1b4d7c9e2f30518; Path=/; Secure; SameSite=Lax; Max-Age=1800
Set-Cookie: theme=dark; Path=/; Secure; SameSite=Lax; Max-Age=31536000
```

The session and CSRF cookies are host-only because `Domain` is absent, and the CSRF value remains readable so the front end can echo it in a header. The preference cookie is allowed to live longer because losing it costs nothing.

Use `Max-Age` for new code because it is relative and immune to client clock skew; keep `Expires` only for clients that do not understand `Max-Age`. Set the shortest lifetime that still supports the flow: fifteen to sixty minutes for an administrative session, days at most for a low-risk consumer session. Renewal belongs on the server, where the session record can enforce an idle timeout and an absolute timeout independently of what the browser stores.

A session cookie is not automatically safer than a persistent one. The cookie file, session restore, and browser sync can all preserve it. What limits exposure is the server-side expiry and rotation policy, not the absence of an expiration attribute.

## `__Host-` and `__Secure-` prefixes, cookie tossing, and subdomain shadowing

The `__Secure-` prefix requires the cookie to be set over HTTPS with the `Secure` attribute. The `__Host-` prefix goes further: `Secure`, no `Domain` attribute, and `Path=/`. The browser rejects any cookie that violates those rules. Because a `__Host-` cookie is host-only, a sibling subdomain cannot overwrite it for the parent domain, which makes it the right name for session and CSRF cookies on an application host.

Cookie tossing exploits the absence of that protection. In an application that names its session cookie `sid` rather than `__Host-sid`, an attacker who controls or compromises `blog.example.com` sets `Domain=example.com` with that same name. The browser now holds two cookies with the same name, ordered by path length and creation time, and different server frameworks read the first or the last. If the attacker's value wins, the victim is pinned to the attacker's session, or the attacker's request is authenticated as the victim.

Subdomain shadowing is the broader version: dangling DNS records, wildcard DNS, user-generated content on `*.example.com`, or a forgotten vendor host all give an outsider a same-site position. Defenses are structural: use `__Host-` for session cookies, omit `Domain` wherever possible, keep untrusted content off subdomains, reject duplicate cookie names at the edge, and validate that a session identifier matches the expected format before looking it up. A wildcard `Domain` value does not solve this; it is invalid and only adds confusion.

## CSRF, readable cookies, and why JWTs do not belong there

Cookies are attached automatically, which is the definition of CSRF: another site causes the browser to send an authenticated request. `SameSite=Lax` blocks most cross-site writes, but not top-level GET navigation, and a state change behind a GET is a bug regardless. The durable defense is a random CSRF token tied to the session, compared on every state-changing request, plus an `Origin` or `Sec-Fetch-Site` allowlist. The double-submit pattern keeps the token readable by JavaScript and compares cookie against header; that is one of the few legitimate reasons a cookie must not be `HttpOnly`.

Storing a JWT in a readable cookie is a common mistake. If the cookie is not `HttpOnly`, any XSS reads it and the token is stolen. If it is `HttpOnly`, script cannot read it, but the browser still attaches it automatically, so CSRF applies and XSS can still act through the page. A long-lived bearer token in a cookie also inherits every revocation problem of a cookie session, without the server-side control that an opaque session identifier provides. Prefer an opaque session identifier in a `__Host-` cookie and keep the token server-side, or use a short-lived access token with rotation and a strict CSP.

## Size limits, partitioning, and CHIPS

Browsers allow roughly 4 KB per cookie, counting name, value, and attributes, and a few dozen to a few hundred cookies per domain depending on the browser. Exceeding either limit causes silent eviction or rejection: the application sees a missing cookie, not an error. Never shard a session across many cookies or store profile data in them. If you need more state, keep an identifier in the cookie and the data in a server-side store or a signed, encrypted token designed for the purpose.

`Partitioned` implements CHIPS: the cookie is stored under a key that includes the top-level site, so an embedded widget gets a separate jar per embedding site and cannot use one partition's identifier to recognize the user on another. It requires `Secure` and is intended for genuine third-party embeds. It does not replace `SameSite=None`, does not make the cookie first-party, and does not remove the need for CSRF protection. It also multiplies the places a session can exist, so logout must clear the partitioned cookie as well as the first-party one.

Third-party cookie restrictions vary by browser and by user setting. Design embeds to fail closed: if the partitioned cookie is absent, show a signed-out widget rather than falling back to a less protected identifier.

## Rotation, revocation, and long-lived sessions

A session identifier must be generated with a cryptographically secure random source and carry at least 128 bits of entropy. The [random token generator](/tools/random-token-generator) produces values in that range; never use a counter, a timestamp, or a UUID that leaks structure. Store only a hash of the identifier server-side, so a database leak does not hand over live sessions.

Rotate the identifier at login to prevent session fixation, again after any privilege change, and periodically for long sessions. Rotation means issuing a new value, moving the server-side record, and invalidating the old one; simply changing the cookie without revoking the old record leaves the stolen copy valid. Enforce an idle timeout and an absolute timeout, invalidate on logout, and revoke every session on password change or suspected compromise.

Long-lived sessions without rotation are the quiet failure: a cookie captured once remains valid for months, and the server has no event that would stop it. For APIs, rotate refresh tokens with reuse detection; a replayed refresh token invalidates the whole token family. Bind sessions to coarse device signals only as a risk input, never as the sole check, because shared networks and mobile browsers produce false positives.

## Verification checklist with concrete pass criteria

Verify the headers first, then the browser. Start with a real login response from production; a local server with relaxed flags proves nothing.

```bash
# 1. Inspect every cookie a login response sets
curl -sS -D - -o /dev/null -c jar.txt -X POST https://app.example.com/login | grep -i '^set-cookie:'

# 2. Replay the jar against a state-changing endpoint with a foreign Origin
curl -sS -o /dev/null -w '%{http_code}\n' -b jar.txt \
  -H 'Origin: https://evil.example' -X POST https://app.example.com/account/email
```

The [HTTP headers analyzer](/tools/http-headers) parses the first response and flags missing attributes. Curl cannot emulate `SameSite`, because it does not implement the browser's site model, so the second command only tests server-side `Origin` enforcement; cross-site behavior must be checked in a browser.

In DevTools, open Application, Cookies, and read every flag. Type `document.cookie` in the console: an `HttpOnly` session cookie must be absent. Load the app inside a cross-site iframe or a second local origin and confirm which cookies arrive. Then treat a check as passed only when every row passes.

| Check | How to test | Pass criteria |
| --- | --- | --- |
| Session cookie flags | Application panel on the login response | `Secure`, `HttpOnly`, `SameSite=Lax`, `__Host-` name, host-only |
| No readable session | `document.cookie` in the console | session identifier absent; only CSRF or preference values appear |
| Cross-site write | POST from another origin with the cookie present | rejected without a valid CSRF token and allowed `Origin` |
| Prefix integrity | Attempt to set the cookie with a `Domain` attribute | browser rejects the `__Host-` cookie |
| Expiry | Inspect `Max-Age` and the Expires column | short lifetime, server-side idle and absolute timeouts enforced |
| Partitioning | Embedded widget in two top-level sites | separate partitioned values; logout clears both |
| Rotation | Log in twice and compare identifiers | value changes, old identifier rejected by the server |

The [HTTP request workbench](/tools/http-request) replays a captured request with exact headers when a proxy or framework rewrites them. Record the result in the release checklist: attribute regressions are invisible in unit tests and obvious in a cookie dump.

## Failure modes and production rules

The expensive mistakes repeat:

- A wildcard or parent `Domain` used for convenience, exposing the session to every subdomain.
- `SameSite=None` without `Secure`, so the browser drops the cookie and the login loops.
- A JWT stored in a readable cookie, or a long-lived bearer token with no server-side revocation.
- A session-bearing cookie with no `HttpOnly`, no rotation, and a one-year `Max-Age`.
- Relying on `SameSite` alone while state-changing GET requests remain enabled.
- Using `Path` as authorization and assuming a cookie scoped to `/admin` protects the admin API.
- Treating a session cookie as safer than a persistent one when the server never expires either.
- Letting a compromised or neglected subdomain set parent-domain cookies that shadow the real session.
- Failing to delete the cookie on logout, or deleting it only in the browser while the server record survives.
- Storing roles, prices, or personal data in the cookie and trusting it without a signature and server check.

The rules are short. Default to a host-only `__Host-` session cookie with `Secure`, `HttpOnly`, `SameSite=Lax`, and a short `Max-Age`. Omit `Domain` unless sibling hosts truly need it, and never use a wildcard. Add a CSRF token and an `Origin` check for state-changing requests, and reserve `SameSite=None; Secure` for genuine cross-site embeds. Rotate identifiers on login and privilege change, store hashes server-side, and revoke on logout. Keep cookies under 4 KB and out of the data-storage business. Verify attributes from production with curl and a browser, and re-check them after every authentication change.

## Frequently asked questions

### Should every cookie be marked Secure and HttpOnly?

Mark every cookie Secure, including analytics and preferences, because plaintext transport leaks it. Mark HttpOnly only on cookies JavaScript never needs; the CSRF token is often readable by design, while the session identifier should not be.

### What is the difference between SameSite=Lax and SameSite=Strict?

Strict withholds the cookie on every cross-site request, including a link click from another site, so users can appear logged out on arrival. Lax sends it on safe top-level navigation such as a followed link but not on cross-site POST, fetch, or iframe loads, which is the better default.

### Why does the browser reject my __Host- cookie?

A __Host- cookie must be set over HTTPS, carry Secure, omit Domain entirely, and use Path=/. Any Domain attribute, a different path, or a plaintext origin causes the browser to discard it silently, which usually shows up as a login loop rather than an error.

### Can I store a JWT in an HttpOnly cookie?

Yes, but HttpOnly only removes the JavaScript read path; it does not stop XSS from issuing authenticated requests or remove CSRF risk, because the browser attaches cookies automatically. Keep the token opaque to scripts, add SameSite and CSRF defenses, and prefer a server-side session when you need instant revocation.

### Does the Partitioned attribute replace SameSite=None?

No. Partitioned, part of CHIPS, stores an embedded third-party cookie under the top-level site so it cannot be reused across sites. It still requires Secure and is usually combined with SameSite=None; it narrows tracking, it does not replace CSRF or session controls.

## References

- [RFC 6265bis: Cookies: HTTP State Management Mechanism](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/)
- [MDN: Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie)
- [OWASP: Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
- [OWASP: CSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)

---

- Canonical: https://www.jsonmind.com/guides/cookie-security-attributes
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: http-headers, http-request, random-token-generator