ScreenshotNeo

BlogHow-to

How to Read Cookies in JavaScript

Read JavaScript-visible cookies with document.cookie, parse values safely, and understand which cookies scripts cannot access.

By the ScreenshotNeo team4 October 20266 min read

Read cookies available to the current page with document.cookie. It returns a semicolon-separated string of name=value pairs, not a JavaScript object. Cookies marked HttpOnly are intentionally hidden from JavaScript, so they will not appear in this string.

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

For example, a page might see theme=dark; session_hint=abc. The exact cookies depend on the current document’s URL, cookie scope, browser policy, and cookie attributes.

Use the getter to read the current cookie string. To find one cookie, split on semicolons, trim whitespace, and match the requested name at the first equals sign. Slicing after the name preserves any additional equals signs in the value.

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); // "dark" or undefined

This parser returns the serialized value. If your application encodes cookie values, decode them only using the format your application chose. For example, use decodeURIComponent(value) only when the value was encoded with the corresponding URI encoding convention.

Do not split an entry on every equals sign: values can contain equals signs. Also do not treat a cookie value as trusted input; users can inspect and modify cookies that are accessible to client-side script.

2. Read all JavaScript-visible cookies

The getter returns a string. A small helper can turn it into entries while preserving extra equals signs in each value:

function readVisibleCookies() {
  const result = Object.create(null);

  for (const part of document.cookie.split(";")) {
    const entry = part.trim();
    if (!entry) continue;

    const equalsAt = entry.indexOf("=");
    if (equalsAt < 0) continue;

    const name = entry.slice(0, equalsAt).trim();
    const value = entry.slice(equalsAt + 1);
    result[name] = value;
  }

  return result;
}

console.log(readVisibleCookies());

This is application code, not a built-in browser parser. Cookie names and values follow cookie syntax rules; avoid assuming arbitrary Unicode or JSON can be stored raw. Choose and consistently apply an encoding when setting application-defined values.

3. Understand what JavaScript can and cannot see

Attribute or scope Effect JavaScript visibility
HttpOnly Prevents script APIs from reading the cookie. Hidden from document.cookie, but the browser can still send it with eligible HTTP requests.
Secure Restricts transmission to secure HTTPS connections, subject to browser behavior for localhost. Does not itself make a cookie unreadable to JavaScript.
SameSite Controls sending cookies in cross-site contexts. Does not make a cookie an HttpOnly cookie. SameSite=None requires Secure.
Domain and Path Influence the hosts and request paths to which the cookie applies. Path is not a security boundary that prevents scripts on other paths from reading a cookie.

For session credentials that do not need client-side access, prefer server-set HttpOnly cookies. This reduces the ability of injected script to steal the cookie value. JavaScript should not expose a session secret just to make it available to application code.

If a request uses an HttpOnly cookie, let the browser attach it to eligible requests and configure the server and request credentials policy for the intended origin relationship. Reading document.cookie is not a way to inspect outgoing request headers.

document.cookie is an accessor with a getter and setter. Reading it returns the available cookie string; assigning to it asks the browser to set or update one cookie. It does not replace the entire cookie list.

document.cookie = "theme=dark; Path=/; SameSite=Lax; Secure";

Set only values that the page genuinely needs to manage. JavaScript cannot set the HttpOnly attribute; that attribute must be added by the server in a Set-Cookie response header. Cookie scope, expiry, and security should be designed on the server as well as in client code.

document.cookie is synchronous. Cookie access can block the main thread, particularly when browser work crosses processes or requires I/O. For infrequent reads, the simple getter is often adequate. For code that frequently manages cookies, consider the asynchronous Cookie Store API where it is available, and verify support in the browsers and execution contexts you target.

The APIs serve the same general purpose of managing cookies, but the Cookie Store API is asynchronous and has different availability constraints. Do not switch without checking your target browser support and execution context.

6. Troubleshooting

Symptom Likely cause What to do
A cookie is missing from document.cookie. It is marked HttpOnly, outside the current document’s applicable scope, expired, or unavailable under browser cookie policy. Check the response’s Set-Cookie attributes and the current page host and path. If it is a session cookie, its invisibility may be intentional.
The cookie value is truncated or parsed incorrectly. The parser split on every =, or did not trim whitespace after semicolons. Split entries at semicolons, trim each entry, then split at the first equals sign only.
Assigning to document.cookie removed other cookies. The setter was treated like a whole-list replacement. Each assignment sets one cookie. Read back the current visible string to inspect the resulting list.
A cookie is not sent with a request. Its Secure, SameSite, domain, path, expiry, or browser policy conditions do not match the request. Inspect the cookie attributes and the request context. For cross-site use, review SameSite requirements; None must be paired with Secure.
Code cannot set HttpOnly. Client-side JavaScript is not permitted to add this server-controlled attribute. Set the cookie in an HTTP response using the server’s Set-Cookie header.
Frequent reads cause UI stalls. The synchronous getter can block the main thread. Reduce repeated reads, cache values when appropriate, or evaluate the asynchronous Cookie Store API for supported environments.

7. Practical checklist

  • Use document.cookie only for cookies that client-side code needs to read.
  • Keep session secrets HttpOnly whenever JavaScript does not need them.
  • Parse semicolon-separated entries after trimming whitespace, and preserve equals signs after the first one.
  • Choose Secure, SameSite, domain, path, and expiry attributes for the actual request flows.
  • Treat script-readable values as untrusted input.
  • Check browser and context support before relying on the asynchronous Cookie Store API.

8. Or skip the browser setup

If your task is to capture a page rather than inspect its cookie values, ScreenshotNeo is a website screenshot API and MCP server. It can accept cookie and consent banners like a visitor, then remove 60+ known consent platforms, newsletter popups, and chat widgets before the capture. Each cleanup step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with the outcome reported in response headers. Its MCP server gives AI agents tools to take screenshots, get page info, and capture PDFs.

One GET request returns an image or PDF. See the ScreenshotNeo API documentation for the available options.

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

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write("shot.webp", res);

The Node.js example uses the supplied fetch call and Bun’s file writer to save the returned bytes. In Node.js, use your preferred filesystem method to write the response body to a file.

The Free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is on every plan. Sign up for 1,000 free screenshots a month, no card required.

9. FAQ

No. In particular, HttpOnly cookies are hidden from script. Scope and browser policy also affect which cookies are available to a document.

No. It is a serialized semicolon-separated string. Parse it before using individual values.

No. Secure governs secure transport. HttpOnly is the attribute that blocks JavaScript access.

Not necessarily. A request may include an HttpOnly cookie that is deliberately unavailable to JavaScript. Let the browser manage eligible cookies and handle authentication on the server.

Sources