Cookies are small name=value pairs the browser stores for a site. JavaScript reads and writes non-HttpOnly cookies through document.cookie. The server can also set them with Set-Cookie response headers.
Note Write ≠ read
document.cookie is an accessor: assigning sets one cookie; reading returns a semicolon-separated list of visible name=value pairs — not the string you just wrote.
Remember
document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax"
document.cookie → "theme=dark; …" // getter: all visible pairs
write → one cookie per assignment
read → parse the full string
delete → same path + max-age=0
Treat cookies as a tiny lifecycle: write attributes carefully, parse on read, and match path when updating or deleting.
Write with name=value, path=/, and max-age when persistence matters.
Encode values with encodeURIComponent; decode when reading.
Parse document.cookie by splitting on ";" and the first =.
Delete by rewriting with max-age=0 and the same path.
Piece
Required?
Role
name=value
Yes
Cookie identity and payload
path
Recommended
URL scope — prefer /
max-age / expires
Optional
Lifetime vs session; 0 deletes
SameSite / Secure
Recommended
Cross-site and HTTPS safety
Pseudocode
Pseudocode
// WRITE
document.cookie = name + "=" + encode(value)
+ "; path=/; max-age=SECONDS; SameSite=Lax"
// READ
for each part in document.cookie.split(";"):
name, value = split on first "="
if name matches: return decode(value)
// DELETE
document.cookie = name + "=; path=/; max-age=0"
Reference
Cheat Sheet
Keep these cookie facts handy.
Topic
Detail
API
document.cookie (getter + setter)
One write
Creates or updates one cookie
Session
Omit max-age and expires
7 days
max-age=604800
Delete
max-age=0 + matching path
HttpOnly
Server-only — invisible to JS
Size
Keep values tiny (~4 KB practical limit)
Try it
Live Preview
Write, read, or delete a demo theme cookie in this browser, then inspect document.cookie.
Demo cookies use path=/ and SameSite=Lax. HttpOnly cookies never appear in document.cookie.
Result
Choose an action, then Run.
document.cookie → (current jar)
Code
JavaScript Examples
Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.
Example 1 — Write a Cookie
Create a site-wide preference cookie that lasts seven days.
JavaScript
document.cookie =
"theme=dark; path=/; max-age=604800; SameSite=Lax";
console.log(document.cookie);
// "theme=dark" (plus any other visible cookies)
Assign once. One document.cookie = … writes one cookie.
Add path=/. The cookie is available on every page of this origin.
Set max-age.604800 seconds keeps it for seven days.
Read back names only. Attributes never appear in the getter string.
Example 2 — Read a Cookie by Name
Parse document.cookie and return one value safely.
JavaScript
function getCookie(name) {
var parts = document.cookie.split(";");
for (var i = 0; i < parts.length; i++) {
var part = parts[i].trim();
var eq = part.indexOf("=");
if (eq === -1) continue;
if (part.slice(0, eq) === name) {
return decodeURIComponent(part.slice(eq + 1));
}
}
return null;
}
document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax";
console.log(getCookie("theme")); // "dark"
Default path is the current directory. Cookies then “vanish” on other routes — see Cookie Path.
HttpOnly
Secrets stay on the server
Auth tokens should be HttpOnly via Set-Cookie. Anything in document.cookie is visible to page scripts.
encode
Raw spaces / semicolons
Unencoded values can truncate the cookie string. Always encode user text.
size
Cookies ride on every request
Large values slow HTTP. Prefer short lifetimes and tiny payloads; use localStorage for client-only data.
Compatibility
Browser Support
Reading and writing cookies via document.cookie is a long-standing DOM feature. max-age, path, Secure, and SameSite are supported in all modern browsers.
✓ Baseline · DOM
document.cookie
Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Prefer max-age + path=/ + SameSite=Lax for new code; add Secure on HTTPS.
99%Universal API
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
document.cookieExcellent
Bottom line: Safe for production. Keep values small, encode carefully, and never store secrets in script-readable cookies.
MDN notes that document.cookie is synchronous. For modern async APIs, see the Cookie Store API.
Summary
Key Takeaways
Role: use document.cookie to write one cookie and read the visible jar.
Defaults: prefer path=/, max-age when persistent, and SameSite=Lax.
Parse carefully: split on ";", trim, and split on the first =.
Secrets: keep auth tokens HttpOnly on the server — not in JS-readable cookies.
One line: write with name=value; path=/; max-age=…; SameSite=Lax, parse to read, delete with max-age=0, and never store secrets in script-readable cookies.
FAQ
Frequently Asked Questions
What are cookies in JavaScript?
Cookies are small name=value pairs the browser stores and may send back to the server on matching requests. In JavaScript you read and write non-HttpOnly cookies through document.cookie.
How do I set a cookie with JavaScript?
Assign a string: document.cookie = "theme=dark; path=/; max-age=604800; SameSite=Lax". Each assignment creates or updates one cookie.
How do I read a cookie by name?
Read document.cookie, split on ";", trim each part, and match the name before the first "=". A small getCookie(name) helper makes this easier.
How do I delete a cookie?
Overwrite it with an empty value and max-age=0 (or a past expires), using the same path (and domain) as when it was set: document.cookie = "name=; path=/; max-age=0".
Can JavaScript read HttpOnly cookies?
No. HttpOnly cookies are set by the server via Set-Cookie and are hidden from document.cookie. That reduces XSS token theft.
When should I use localStorage instead of cookies?
Use localStorage for client-only data that the server does not need on every request. Prefer cookies when the value must travel with HTTP requests or when the server sets HttpOnly session cookies.