JavaScript Cookie Read

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

What Is Reading Cookies?

Reading cookies means inspecting document.cookie — a single semicolon-separated string of name=value pairs visible to scripts on the current page. Attributes like path, expires, and HttpOnly are never included.

Note Write ≠ read

document.cookie is an accessor: assigning sets one cookie; reading returns the whole jar of script-visible name=value pairs — not the string you just wrote.

Remember
document.cookie
→ "username=JohnDoe; theme=dark"

split on ";" → trim → split on first "="
getCookie("theme") → "dark"
missing / HttpOnly / wrong path → null (or absent)
GoalPrefer
See all visible cookiesdocument.cookie
One cookie by namegetCookie(name) helper
Encoded valuesdecodeURIComponent(value)
Many lookupsParse once into an object

How to Read Cookies

Read the string, parse pairs carefully, and decode values you encoded on write.

  1. Read document.cookie (empty string if none are visible).
  2. Split on ";", then trim() each segment (spaces are common).
  3. Split each segment on the first = only — values may contain more equals.
  4. Use decodeURIComponent when the value was written with encodeURIComponent.
PieceRequired?Role
document.cookieYesRaw semicolon-separated string
Split + trimYesIsolate each name=value
First = onlyYesKeeps = inside values intact
decodeURIComponentRecommendedRestores encoded characters

Pseudocode

Pseudocode
raw = document.cookie          // "a=1; b=2" or ""
target = cookie name to find

for each part in raw.split(";"):
    part = trim(part)
    eq = index of first "=" in part
    if eq == -1: continue
    name  = part[0 .. eq)
    value = part[eq+1 .. end]
    if name == target:
        return decode(value)

return null                    // missing / not visible

Cheat Sheet

Keep these read-side facts handy.

TopicDetail
APIdocument.cookie (getter)
Formatname=value; name2=value2
MetadataNo path / expires / HttpOnly in the string
Missing cookieHelper returns null (or omit from object)
HttpOnlyNever readable from JavaScript
Equals in valueSplit on first = only
EncodingPair encodeURIComponent / decodeURIComponent

Live Preview

Seed demo cookies, then look up a name with a small getCookie parser — same idea as the examples below.

Seeds theme, username, and encoded greeting with path=/. HttpOnly cookies would never appear here.

Result
Click “Seed cookies”, then “Read”.

document.cookie → (current jar)

JavaScript Examples

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

Example 1 — Read All Cookies as a String

Log the full document.cookie value after setting two cookies.

JavaScript
document.cookie = "username=JohnDoe; path=/";
document.cookie = "theme=dark; path=/";

console.log(document.cookie);
// "username=JohnDoe; theme=dark" (order may vary)
Try It Yourself

How It Works

  1. Write two cookies. Each assignment creates or updates one name.
  2. Read the jar. document.cookie returns every script-visible pair.
  3. No metadata. You see names and values only — not path or expiry.
  4. Order may vary. Do not rely on a fixed sequence of cookies.

Example 2 — Read One Cookie with getCookie

Extract username from the semicolon-separated string.

JavaScript
function getCookie(name) {
  const pairs = document.cookie.split(";");
  for (const pair of pairs) {
    const trimmed = pair.trim();
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq);
    const value = trimmed.slice(eq + 1);
    if (key === name) return value;
  }
  return null;
}

document.cookie = "username=JohnDoe; path=/";
console.log(getCookie("username")); // JohnDoe
console.log(getCookie("missing"));  // null
Try It Yourself

How It Works

  1. Split the string. Each segment is one name=value pair.
  2. Trim spaces. Browsers often put a space after each semicolon.
  3. Use the first =. That keeps values that contain more equals signs intact.
  4. Return null if missing. Absent, expired, HttpOnly, or out-of-path cookies are not found.

Example 3 — Decode Encoded Values

Restore human-readable text from an encoded cookie value.

JavaScript
function getCookie(name) {
  const pairs = document.cookie.split(";");
  for (const pair of pairs) {
    const trimmed = pair.trim();
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    if (trimmed.slice(0, eq) === name) {
      try {
        return decodeURIComponent(trimmed.slice(eq + 1));
      } catch {
        return trimmed.slice(eq + 1);
      }
    }
  }
  return null;
}

