1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
HTTP cookies explained: Secure, HttpOnly, SameSite and scope

Key takeaways

  • HTTP cookies are set with the Set-Cookie response header and returned in the Cookie request header.
  • Attributes control scope and safety: Path, Domain, Max-Age, Secure, HttpOnly and SameSite.
  • In our test, a Secure cookie was stored but never sent over plain HTTP, and a Path=/admin cookie 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_token was stored but never sent, because the connection was not HTTPS.
  • admin_pref appeared only under /admin, because of its Path.
  • flash expired after one second and disappeared from /cart.
  • session vanished after /logout sent Max-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 with Secure from an HTTPS page.
  • __Host-: also requires Path=/ and no Domain, 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
Software Development

HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope

HTTP cookies explained: Set-Cookie, Path, Domain, expiry, Secure, HttpOnly, SameSite, prefixes, deleting cookies and a secure session recipe, tested locally.

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Databases & SQL

SQL Auto Increment: MySQL, PostgreSQL, SQL Server and SQLite

SQL auto increment in MySQL, PostgreSQL, SQL Server and SQLite: syntax, reading the new ID, why gaps appear, ID reuse,…

Read article →
Databases & SQL

SQL BETWEEN: Inclusive Ranges and the Date Trap Explained

SQL BETWEEN explained with tested queries: inclusive ranges, reversed bounds, NULLs, the last-day date trap, half-open ranges and index-friendly date…

Read article →
Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals explained with 10 tested examples: interpolation, multiline strings, escaping, tagged templates for safe HTML and SQL, and…

Read article →
Software Development

Python heapq: Priority Queues, Top N and Heaps Explained

Python heapq explained: heappush, heappop, heapify, priority queues with tie-breakers, max heaps, nlargest and merge, with real timings against sorting.

Read article →
Software Development

Python Walrus Operator (:=) Explained With 8 Real Examples

The Python walrus operator := explained with 8 tested examples: if checks, regex matches, while loops, comprehensions, scope rules, precedence…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →