JavaScript Cookies

Beginner
10 min read
Updated: Oct 2026
4 examples
Live preview

What Are Cookies?

Cookies are small name=value pairs the browser stores for a site. JavaScript reads and writes non-HttpOnly cookies through document.cookie. The server can also set them with Set-Cookie response headers.

Note Write ≠ read

document.cookie is an accessor: assigning sets one cookie; reading returns a semicolon-separated list of visible name=value pairs — not the string you just wrote.

Remember
document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax"
document.cookie → "theme=dark; …"   // getter: all visible pairs

write  → one cookie per assignment
read   → parse the full string
delete → same path + max-age=0
GoalPrefer
Create / updatedocument.cookie = "…"
Read one namegetCookie(name) helper
Site-wide scopepath=/
Client-only datalocalStorage (not cookies)

How to Use Cookies

Treat cookies as a tiny lifecycle: write attributes carefully, parse on read, and match path when updating or deleting.

  1. Write with name=value, path=/, and max-age when persistence matters.
  2. Encode values with encodeURIComponent; decode when reading.
  3. Parse document.cookie by splitting on ";" and the first =.
  4. Delete by rewriting with max-age=0 and the same path.
PieceRequired?Role
name=valueYesCookie identity and payload
pathRecommendedURL scope — prefer /
max-age / expiresOptionalLifetime vs session; 0 deletes
SameSite / SecureRecommendedCross-site and HTTPS safety

Pseudocode

Pseudocode
// WRITE
document.cookie = name + "=" + encode(value)
                 + "; path=/; max-age=SECONDS; SameSite=Lax"

// READ
for each part in document.cookie.split(";"):
    name, value = split on first "="
    if name matches: return decode(value)

// DELETE
document.cookie = name + "=; path=/; max-age=0"

Cheat Sheet

Keep these cookie facts handy.

TopicDetail
APIdocument.cookie (getter + setter)
One writeCreates or updates one cookie
SessionOmit max-age and expires
7 daysmax-age=604800
Deletemax-age=0 + matching path
HttpOnlyServer-only — invisible to JS
SizeKeep values tiny (~4 KB practical limit)

Live Preview

Write, read, or delete a demo theme cookie in this browser, then inspect document.cookie.

Demo cookies use path=/ and SameSite=Lax. HttpOnly cookies never appear in document.cookie.

Result
Choose an action, then Run.

document.cookie → (current jar)

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Write a Cookie

Create a site-wide preference cookie that lasts seven days.

JavaScript
document.cookie =
  "theme=dark; path=/; max-age=604800; SameSite=Lax";

console.log(document.cookie);
// "theme=dark" (plus any other visible cookies)
Try It Yourself

How It Works

  1. Assign once. One document.cookie = … writes one cookie.
  2. Add path=/. The cookie is available on every page of this origin.
  3. Set max-age. 604800 seconds keeps it for seven days.
  4. Read back names only. Attributes never appear in the getter string.

Example 2 — Read a Cookie by Name

Parse document.cookie and return one value safely.

JavaScript
function getCookie(name) {
  var parts = document.cookie.split(";");
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i].trim();
    var eq = part.indexOf("=");
    if (eq === -1) continue;
    if (part.slice(0, eq) === name) {
      return decodeURIComponent(part.slice(eq + 1));
    }
  }
  return null;
}

document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax";
console.log(getCookie("theme")); // "dark"
Try It Yourself

How It Works

  1. Split pairs. ";" separates cookies in the getter string.
  2. Trim spaces. Browsers often leave a space after each semicolon.
  3. Split on first =. Values may contain more equals signs.
  4. Decode. Pair with encodeURIComponent on write — see Cookie Read.

Example 3 — Update a Cookie

Overwrite the same name with a matching path to change the value.

JavaScript
document.cookie = "theme=dark; path=/; max-age=2592000; SameSite=Lax";
document.cookie = "theme=light; path=/; max-age=2592000; SameSite=Lax";

console.log(document.cookie);
// theme=light (same path → overwrite, not a second cookie)
Try It Yourself

