Cookies let web apps remember preferences, sessions, and lightweight state between page loads. This hub covers 5 focused tutorials on writing, reading, updating, path scope, and expiration — plus security basics every beginner should know.
01
Write
document.cookie
02
Read
getCookie()
03
Update
Overwrite
04
path
URL scope
05
max-age
Lifetime
06
5 guides
Full index
Fundamentals
Introduction
Cookies are small text files the browser stores and attaches to HTTP requests for your site. They are ideal for session IDs, theme preferences, and “remember me” flags—not for large data (see localStorage for bigger client storage).
What Are Cookies?
Each cookie is a name=value pair plus optional attributes (path, max-age, Secure, SameSite). JavaScript reads and writes cookies through the document.cookie API. The server can also set cookies via the Set-Cookie response header.
💡
Beginner Tip
document.cookie returns all visible cookies as one semicolon-separated string. Setting a cookie only changes one name at a time—it does not replace every cookie on the page.
Key Features
Small size — about 4 KB per cookie; keep values short.
Expiration — session cookies die with the tab; persistent cookies use max-age or expires.
Scope — path and domain limit where the browser sends the cookie.
Automatic sending — matching cookies ride along on every request to your server (unlike localStorage).
Storage Limitations
~4 KB per cookie value (rough limit; browsers may vary slightly).
~20–50 cookies per domain (browser-dependent).
Same-origin rules — scripts on other domains cannot read your cookies.
Without path, the default path is the current URL directory. For site-wide cookies, always add path=/.
Example 2 — Read a Cookie by Name
Parse the cookie string to extract one value.
JavaScript
function getCookie(name) {
const prefix = name + "=";
const parts = decodeURIComponent(document.cookie).split(";");
for (const part of parts) {
const trimmed = part.trim();
if (trimmed.startsWith(prefix)) {
return trimmed.slice(prefix.length);
}
}
return "";
}
console.log(getCookie("username"));
Encoding names and values avoids breaking the cookie string when data contains =, ;, or spaces. Always use path=/ unless you intentionally scope to a subdirectory.
Tips
💬 Usage Tips
Always set path=/ for site-wide preferences unless you need a subdirectory scope.
Encode values with encodeURIComponent when they contain special characters.
Inspect in DevTools — Application tab → Cookies shows every attribute.
Match attributes on delete — same path and domain as when created.
Search this index — jump to any of 5 focused tutorials above.
Watch Out
⚠️ Common Pitfalls
Duplicate cookies — different path values create two cookies with the same name.
Storing passwords — never put credentials or JWTs in JS-readable cookies.
Assuming HttpOnly from JS — only the server can set HttpOnly via Set-Cookie.
Large payloads — cookies are not for big JSON blobs; use localStorage or the server.
Third-party context — modern browsers restrict cross-site cookies; plan for SameSite rules.
🧠 How Browser Cookies Work
1
Set cookie
JavaScript assigns document.cookie or the server sends Set-Cookie.
Create
2
Browser stores it
The cookie jar keeps name, value, path, domain, expiry, and flags.
Store
3
Sent on requests
Matching cookies attach to HTTP requests automatically via the Cookie header.
Send
=
🍪
Stateful browsing
Sessions and preferences persist across page loads without URL parameters.
Compatibility
Browser Support
document.cookie is supported in every browser and Node.js (with a document shim in tests). Attribute support for SameSite and Secure follows modern browser rules — always test in current Chrome, Firefox, and Safari.
✓ Baseline · Universal
document.cookie API
Supported in Chrome, Firefox, Safari, Edge, IE 6+, Opera, and all modern Node.js test environments. Privacy settings and third-party blocking may limit cross-site cookies regardless of API support.
100%Core 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.cookieUniversal
Bottom line: Safe to use for client-readable cookies everywhere. HttpOnly cookies are server-set only; SameSite and Secure attributes require modern browsers for full behavior.
Wrap Up
🎉 Conclusion
JavaScript cookies are a simple way to persist small pieces of state on the client. Master document.cookie, path scope, and expiration first, then explore the 5 focused tutorials for deeper patterns.
Handle cookies carefully: encode values, avoid secrets, and use server-set HttpOnly cookies for session tokens whenever possible.
Cookies are small text key=value pairs the browser stores and sends back to the server on matching requests. In JavaScript you access them through document.cookie — a string containing all cookies for the current page's URL scope.
Assign to document.cookie: document.cookie = "name=value; path=/; max-age=604800". Each assignment sets or updates one cookie. Add path, max-age, Secure, or SameSite as needed.
No. HttpOnly cookies are set by the server and hidden from document.cookie. That is intentional — it reduces XSS token theft. Only non-HttpOnly cookies are visible to scripts.
Overwrite it with an empty value and a past expiration: document.cookie = "name=; path=/; max-age=0". The path (and domain if used) must match how the cookie was originally set.
expires is an HTTP-date string in UTC. max-age is lifetime in seconds from now. Prefer max-age for simpler math. Omit both for a session cookie removed when the browser closes.
Read the overview, try the five examples, then open Write cookies from Cookie Operations. Use the search box to jump to any of the five topic tutorials.
Did you know?
Setting document.cookie never removes other cookies — it only creates or updates the cookie whose name you specify. To wipe everything, you must delete each name individually or use DevTools.