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
Fundamentals
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.
Concept
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.
Purpose
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.
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.
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.
Applications
🚀 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.
Important
📝 Notes & Common Pitfalls
Case-sensitive names — Theme 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.
Compatibility
Browser Support
Reading via document.cookie is supported in every browser that runs JavaScript on web pages, including legacy Internet Explorer.
Bottom line: Safe everywhere for reading script-visible cookies. Test with DevTools when cookies seem missing—path, expiration, and HttpOnly are the usual causes.
Wrap Up
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.
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.