Join our Newsletter — 33% off our NHI Course
Home› Guides› Cookie Security Guide: Setting Secure, HttpOnly, SameSite and…
Guide Web & API Security

Cookie Security Guide: Setting Secure, HttpOnly, SameSite and Prefixes Correctly

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 17 min read
On this page

Most web sessions are only as safe as the attributes on one Set-Cookie header, and those attributes are routinely left at framework defaults that leak the cookie to scripts, subdomains or cross-site requests. A session cookie is a bearer credential: whoever presents it is the user, MFA included. This guide goes attribute by attribute through Secure, HttpOnly, SameSite, Domain, Path, Expires and Max-Age, the __Secure-, __Host- and __Http- name prefixes, and partitioned cookies (CHIPS), then gives a recommended baseline per cookie type, a rollout plan, test methods and framework mappings. It is written for application security engineers, web developers and reviewers who own session handling. Response headers in general are covered in the Security Headers Guide; this page goes deeper on cookies only.

Key takeaways

  • Use the __Host- prefix for session cookies unless the cookie genuinely must be shared across subdomains; it forces Secure, Path=/ and no Domain, and the browser enforces it.
  • Set SameSite explicitly on every cookie, because the browser default is not uniform and Lax-by-default has a two-minute POST exception; treat SameSite as CSRF defence in depth, not a replacement for tokens.
  • HttpOnly stops script reads, not session theft: infostealers lift cookies from disk and an XSS payload can still ride the session, so pair it with short lifetimes and server-side revocation.
  • Domain widens exposure and Path is not a boundary: omit Domain to keep a cookie host-only, and isolate applications of different trust levels on different hostnames.
  • Logout and expiry belong on the server: deleting a cookie in the browser does nothing to a stolen copy, so invalidate the session record and keep idle and absolute timeouts server-side.

What each attribute actually does

The cookie specification is being revised: the IETF draft draft-ietf-httpbis-rfc6265bis (version 22, December 2025) was in the RFC Editor queue as a Proposed Standard when checked on 27 October 2026 and will obsolete RFC 6265 once published. Browsers already implement most of it. The table summarises behaviour as documented by MDN and the draft.

AttributeEffectSecurity note
SecureCookie is sent only over HTTPS (localhost is an exception for development); HTTP pages cannot set a Secure cookieRequired on every cookie on an HTTPS site; without it a single plain HTTP request leaks the value
HttpOnlyHidden from document.cookie; still sent with fetch() and XMLHttpRequestBlocks script reads after XSS, does not block requests made by injected script
SameSite=StrictSent only on same-site requestsStrongest CSRF mitigation; breaks login state when users arrive from links on other sites
SameSite=LaxSame-site requests plus cross-site top-level navigations with safe methods (GET); not sent on cross-site POST, iframes, images or fetchGood default for session cookies on most sites
SameSite=NoneSent on all requests, cross-site included; must be combined with SecureOnly for cookies that must work in third-party embeds; needs CSRF tokens
DomainAbsent: host-only. Present: sent to that domain and all its subdomains; a public suffix is rejectedSetting it is a widening, never a narrowing
PathSent only for matching URL paths (default: the directory of the setting URL)MDN states plainly that Path is not a security boundary; scripts on the same origin can read other paths
Expires / Max-AgeAbsent: session cookie. Present: persistent cookie stored on disk. Max-Age wins if both are set; zero or negative deletesrfc6265bis caps lifetimes at no more than 400 days
PartitionedStores the cookie in a jar keyed by the top-level site (CHIPS); requires SecureLets embeds keep state without becoming a cross-site tracker

Two size rules from rfc6265bis matter in practice: a cookie whose name plus value exceeds 4096 octets is ignored, and an attribute value over 1024 octets is ignored. OWASP ASVS 5.0 requirement V3.3.5 asks applications to keep cookies under that limit, because an oversized cookie is silently dropped and users get logged out or locked out.

SameSite in detail: site, scheme and the defaults

SameSite works on sites, not origins. A site is the scheme plus the registrable domain, so app.example.com and blog.example.com are same-site, while http://example.com and https://example.com are cross-site under the "schemeful same-site" rules that browsers adopted. This has three consequences:

  • Sibling subdomains are trusted: a compromised or attacker-controlled subdomain (user content, a forgotten marketing site, a dangling CNAME) can send same-site requests that carry Strict and Lax cookies. SameSite does not protect against your own subdomains. See the Subdomain Takeover and Dangling DNS Guide.
  • Mixed schemes break cookies: Strict and Lax cookies are not sent on subresource requests or form POSTs between the HTTP and HTTPS versions of a site. The fix is HTTPS everywhere and HSTS with includeSubDomains, not relaxing SameSite.
  • Defaults vary: MDN notes that some browsers apply Lax when SameSite is missing, and when they do they allow cross-site POST for cookies set within the last two minutes (the "Lax-allowing-unsafe" behaviour described in rfc6265bis). Other browsers do not apply Lax by default. A cookie with no SameSite attribute therefore behaves differently depending on the user's browser, which is why the OWASP Session Management Cheat Sheet says not to rely on defaults.

