document.cookie Reads And Writes Cookies

Assign name=value pairs with max-age and path, then read the whole jar back as one string split on semicolons — encodeURIComponent keeps awkward values intact.

JavascriptSecurity Boundaries

Code

javascriptsnippet
29 lines
// document.cookie exposes the cookie jar as one flat string; writes
// merge into existing pairs and expired pairs disappear on read
document.cookie = 'theme=dark; max-age=3600; path=/';
document.cookie = 'locale=zh-CN; max-age=31536000; path=/; samesite=lax';
document.cookie = 'flash=1; max-age=0'; // already expired, never appears

// Read one cookie: split the jar into pairs and match the name prefix
function readCookie(name) {
  const prefix = `${encodeURIComponent(name)}=`;
  for (const pair of document.cookie.split('; ')) {
    if (pair.startsWith(prefix)) {
      return decodeURIComponent(pair.slice(prefix.length));
    }
  }
  return null;
}

// Write one cookie: encode the value, then attach the attributes
function writeCookie(name, value, maxAgeSeconds) {
  document.cookie =
    `${encodeURIComponent(name)}=${encodeURIComponent(value)}; ` +
    `max-age=${maxAgeSeconds}; path=/; samesite=lax`;
}

writeCookie('currency', 'EUR;GBP', 86400); // semicolons survive encoding
console.log('currency:', readCookie('currency'));
console.log('theme:', readCookie('theme'));
console.log('expired:', readCookie('flash'));
console.log('jar contains locale:', document.cookie.includes('locale='));

Tracing the logic

The short read: the functions readCookie and writeCookie, doing all the work.

The cycling part of this snippet is for (const pair of document.cookie.split('; ')).

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

Entry signature: function readCookie(name)

Output lines are prefixed (currency:, theme:, expired:), so you can tell which step produced each line.

Key statements

return decodeURIComponent(pair.slice(prefix.length));

Interactive Tools for This Topic

FAQ

Does document.cookie Reads And Writes Cookies run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.