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.
Code
// 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
Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.