Choosing Strict, Lax or None

SituationValueWhy
Session cookie for a normal web applicationLaxUsers stay logged in when following a link from email or another site; cross-site POST does not carry the cookie
Banking, admin consoles, high-value actionsStrict (optionally with a separate Lax "logged-in" indicator cookie)No cross-site request ever carries the authority cookie; the indicator cookie gives a smooth landing page
Embedded widget, payment iframe, third-party SSO flow that posts back cross-siteNone; Secure (consider Partitioned)The cookie must be sent cross-site; add CSRF tokens and origin checks
SAML or OIDC form_post response to your callbackNone; Secure on the short-lived state or nonce cookie onlyThe identity provider POSTs cross-site; keep the main session cookie Lax or Strict

SameSite reduces CSRF exposure but does not remove it: same-site attacks, GET endpoints that change state, and browsers without Lax defaults all remain. Keep synchroniser or double-submit tokens and Origin checks as described in the CSRF Prevention Guide.

Prefixes are the only cookie control the browser enforces at set time. If a Set-Cookie header (or script) tries to create a prefixed cookie without meeting the rules, the browser rejects it. That closes two attack paths that attributes alone cannot: a network attacker injecting a cookie over plain HTTP, and a sibling subdomain "tossing" a cookie scoped to the parent domain that shadows your session cookie (a classic route to session fixation).

PrefixBrowser requiresProtects againstUse for
__Secure-Secure, set from an HTTPS pageInjection over HTTPCookies that must be shared across subdomains (Domain allowed)
__Host-Secure, HTTPS, Path=/, no DomainHTTP injection and subdomain cookie tossingSession and CSRF cookies of a single host
__Http-Secure, HTTPS, HttpOnly; can only be set by the Set-Cookie header, not by document.cookie or the Cookie Store APIScript on the page planting or overwriting the cookieServer-issued cookies shared across subdomains
__Host-Http-All __Host- rules plus HttpOnly and header-only settingAll of the aboveThe strongest form for a host-only session cookie

Points to know before adopting them:

  • Older browsers ignore prefixes: MDN notes that a browser without prefix support accepts the cookie without the restrictions. The prefix is a hardening layer, so still set every attribute explicitly.
  • Prefix matching is case-insensitive in rfc6265bis, so attempts to bypass with __HOST- are caught by conforming browsers, but your own server-side parsing should also be case-insensitive when it reads the cookie.
  • __Http- is newer: it is documented on MDN, but check browser support for your user base before depending on it; fall back to __Host- with HttpOnly.
  • Renaming logs everyone out: moving from session to __Host-session is a new cookie. Plan the migration (see the rollout section).

OWASP ASVS 5.0 makes this concrete: V3.3.1 (Level 1) requires Secure on every cookie and the __Secure- prefix where __Host- is not used, and V3.3.3 (Level 2) requires __Host- unless a cookie is explicitly designed to be shared with other hosts.

CHIPS (Cookies Having Independent Partitioned State) lets a third-party embed opt in to a separate cookie jar per top-level site. The cookie is double-keyed: by the site that set it and by the top-level site the user was visiting. A chat widget embedded on shop.example and on news.example gets two unrelated cookies, so it can keep state without tracking users across sites. MDN lists CHIPS as Baseline 2025 (newly available since December 2025). Partitioned requires Secure; MDN's example uses __Host- with SameSite=None; Secure; Path=/; Partitioned, and recommends the __Host- prefix unless the partitioned cookie must be shared between subdomains of the top-level site.

  • Chrome position: in an update dated 17 October 2025 Google stated that Chrome will maintain its current approach of offering users third-party cookie choice rather than removing third-party cookies. Third-party cookies therefore remain possible in Chrome, but users and other browsers may block them, so embeds should not depend on unpartitioned cross-site cookies.
  • Security use: if you ship an embeddable component, a partitioned cookie limits what a malicious host page can learn about the same user on other sites, and it survives third-party cookie blocking.
  • Not a session store for your main app: partitioning is for embedded contexts. Your first-party session cookie should stay Lax or Strict.