How It Works

  1. Same name + path. That identity selects which cookie to replace.
  2. Rewrite everything. Include lifetime and path again on every update.
  3. Avoid path traps. A different path creates a duplicate — see Cookie Update.
  4. Check DevTools. Application → Cookies shows the live attributes.

Example 4 — Delete a Cookie

Expire the cookie immediately with max-age=0 and the same path.

JavaScript
document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax";
document.cookie = "theme=; path=/; max-age=0";

console.log(document.cookie);
// "theme=…" gone from the visible jar
Try It Yourself

How It Works

  1. Empty the value. Set name= with nothing after the equals.
  2. Expire now. max-age=0 (or a past expires) removes it.
  3. Match path. Deletion fails silently if path/domain differ.
  4. Prefer max-age. Simpler than UTC dates — see Cookie Expires.

Cookie Tutorials

Go deeper on each operation and attribute.

TutorialFocus
Cookie WriteSet name=value, path, max-age, Secure, SameSite
Cookie ReadParse document.cookie and getCookie helpers
Cookie UpdateOverwrite values with matching path/domain
Cookie PathControl which URLs receive the cookie
Cookie ExpiresSession vs persistent lifetime and deletion

Edge Cases & Pitfalls

Check these before shipping cookie code.

path

Forgetting path=/

Default path is the current directory. Cookies then “vanish” on other routes — see Cookie Path.

HttpOnly

Secrets stay on the server

Auth tokens should be HttpOnly via Set-Cookie. Anything in document.cookie is visible to page scripts.

encode

Raw spaces / semicolons

Unencoded values can truncate the cookie string. Always encode user text.

size

Cookies ride on every request

Large values slow HTTP. Prefer short lifetimes and tiny payloads; use localStorage for client-only data.

Browser Support

Reading and writing cookies via document.cookie is a long-standing DOM feature. max-age, path, Secure, and SameSite are supported in all modern browsers.

✓ Baseline · DOM

document.cookie

Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Prefer max-age + path=/ + SameSite=Lax for new code; add Secure on HTTPS.

99% Universal API
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
document.cookie Excellent

Bottom line: Safe for production. Keep values small, encode carefully, and never store secrets in script-readable cookies.

Performance Notes

ChoiceEffectBest for
One write / readCheap assign / parsePreferences, flags
Large cookie jarExtra bytes on every requestAvoid — keep values tiny
Client-only dataNo HTTP overheadlocalStorage

MDN notes that document.cookie is synchronous. For modern async APIs, see the Cookie Store API.

Key Takeaways

  • Role: use document.cookie to write one cookie and read the visible jar.
  • Defaults: prefer path=/, max-age when persistent, and SameSite=Lax.
  • Parse carefully: split on ";", trim, and split on the first =.
  • Secrets: keep auth tokens HttpOnly on the server — not in JS-readable cookies.

One line: write with name=value; path=/; max-age=…; SameSite=Lax, parse to read, delete with max-age=0, and never store secrets in script-readable cookies.

Frequently Asked Questions

What are cookies in JavaScript?

Cookies are small name=value pairs the browser stores and may send back to the server on matching requests. In JavaScript you read and write non-HttpOnly cookies through document.cookie.

How do I set a cookie with JavaScript?

Assign a string: document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax". Each assignment creates or updates one cookie.

How do I read a cookie by name?

Read document.cookie, split on ";", trim each part, and match the name before the first "=". A small getCookie(name) helper makes this easier.

How do I delete a cookie?

Overwrite it with an empty value and max-age=0 (or a past expires), using the same path (and domain) as when it was set: document.cookie = "name=; path=/; max-age=0".

Can JavaScript read HttpOnly cookies?

No. HttpOnly cookies are set by the server via Set-Cookie and are hidden from document.cookie. That reduces XSS token theft.

When should I use localStorage instead of cookies?

Use localStorage for client-only data that the server does not need on every request. Prefer cookies when the value must travel with HTTP requests or when the server sets HttpOnly session cookies.

Next: Cookie Write

Learn how to set cookies with path, max-age, Secure, and SameSite.

Cookie Write tutorial →

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.

14 people found this page helpful