Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Read Cookies in JavaScript

JavaScript reads page-accessible cookies through document.cookie, a semicolon-separated string. Learn how to find a cookie by name and why HttpOnly cookies stay hidden.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read cookies available to the current page with document.cookie. It returns a semicolon-separated string of name=value pairs—not an object—and JavaScript cannot see cookies marked HttpOnly.

Read the cookies available to the current page

The cookie property on document has a getter and a setter. Reading it returns the cookie pairs JavaScript is allowed to access:

const cookieString = document.cookie;
console.log(cookieString);

A result might look like theme=dark; session_hint=abc. The browser returns a serialized string, with entries separated by semicolons and possible whitespace around them. It does not return JSON, an array, or a Map.

Get one cookie by name

To find one cookie, split the string at semicolons, trim each entry, and match the name before the first equals sign. Slicing after the matched prefix preserves additional equals signs that may appear in a value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function readCookie(name) {
  const prefix = `${name}=`;
  const item = document.cookie
    .split(";")
    .map((part) => part.trim())
    .find((part) => part.startsWith(prefix));

  return item ? item.slice(prefix.length) : undefined;
}

const theme = readCookie("theme");
console.log(theme);

This is a small parser built around the documented string format, not a browser-provided cookie-parsing API. It returns undefined when no matching readable cookie is present. Treat returned values as untrusted input: a user can inspect and modify many cookies that are accessible to scripts.

If your application controls the cookie values, agree on an encoding format when setting them and decode them only according to that format. Do not assume that every existing value is safely or consistently encoded.

Why a cookie may be missing

HttpOnly hides a cookie from JavaScript

A cookie marked HttpOnly is deliberately unavailable through document.cookie. It can still be sent by the browser with eligible HTTP requests. This is usually the right choice for session credentials that client-side code does not need: it prevents page scripts from reading the secret directly.

If a login cookie is absent from the JavaScript string, do not remove HttpOnly just to make it visible. Let the browser attach the cookie to eligible requests, and configure the server and request credentials policy for the authentication flow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cookie scope and sending rules matter

Cookie attributes govern where and how cookies are sent. Secure restricts sending to secure HTTPS requests, subject to browser behavior for localhost; it does not, by itself, prevent JavaScript from reading a cookie. SameSite affects sending in cross-site contexts. Its Strict, Lax, and None settings have different behavior, and SameSite=None requires Secure.

Domain and Path affect which requests receive a cookie. Path is not a security barrier that prevents scripts running on another path from reading a cookie. Use HttpOnly when a cookie should not be accessible to scripts.

Reading is different from setting

Although reading and writing use the same property, assigning to it asks the browser to set an individual cookie; it does not replace the entire readable cookie list.

const availableCookies = document.cookie; // Read

document.cookie = "theme=dark"; // Ask the browser to set a cookie

Setting cookies has additional rules and attributes; assigning a string is not a way to inspect or change outgoing request headers. For authentication, avoid exposing a session secret to JavaScript when the server can manage it as an HttpOnly cookie.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to consider the Cookie Store API

The document.cookie getter is synchronous and can block the main thread, particularly when cookie access involves work across processes or I/O. Occasional reads are straightforward with document.cookie; code that manages cookies frequently may be better suited to the asynchronous Cookie Store API where it is supported. Check support in the browsers and execution contexts you target before adopting it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common problems and fixes

  • The value is a string, not an object: parse the semicolon-separated entries rather than treating the result as JSON.
  • A value seems truncated at an equals sign: match the cookie name and remove only the first name= prefix, as in the parser above.
  • A session cookie does not appear: check whether it is HttpOnly. JavaScript cannot read it; use the browser’s eligible requests and server-side authentication flow instead.
  • A cookie is not sent with a request: check its domain, path, secure transport, and SameSite behavior against the request context.
  • Cookie access is affecting responsiveness: avoid unnecessary repeated synchronous reads; consider the asynchronous Cookie Store API if your target environments support it.

Or skip the browser setup

If what you actually need is a screenshot of a page that displays cookie banners, popups, or chat widgets—not access to its cookie values—ScreenshotNeo provides a website screenshot API. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and other MCP clients.

For example, this cURL request returns a screenshot for the target URL (replace the example URL and provide your API key):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can JavaScript read cookies set by a server?

Yes, if they are available to the current document and are not marked HttpOnly. A server-set HttpOnly cookie is intentionally hidden from JavaScript.

Does document.cookie show every cookie sent with a request?

No. It exposes only cookies available to the current document and excludes HttpOnly cookies; request sending also depends on cookie scope and attributes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.