CookieRecommended Set-Cookie patternNotes
Primary session__Host-sid=<random>; Secure; HttpOnly; SameSite=Lax; Path=/No Expires/Max-Age (session cookie) or a short Max-Age matched to the server absolute timeout
High-value session (admin, payments)__Host-Http-sid=...; Secure; HttpOnly; SameSite=Strict; Path=/Short idle timeout server-side; step-up for sensitive actions
CSRF token (double submit)__Host-csrf=...; Secure; SameSite=Strict; Path=/Not HttpOnly if the page script must read it; bind to the session
"Remember me" or refresh__Host-rt=...; Secure; HttpOnly; SameSite=Strict; Path=/; Max-Age=<days>Store only a hashed, rotating, revocable value server-side
OIDC/SAML state or nonce__Host-state=...; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=600Short-lived, single use, deleted after callback
Cross-subdomain SSO__Secure-sso=...; Secure; HttpOnly; SameSite=Lax; Domain=example.com; Path=/Only if every subdomain is equally trusted and centrally managed
Third-party embed state__Host-w=...; Secure; SameSite=None; Path=/; PartitionedCSRF tokens on any state-changing endpoint

Beyond attributes, the value matters. The OWASP Session Management Cheat Sheet requires session identifiers with at least 64 bits of entropy from a cryptographically secure generator (128 bits is a sensible floor for self-generated IDs), a meaningless value with all session data held server-side, a generic name instead of framework defaults such as PHPSESSID or JSESSIONID, and a new identifier after login or any privilege change. ASVS V14.3.3 adds that browser storage, cookies included, should hold no sensitive data other than session tokens: do not put roles, email addresses or unencrypted JWT claims in cookies. For the token side of the design see the Token and Session Security Guide and the Browser Storage Security Guide.

  • Host-only by default: choose __Host- unless a business requirement says otherwise. Each application on its own hostname gets its own session, and a breach of marketing.example.com cannot read or shadow app.example.com cookies.
  • Shared parent-domain cookies only with central control: a Domain=example.com cookie is exposed to every subdomain, including ones run by agencies or SaaS providers through CNAMEs. Large organisations with many subdomains should move to an SSO hop (each app gets its own host-only session after an OIDC redirect) rather than one shared cookie.
  • Cookies over JavaScript-held tokens for browser apps: an HttpOnly session cookie behind a backend-for-frontend keeps tokens out of reach of page script, which localStorage cannot. See the OAuth for Browser-Based Applications and the BFF Pattern Guide.
  • Small organisations: one application, one hostname: a framework setting change (session cookie name, SameSite, Secure, HttpOnly) plus HSTS usually covers the whole baseline in a day.
  • Large estates: enforce the baseline at the edge (reverse proxy or gateway rewriting Set-Cookie) as a backstop, but fix the application too, because cookies set by script are not visible to the proxy.

How to implement and roll out

  1. Inventory cookies: crawl authenticated and unauthenticated journeys with a proxy or browser automation and export every Set-Cookie and document.cookie write with name, attributes, size, setting host and purpose. Include third-party scripts.
  2. Classify: session, CSRF, preference, analytics, third-party. Mark which must be readable by script and which must cross subdomains or sites. Consent and tracking classification is covered in the Cookie and Tracking Technology Compliance Guide.
  3. Fix attributes first: add Secure and explicit SameSite to everything, HttpOnly to anything script does not need, remove Domain where not required. These changes do not rename cookies, so users stay logged in.
  4. Enable HSTS: serve every subdomain over HTTPS and set HSTS with includeSubDomains, so Secure cookies are never offered on a downgraded connection.
  5. Introduce prefixes with dual-read: set the new __Host- cookie on login and session refresh, accept either name for one session lifetime, then stop reading the old name and expire it with Max-Age=0. Rollback is simply re-enabling the old name.
  6. Pilot: release to an internal ring, then a percentage of users. Watch login error rates, SSO callback failures (the usual SameSite casualty) and support tickets about being logged out.
  7. Harden logout: invalidate the server session, expire cookies with matching Path and no Domain, and consider the Clear-Site-Data: "cookies" response header on the logout endpoint.
  8. Lock it in: add automated tests that fail the build when a Set-Cookie lacks the baseline, and add the checks to your DAST profile. See the Web Application Security Testing Guide.

Testing, detection and measurement

Test what the browser stores, not what the code intends. Browser developer tools (Application or Storage panel) show the final attributes, including whether a prefixed cookie was rejected. Test cases worth automating:

  • Set from HTTP: confirm no session cookie is ever set or sent over http://.
  • Cross-site POST: submit a form from another site and confirm the session cookie is not attached (Lax or Strict) and the CSRF check fails.
  • Subdomain tossing: from a test subdomain, set a cookie with the same unprefixed name for the parent domain and confirm the application ignores it or the __Host- name makes it impossible.
  • Script access: confirm document.cookie does not show the session cookie.
  • Logout replay: capture a session cookie, log out, replay it and confirm a 401 or redirect.
  • Session ID rotation: confirm the identifier changes at login and at privilege elevation (session fixation, CAPEC-61). See the Session Fixation Guide.

