Document.cookie is a read/write instance property (an accessor) that lets you read and write cookies for the current document. Learn the get vs set asymmetry, attributes like expires, max-age, path, SameSite, and Secure, how to parse and delete cookies, and five examples with try-it labs.
01
Kind
Read / write
02
Get
name=value list
03
Set
One cookie
04
Attrs
path / expires
05
Safety
HttpOnly / XSS
06
Status
Baseline widely
Fundamentals
Introduction
Cookies are small name/value pieces of data the browser stores and may send back to the server on later requests. They are often used for preferences, analytics IDs, and (when set carefully by the server) session tokens.
document.cookie is how page scripts read cookies that are not marked HttpOnly, and how they set or update a single cookie at a time. MDN notes that reading cookies is a synchronous API and can block the main thread—prefer the asynchronous Cookie Store API when you need modern, non-blocking cookie management.
💡
Write ≠ read
MDN: document.cookie is an accessor with native getter and setter. What you assign is not the same string you later read—the getter returns only visible name=value pairs, never the attributes you passed when setting.
Encoding — use encodeURIComponent() for values that may contain special characters.
HttpOnly — not readable or writable from document.cookie.
Foundation
📝 Syntax
JavaScript
// Read all visible cookies
document.cookie
// Set / update one cookie
document.cookie = "name=value; path=/; max-age=3600";
Value
A string of semicolon-separated cookies when reading. When writing, a string of the form key=value optionally followed by attribute pairs separated by semicolons.
Small prefs / legacy; server sessions (prefer HttpOnly)
localStorage
No
Client-only data that persists
sessionStorage
No
Per-tab temporary client data
Cookie Store API
Yes (cookies)
Async cookie management (MDN recommendation)
IndexedDB
No
Larger structured client data
MDN: for client-only data, prefer DOM Storage (or IndexedDB) instead of stuffing more cookies onto every HTTP request.
Details
📌 Cookie attributes (setter)
Attribute
Meaning
;domain=...
Host the cookie is sent to; foreign domains are ignored (MDN).
;expires=...
UTC expiry string (Date.toUTCString()). Session cookie if omitted with max-age.
;max-age=seconds
Lifetime in seconds (e.g. 31536000 for one year).
;path=/
URL path scope for when the cookie is sent.
;SameSite=Lax|Strict|None
Cross-site sending rules. Modern default is often Lax.
;Secure
Send only over HTTPS.
;partitioned
CHIPS partitioned storage (advanced).
⚠️
SameSite=None
Requires Secure. MDN demo pages often use SameSite=None; Secure for cross-origin embeds. On a normal same-site page, omitting SameSite (or using Lax) is usually better.
Cheat Sheet
⚡ Quick Reference
Goal
Code / note
Read all cookies
document.cookie
Set a cookie
document.cookie = "k=v; path=/"
Encode value
encodeURIComponent(value)
Get one cookie
Split on "; ", find name=
Delete cookie
Set expires in the past (same path)
HttpOnly secrets
Set from server only — not via JS
MDN status
Baseline Widely available
Snapshot
🔍 At a Glance
Four facts about document.cookie.
Type
string
Accessor
Access
get + set
One cookie / write
Hidden
HttpOnly
Not in JS
Status
baseline
Standard API
Compare
📋 Cookie name prefixes (MDN)
Prefix
Extra rules (supporting browsers)
__Secure-
Must use Secure on HTTPS.
__Host-
Secure, no Domain, Path must be /.
__Http-
Secure + HttpOnly (set via Set-Cookie, not JS).
__Host-Http-
Combines __Host- and HttpOnly rules.
The dash is part of the prefix. These flags require the Secure attribute (MDN).
Hands-On
Examples Gallery
Examples follow MDN Document: cookie. Labs use same-site friendly attributes (no cross-origin SameSite=None). Use View Output or Try It Yourself for each case.
📚 Getting Started
Set cookies and read the combined cookie string.
Example 1 — Set Cookies and Show Them (MDN-style)
Assign one cookie at a time, then read document.cookie.
JavaScript
document.cookie = "name=Oeschger; path=/; SameSite=Lax";
document.cookie = "favorite_food=tripe; path=/; SameSite=Lax";
console.log(document.cookie);
// e.g. "name=Oeschger; favorite_food=tripe"
// (order and other site cookies may vary)
Document.cookie is marked Baseline Widely available on MDN. Logos use the shared browser-image-sprite.png sprite from this project.
✓ Baseline · Widely available
Document.cookie
Read/write accessor for document cookies — set one cookie at a time; read a semicolon-separated list.
UniversalWidely available
Google ChromeFull support · Desktop & Mobile
Full support
Mozilla FirefoxFull support · Desktop & Mobile
Full support
Apple SafariFull support · macOS & iOS
Full support
Microsoft EdgeFull support · Chromium
Full support
OperaFull support · Modern versions
Full support
Internet ExplorerSupported (legacy)
Full support
Document.cookieExcellent
Bottom line: Use document.cookie to read and write non-HttpOnly cookies. Prefer HttpOnly Secure cookies for sessions, and storage APIs for client-only data.
Wrap Up
Conclusion
Document.cookie is the classic DOM way to read and write cookies from JavaScript. Remember the get/set asymmetry, encode values, delete with a past expires, and keep secrets in HttpOnly cookies set by the server.
Use encodeURIComponent / decodeURIComponent for safe values
Always set a clear path (often /) so delete matches
Prefer SameSite=Lax (or Strict) unless you truly need cross-site
Store sessions with server HttpOnly + Secure cookies
Keep cookie payloads small
❌ Don’t
Expect attributes to appear when reading document.cookie
Put auth secrets in JS-writable cookies
Use cookies for large client-only datasets
Forget matching path/domain when deleting
Ignore XSS risk for any non-HttpOnly cookie
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about document.cookie
Read a list, write one cookie, protect secrets with HttpOnly.
5
Core concepts
🍪01
Accessor
get + set
API
✓02
Status
baseline
Standard
🔒03
HttpOnly
hidden from JS
Security
🗑️04
Delete
past expires
Pattern
💾05
Client data
prefer storage
MDN
❓ Frequently Asked Questions
It is an accessor property that lets you read and write cookies for the current document. Reading returns a semicolon-separated list of name=value pairs. Assigning sets or updates one cookie at a time.
No. MDN marks Document.cookie as Baseline Widely available. It is a standard instance property. For async cookie work, MDN also points to the Cookie Store API as a modern alternative.
What you write is not the same as what you read. The setter accepts one cookie plus optional attributes (expires, path, SameSite…). The getter returns only name=value pairs for cookies visible to the script — no attributes.
Set the same cookie name again with an expires date in the past (or max-age=0), and match path/domain if you set them originally.
No. Cookies marked HttpOnly are sent to the server but are not visible to document.cookie. That helps reduce damage from XSS cookie theft.
Yes. Use encodeURIComponent() so values do not contain commas, semicolons, or whitespace, which are disallowed in cookie values (MDN).
Did you know?
When you write document.cookie = "a=1" and then document.cookie = "b=2", you are not replacing the whole cookie jar—you are adding or updating one cookie each time. That asymmetry surprises many beginners the first time they log document.cookie after a write.