document.cookie =
  "greeting=" + encodeURIComponent("Hello, world!") + "; path=/";

console.log(getCookie("greeting")); // Hello, world!
Try It Yourself

How It Works

  1. Encode on write. Spaces and punctuation are unsafe in raw cookie values.
  2. Find the name. Same parse loop as getCookie.
  3. Decode on read. decodeURIComponent restores the original text.
  4. Guard bad encodings. A try/catch falls back to the raw string if decoding fails.

Example 4 — Parse All Cookies into an Object

Convert the raw string into a plain object for easier lookups.

JavaScript
function getAllCookies() {
  const result = {};
  if (!document.cookie) return result;

  for (const pair of document.cookie.split(";")) {
    const trimmed = pair.trim();
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq);
    const raw = trimmed.slice(eq + 1);
    try {
      result[key] = decodeURIComponent(raw);
    } catch {
      result[key] = raw;
    }
  }
  return result;
}

document.cookie = "username=JohnDoe; path=/";
document.cookie = "theme=dark; path=/";

console.log(getAllCookies());
// { username: "JohnDoe", theme: "dark" }
Try It Yourself

How It Works

  1. Start empty. Build a plain object for every visible cookie.
  2. Parse each pair. Same trim + first-= rules as getCookie.
  3. Decode values. Store human-readable strings when encoding was used.
  4. Duplicate names. Later keys overwrite earlier ones in the object — path duplicates can look ambiguous in one string.

Edge Cases & Pitfalls

Check these before trusting cookie reads in production.

HttpOnly

HttpOnly never appears

Session tokens set with HttpOnly are hidden from document.cookie on purpose — DevTools can show them; scripts cannot.

path

Wrong path looks like “missing”

A cookie scoped to /shop is invisible on /js/cookies/read. See Cookie Path.

parse

Split on every =

Values can contain equals signs. Always use the first = only.

meta

No expiry or path in reads

Inspect Application → Cookies in DevTools for attributes. The JS string never includes them.

Browser Support

Reading cookies via document.cookie is a long-standing DOM feature available in all browsers that run JavaScript on web pages.

✓ Baseline · DOM

document.cookie (read)

Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Parsing helpers are pure JavaScript — no special browser API required.

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. For high-frequency cookie work in modern apps, consider the async Cookie Store API as an alternative to sync reads.

Performance Notes

ApproachCostBest for
One getCookieO(n) over cookie countOccasional lookups
Parse once to objectO(n) onceMany reads on the same page
Hot-loop document.cookieSync; can blockAvoid — cache the parsed result

MDN notes that document.cookie is synchronous and can block the main thread. Prefer parsing once per page load. For client-only data, consider localStorage; for modern async cookie APIs, see the Cookie Store API.

Key Takeaways

  • Role: document.cookie exposes script-visible name=value pairs only.
  • Parse carefully: trim segments; split on the first =.
  • Decode: pair encodeURIComponent on write with decodeURIComponent on read.
  • Limits: HttpOnly, wrong path, and expired cookies look “missing.”

One line: read document.cookie, parse with first-= splits, decode when needed, and remember HttpOnly stays invisible.

Frequently Asked Questions

Use document.cookie. It returns one semicolon-separated string of name=value pairs visible to scripts on the current page, such as "theme=dark; lang=en".
Split document.cookie on semicolons, trim each part, split on the first equals sign, then compare the name. A small getCookie(name) helper wraps this loop.
HttpOnly cookies, wrong path scope, expired cookies, or cookies on another domain are not exposed through document.cookie even if DevTools shows them.
Yes, when values were stored with encodeURIComponent. It restores spaces, commas, and Unicode characters safely.
No. The string only includes names and values. Attributes like expires, path, Secure, and HttpOnly are never returned to script.
Split on the first equals sign only: const eq = part.indexOf("="); const value = part.slice(eq + 1). Splitting on every equals truncates the value.

Next: Cookie Update

Learn how to change cookie values while keeping path and lifetime attributes correct.

Cookie Update 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.

10 people found this page helpful