On the detection side, stolen cookies show up as the same session identifier used from a new IP address, ASN, device fingerprint or user agent (ATT&CK T1539 Steal Web Session Cookie and T1550.004 Web Session Cookie). Log a session identifier hash, IP, user agent and timestamp at each authenticated request, and alert on impossible travel or mid-session fingerprint changes.

MetricTargetSource
Share of first-party cookies with Secure and explicit SameSite100%Crawler or DAST export
Share of authentication cookies using __Host- (or __Secure- with documented exception)100%Cookie inventory
Cookies over 4096 bytes or carrying personal data0Inventory with size and content review
Session replay after logout succeeds0 occurrencesAutomated regression test
Sessions flagged for mid-session IP or fingerprint change, investigated within SLA100% triagedSIEM

Where identity fits

A session cookie that has passed MFA is an identity credential in its own right, and the same is true of cookies issued to automation: browser-driven test accounts, RPA bots and headless crawlers often hold long-lived "remember me" cookies in shared profiles or CI variables. Treat those as non-human credentials: give them their own accounts, short lifetimes and storage in a secrets manager, and rotate them when staff leave. Binding sessions to a device key closes the replay gap that attributes cannot; see the Device-Bound Session Credentials (DBSC) Guide.

Common failure patterns

  • Trusting HttpOnly against infostealers: HttpOnly only hides the cookie from page script. Malware reads the browser's cookie store directly, as in the CircleCI breach, where malware on an engineer's laptop took an SSO session cookie that had already passed two-factor authentication. Only short lifetimes, device binding and anomaly detection limit that. See the Infostealer Logs and Session Token Abuse Guide.
  • Domain set "to be safe": developers add Domain=example.com believing it restricts the cookie, when it widens it to every subdomain.
  • SameSite=None everywhere to fix one SSO flow: a single failed callback leads teams to relax the main session cookie, reopening CSRF across the application. Put None on the short-lived state cookie only.
  • Relying on Path for isolation: two applications under /app1 and /app2 on one host can read each other's cookies through script. Use separate hostnames (ASVS V3.5.4).
  • Client-side logout only: clearing the cookie while the server session stays valid leaves any stolen copy usable until the absolute timeout.
  • Cookie bloat: storing state or JWTs in cookies until they pass 4096 bytes, which the browser silently drops, producing intermittent logouts and pressure to weaken settings.

Framework mapping

FrameworkReferenceRelevance
OWASP ASVS 5.0V3.3.1 to V3.3.5 Cookie Setup; V3.5.4; V14.3.3Secure and prefixes, SameSite by purpose, __Host-, HttpOnly, size limit, origin separation, no sensitive data
NIST SP 800-53 Rev. 5SC-23 Session Authenticity; SC-8 Transmission Confidentiality and Integrity; AC-12 Session TerminationProtecting session identifiers, HTTPS only, server-side termination
NIST CSF 2.0PR.DS-02; PR.AA-03Data in transit protected; users authenticated
ISO/IEC 27001:2022 Annex AA.8.26 Application security requirements; A.8.28 Secure codingCookie baseline as a written requirement and coding standard
CIS Controls v8.1Control 16 Application Software SecuritySecure configuration standards for applications
MITRE ATT&CKT1539; T1550.004; T1185 Browser Session HijackingCookie theft and reuse
MITRE CAPECCAPEC-31 Accessing/Intercepting/Modifying HTTP Cookies; CAPEC-61 Session FixationAttack patterns the attributes and prefixes address
CWECWE-614 (missing Secure); CWE-1004 (missing HttpOnly); CWE-1275 (improper SameSite)Weakness IDs used by scanners and SAST tools

Practitioner checklist

  • Inventory every cookie (name, attributes, size, setter, purpose), including those set by script and third parties.
  • Set Secure and an explicit SameSite value on every cookie; set HttpOnly on every cookie script does not need.
  • Rename session and CSRF cookies to __Host- (or __Host-Http-) with a dual-read migration; document any __Secure- exception.
  • Remove Domain unless there is an approved cross-subdomain requirement, and host applications of different trust levels on separate hostnames.
  • Restrict SameSite=None to short-lived SSO state cookies and genuine embeds; use Partitioned for embed state.
  • Generate session IDs with at least 64 bits (preferably 128) of CSPRNG entropy, use a generic name, rotate on login and privilege change.
  • Enforce idle and absolute timeouts and logout invalidation on the server; add Clear-Site-Data on logout.
  • Enable HSTS with includeSubDomains across the domain.
  • Add build-time and DAST tests that fail on missing attributes, then monitor for session reuse from new devices.

Standards and references

Related NHI Mgmt Group resources: Security Headers Guide · Session Hijacking and Cookie Theft Guide · CSRF Prevention Guide · Token and Session Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.