JavaScript Document cookie Property

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance property

What You’ll Learn

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

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.

Related Document tutorials: contentType, characterSet, Document constructor.

Understanding Document.cookie

An instance property on Document that acts as both getter and setter for document-associated cookies.

  • Getter — semicolon-separated key=value list (whitespace may surround keys/values; RFC 6265 prefers a space after each ;).
  • Setter — assign "name=value" plus optional attributes; only one cookie per assignment.
  • Attributesdomain, expires, max-age, path, samesite, secure, partitioned (MDN).
  • Encoding — use encodeURIComponent() for values that may contain special characters.
  • HttpOnly — not readable or writable from document.cookie.

📝 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.

Common attributes (when setting)

JavaScript
document.cookie =
  "theme=dark" +
  "; path=/" +
  "; max-age=" + (60 * 60 * 24 * 7) + // 7 days
  "; SameSite=Lax";
// Also: expires=UTCString, Secure, domain=..., partitioned

📌 Cookie attributes (setter)

AttributeMeaning
;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=secondsLifetime in seconds (e.g. 31536000 for one year).
;path=/URL path scope for when the cookie is sent.
;SameSite=Lax|Strict|NoneCross-site sending rules. Modern default is often Lax.
;SecureSend only over HTTPS.
;partitionedCHIPS 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.

⚡ Quick Reference

GoalCode / note
Read all cookiesdocument.cookie
Set a cookiedocument.cookie = "k=v; path=/"
Encode valueencodeURIComponent(value)
Get one cookieSplit on "; ", find name=
Delete cookieSet expires in the past (same path)
HttpOnly secretsSet from server only — not via JS
MDN statusBaseline Widely available

🔍 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

📋 Cookie name prefixes (MDN)

PrefixExtra 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).

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)
Try It Yourself

How It Works

Each assignment updates one cookie. The getter concatenates all script-visible cookies for this document.

Example 2 — Read One Cookie by Name (MDN)

Split the cookie string and pick a specific key.

JavaScript
document.cookie = "test1=Hello; path=/; SameSite=Lax";
document.cookie = "test2=World; path=/; SameSite=Lax";

const cookieValue = document.cookie
  .split("; ")
  .find((row) => row.startsWith("test2="))
  ?.split("=")[1];

console.log(cookieValue); // "World"
Try It Yourself

How It Works

There is no built-in “getCookie(name)”—parse the string yourself (or use a small helper).

📈 Once, Delete & Exists

Common patterns: run once, clear a cookie, and test for a name.

Example 3 — Do Something Only Once (MDN)

Set a long-lived flag cookie the first time an action runs.

JavaScript
const FLAG = "doSomethingOnlyOnce";

if (
  !document.cookie
    .split("; ")
    .find((row) => row.startsWith(FLAG + "="))
) {
  document.cookie =
    FLAG +
    "=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; SameSite=Lax";
  console.log("First time — do the action!");
} else {
  console.log("Already done earlier.");
}
Try It Yourself

How It Works

Replace the flag name with your own. Prefer app-controlled expiry over relying on browsers never to expire cookies (MDN privacy note).

Example 4 — Delete a Cookie (MDN)

Clear a cookie by setting an expired date (match path/domain).

JavaScript
// Create then delete the same cookie (same path!)
document.cookie = "doSomethingOnlyOnce=true; path=/; SameSite=Lax";

document.cookie =
  "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax";

console.log("After delete:", document.cookie);
Try It Yourself

How It Works

MDN: delete by updating expiration to the past (or use max-age=0). Path/domain must match the original cookie.

Example 5 — Check If a Cookie Exists (MDN)

Test for a cookie name (and optionally a value).

JavaScript
document.cookie = "reader=1; path=/; SameSite=Lax";

const hasReader = document.cookie
  .split(";")
  .some((item) => item.trim().startsWith("reader="));

const isOne = document.cookie
  .split(";")
  .some((item) => item.includes("reader=1"));

console.log('Cookie "reader" exists:', hasReader);
console.log('Value is "1":', isOne);
Try It Yourself

How It Works

Trim segments before matching names so leading spaces after ; do not break the check.

🔒 Security notes (MDN)

  • XSS can steal cookies visible to JavaScript (classic image/beacon exfiltration patterns).
  • HttpOnly session cookies (set via Set-Cookie) cannot be read with document.cookie.
  • path is not a strong security boundary—same-origin scripts can still reach cookies under other paths in some setups (MDN).
  • Secure + careful SameSite reduce cross-site leakage.
  • Never store secrets you would mind losing to XSS in a non-HttpOnly cookie.

🚀 Common Use Cases

  • UI preferences — theme, language, dismissed banners (small values).
  • First-visit flags — “do something only once” patterns.
  • Analytics / consent — when product requirements use cookies (follow privacy laws).
  • Legacy apps — reading cookies set by older server code.
  • Not for large data — prefer localStorage / IndexedDB for client-only payloads (MDN).
  • Auth tokens — prefer server-set HttpOnly + Secure cookies, not JS-writable ones.

🧠 How Cookies Move (Client ↔ Server)

1

Server sets a cookie

Set-Cookie: name=value; Path=/; HttpOnly (or JS sets a non-HttpOnly cookie).

Set-Cookie
2

Browser stores it

Respects expires / max-age, path, domain, SameSite, Secure.

Store
3

Later requests send Cookie

Matching cookies go in the HTTP Cookie request header.

Cookie
4

Scripts use document.cookie

Only non-HttpOnly cookies appear; attributes are not returned on read.

📝 Notes

  • MDN: Baseline Widely available — no Deprecated / Experimental / Non-standard banner.
  • Synchronous API — can block; consider Cookie Store API for async work (MDN).
  • One cookie per assignment; reading returns the whole visible list.
  • Encode values with encodeURIComponent() when needed (MDN).
  • More cookies → more request overhead; prefer storage APIs for client-only data.
  • Related: contentType, characterSet, Document constructor.

Universal Browser Support

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.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported (legacy)
Full support
Document.cookie Excellent

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.

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.

Continue with currentScript, contentType, characterSet, or the JavaScript hub.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about document.cookie

Read a list, write one cookie, protect secrets with HttpOnly.

5
Core concepts
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.

Next: currentScript

Learn which classic script element is currently being processed.

currentScript →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful