JavaScript Cookies — Read

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Client storage

What You’ll Learn

Reading cookies means parsing the document.cookie string to recover stored values. This tutorial covers the raw API, a reliable getCookie helper, decoding, parsing every cookie into an object, and pitfalls beginners hit.

01

Raw string

document.cookie

02

By name

getCookie()

03

Decode

decodeURIComponent

04

Parse all

Object map

05

Fallbacks

Missing cookies

06

Limits

No HttpOnly access

Introduction

After you write cookies, pages need to read them back—to apply a dark theme, restore language choice, or show a greeting. JavaScript exposes cookies through one property: document.cookie.

Unlike localStorage, there is no getItem(name) built in. You read the entire visible cookie string and parse the name you need.

What Are Cookies?

Cookies are small name–value pairs stored by the browser and sent with HTTP requests. From JavaScript you only see cookies that are not marked HttpOnly and that match the current document’s URL scope.

When you read document.cookie, you get a single string like "username=JohnDoe; theme=dark"—names and values only, never expires, path, or Secure metadata.

💡
Beginner Tip

DevTools shows full cookie details, but document.cookie is intentionally limited. If a cookie appears in Application → Cookies but not in your script, check for HttpOnly or path/domain mismatch.

Why Read Cookies?

  • Personalization — restore theme, font size, or language on page load.
  • Client hints — read non-sensitive flags like consent=1 or cart IDs.
  • UI state — show “Welcome back” when a display name cookie exists.
  • Debugging — log visible cookies while building write/update flows.

Avoid relying on JavaScript-readable cookies for authentication secrets—use HttpOnly server cookies instead. Scripts should treat readable cookie values as untrusted user-controlled input.

📝 Syntax

Read every cookie visible to the current page:

JavaScript
const allCookies = document.cookie;
console.log(allCookies); // "username=JohnDoe; theme=dark"

Reliable getCookie helper (split on first = only):

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 decodeURIComponent(value);
    }
  }
  return null;
}

Return value

  • String — decoded cookie value when the name is found.
  • null — when no matching cookie exists or it is not visible to script.

⚡ Quick Reference

GoalCode
All visible cookiesdocument.cookie
One cookie by namegetCookie("theme")
Decode stored valuedecodeURIComponent(value)
Missing cookieReturns null — use fallback
Value with =Split on first = only
HttpOnly cookieNot in document.cookie

📋 Script Read vs DevTools

document.cookie is not a full dump of everything DevTools lists. Know what JavaScript can and cannot see.

Script sees
name=value

Name and value only

DevTools sees
path, expires

Full metadata

Hidden
HttpOnly

Server-only cookies

Scope
current URL

Path rules apply

Handling Special Characters

Values stored with encodeURIComponent look like Hello%2C%20world. Always decode on read when your write path encodes:

JavaScript
// Written earlier as:
// document.cookie = "greeting=" + encodeURIComponent("Hello, world!") + "; path=/";

const greeting = getCookie("greeting");
console.log(greeting); // "Hello, world!"

If decoding throws on malformed sequences, wrap in try/catch and fall back to the raw string for robust apps.

Examples Gallery

Open DevTools Console or use Try-it labs. Examples seed cookies first so reads return meaningful output.

📚 Getting Started

Inspect the raw cookie string the browser exposes.

Example 1 — Read All Cookies as a String

Log the full document.cookie value after setting two sample 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

Each write adds or updates one cookie. Reading returns every script-visible cookie joined by ; with no metadata attached.

📈 Practical Patterns

Targeted lookups, decoding, bulk parsing, and UI usage.

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

The loop scans each name=value segment. Using indexOf("=") preserves values that contain additional equals signs (e.g. Base64 tokens).

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;
    const key = trimmed.slice(0, eq);
    const value = trimmed.slice(eq + 1);
    if (key === name) {
      try {
        return decodeURIComponent(value);
      } catch {
        return value;
      }
    }
  }
  return null;
}

document.cookie = "greeting=" + encodeURIComponent("Hello, world!") + "; path=/";
console.log(getCookie("greeting")); // Hello, world!
Try It Yourself

How It Works

Encoding on write and decoding on read keeps commas, spaces, and Unicode safe inside cookie values.

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

Later keys with the same name overwrite earlier entries in the object—mirroring how duplicate path-scoped cookies can be ambiguous when read as one string.

Example 5 — Display Preferences on Page Load

Read theme and username cookies and render friendly fallbacks.

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 = "username=JohnDoe; path=/";
document.cookie = "theme=dark; path=/";

const username = getCookie("username") || "Guest";
const theme = getCookie("theme") || "light";

console.log("Welcome, " + username + "!");
console.log("Theme: " + theme);
Try It Yourself

How It Works

The || "Guest" and || "light" fallbacks keep the UI usable when cookies are missing or expired. After reading, you can update preferences when the user changes settings.

🚀 Common Use Cases

  • Theme on load — read theme before painting the page.
  • Language selection — pick locale strings from a lang cookie.
  • Consent gating — skip the banner when consent is already set.
  • Returning visitor UX — show a name from a display cookie (non-sensitive).
  • Debug panels — dump getAllCookies() during development.
  • Form prefill hints — restore non-sensitive defaults saved earlier.

🧠 How Reading a Cookie Works

1

Browser filters

Collect cookies eligible for this document URL, excluding HttpOnly entries.

Scope
2

Serialize string

Join visible pairs as name=value; name2=value2.

Expose
3

Script parses

Split, trim, match name, optionally decode value.

Parse
4

Use in app

Apply theme, locale, or other client logic—treat values as untrusted input.

📝 Notes & Common Pitfalls

  • Case-sensitive namesTheme and theme are different keys.
  • Expired cookies — absent from document.cookie; no error is thrown.
  • Split trap — never use split("=") on the whole pair; split on the first equals sign only.
  • HttpOnly — session tokens stored securely are invisible to getCookie.
  • Duplicate names — different paths can produce confusing reads; normalize writes with path=/.
  • Security — never trust cookie values for authorization without server validation.

Browser Support

Reading via document.cookie is supported in every browser that runs JavaScript on web pages, including legacy Internet Explorer.

Baseline · DOM Level 0

document.cookie (read)

Universal API. Parsing helpers are plain JavaScript—no polyfill required. Cookie visibility rules (HttpOnly, SameSite, third-party blocking) vary by browser privacy settings.

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 everywhere for reading script-visible cookies. Test with DevTools when cookies seem missing—path, expiration, and HttpOnly are the usual causes.

Conclusion

Reading cookies starts with document.cookie, but real apps need a small parser: split carefully, decode when needed, and return null with sensible fallbacks.

Keep one shared getCookie in your project and reuse it for write, update, and delete flows so parsing stays consistent.

💡 Best Practices

✅ Do

  • Split on the first = only
  • Decode with decodeURIComponent
  • Provide fallbacks for missing cookies
  • Centralize parsing in one helper
  • Treat values as untrusted input

❌ Don’t

  • Assume DevTools list equals script access
  • Store or read passwords in cookies
  • Use split("=") on the whole pair
  • Expect expires/path from document.cookie
  • Authorize users based only on client cookies

Key Takeaways

Knowledge Unlocked

Five things to remember when reading cookies

Parse safely and know what JavaScript cannot see.

5
Core concepts
🔍 02

getCookie

Loop + first =.

Parser
🔤 03

Decode

Restore special chars.

Encoding
🚫 04

HttpOnly

Hidden from script.

Limit
👤 05

Fallbacks

null → default.

UX

❓ 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 to separate name and value, then compare the name. A small getCookie(name) helper wraps this loop.
HttpOnly cookies, wrong path scope, expired cookies, or cookies on a different domain are not exposed through document.cookie even if they appear in DevTools for the active request.
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 not returned to script code.
Split on the first equals sign only: var eq = part.indexOf("="); var value = part.slice(eq + 1). Splitting on every equals sign truncates the value.
Did you know?

document.cookie is read-only in the sense that you cannot delete or change cookies by assigning to it—you only append/update via write syntax. Reading always returns the current visible snapshot as one string.

Continue to Update Cookies

Learn how to overwrite values and refresh expiration while keeping path scope aligned.

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

6 people found this page helpful