Cookies
A cookie is a small piece of
text data that the browser stores on the user's computer and automatically sends to the
server with every HTTP request. Unlike localStorage,
cookies have an expiry date, are sent with every request,
and support rich security attributes — making them the foundation of session management,
authentication, and user preferences on the web.
What Are Cookies?
Cookies are key-value pairs stored by the browser that the server can read on every HTTP request. They were designed to give the stateless HTTP protocol a memory — letting the server know who you are between requests:
document.cookie with a key=value pair plus
optional attributes. Each assignment adds or updates one cookie — it does not
overwrite all cookies.document.cookie returns all cookies as a
single semicolon-separated string of key=value pairs. You must parse it to find
a specific value.expires attribute to
a past date or set max-age=0. The browser removes it
automatically.Cookie Syntax & Anatomy
A cookie string is built from a name=value pair followed by semicolon-separated attributes. All attributes are optional except the name-value pair itself:
document.cookie = "username=Alice" + "; expires=Fri, 31 Dec 2025 23:59:59 GMT" + "; path=/" + "; domain=example.com" + "; Secure" + "; SameSite=Strict";
// Minimum valid cookie
document.cookie = "theme=dark"; // session cookie — deleted when browser closes
// ── Simple session cookie (deleted when browser closes) ─────
document.cookie = "username=Alice";
// ── Cookie with expiry date ──────────────────────────────────
const expires = new Date();
expires.setDate(expires.getDate() + 7); // 7 days from now
document.cookie = `theme=dark; expires=${expires.toUTCString()}; path=/`;
// ── Cookie with max-age (seconds) — simpler than expires ─────
document.cookie = "lang=en; max-age=86400; path=/"; // 86400 sec = 1 day
// ── Secure cookie (HTTPS only) ───────────────────────────────
document.cookie = "token=abc123; max-age=3600; path=/; Secure; SameSite=Strict";
// ── IMPORTANT: Each assignment sets ONE cookie ───────────────
document.cookie = "a=1"; // adds/updates cookie "a"
document.cookie = "b=2"; // adds/updates cookie "b" — does NOT replace "a"
// Now browser has both cookies: a=1 and b=2
document.cookie = "..." does not overwrite all existing
cookies. Each assignment only adds or updates the single named cookie. To see all cookies,
read document.cookie — it returns a string of all cookies joined by
"; ".
Reading Cookies
Reading document.cookie gives
you all cookies as one concatenated string — no values for attributes, just
name=value pairs. You need to parse this string to find a specific
cookie:
// ── What document.cookie returns ─────────────────────────────
// "username=Alice; theme=dark; lang=en"
console.log(document.cookie); // all cookies, semicolon-separated
// ── Parse a specific cookie value ────────────────────────────
function getCookie(name) {
const cookies = document.cookie.split(";");
for (let cookie of cookies) {
const [key, value] = cookie.trim().split("=");
if (key === name) return decodeURIComponent(value);
}
return null; // cookie not found
}
console.log(getCookie("theme")); // "dark"
console.log(getCookie("username")); // "Alice"
console.log(getCookie("missing")); // null
// ── Modern one-liner using find ──────────────────────────────
function getCookieModern(name) {
return document.cookie
.split(";")
.find(c => c.trim().startsWith(name + "="))
?.split("=")[1] ?? null;
}
encodeURIComponent() when setting a cookie value
and decodeURIComponent() when reading it, to safely handle
spaces, equals signs, semicolons, and special characters in the value.
Updating & Deleting Cookies
Updating a cookie is done by setting it again with
the same name — the browser overwrites the existing value. Deleting
requires setting the cookie with an expired date or max-age=0:
// ── Update: set the same name with a new value ───────────────
document.cookie = "theme=dark; max-age=86400; path=/"; // original
document.cookie = "theme=light; max-age=86400; path=/"; // updated!
// ── Delete using max-age=0 (simplest) ───────────────────────
document.cookie = "theme=; max-age=0; path=/";
// ── Delete using a past expires date ─────────────────────────
document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
// ── Reusable helper functions ────────────────────────────────
function setCookie(name, value, days = 7, path = "/") {
const maxAge = days * 24 * 60 * 60;
document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${maxAge}; path=${path}`;
}
function getCookie(name) {
return document.cookie.split(";")
.find(c => c.trim().startsWith(name + "="))
?.split("=")[1] ?? null;
}
function deleteCookie(name, path = "/") {
document.cookie = `${name}=; max-age=0; path=${path}`;
}
// ── Usage ────────────────────────────────────────────────────
setCookie("username", "Alice", 30); // set for 30 days
console.log(getCookie("username")); // "Alice"
deleteCookie("username"); // remove it
console.log(getCookie("username")); // null
Cookie Attributes
Cookie attributes control the lifetime, scope, and security of each cookie. They are appended to the name=value pair separated by semicolons:
| Attribute | Type | Description | Example |
|---|---|---|---|
| expires | optional | UTC date when the cookie expires. Without it, the cookie is deleted when the browser closes (session cookie). | expires=Fri, 31 Dec 2025 23:59:59 GMT |
| max-age | optional | Lifetime in seconds. Overrides expires if both are set.
0 or negative deletes the cookie immediately.
|
max-age=86400 (1 day) |
| path | optional | URL path the cookie is sent to. Default is the current path. Use /
to send it for all pages. |
path=/ |
| domain | optional | Domain that can receive the cookie. By default, only the exact domain. Add a leading dot to include subdomains. | domain=.example.com |
| Secure | security | Cookie sent only over HTTPS connections. Ignored on HTTP (except localhost). | Secure |
| HttpOnly | security | Cookie is inaccessible via JavaScript (document.cookie).
Server-only. Prevents XSS theft. Can only be set by the server. |
HttpOnly |
| SameSite | security | Controls cross-site sending. Strict = never cross-site,
Lax = safe cross-site navigation only (default), None
= always (requires Secure).
|
SameSite=Strict |
// ── Session cookie — lives until browser closes ──────────────
document.cookie = "sessionId=xyz789";
// ── Persistent cookie — lives 30 days ────────────────────────
document.cookie = "userId=42; max-age=2592000; path=/"; // 30*24*60*60
// ── Scoped to /admin path only ───────────────────────────────
document.cookie = "adminToken=abc; path=/admin; Secure";
// ── Shared across all subdomains ─────────────────────────────
document.cookie = "pref=dark; domain=.example.com; max-age=86400";
// ── Secure + SameSite for CSRF protection ────────────────────
document.cookie = "csrfToken=token123; max-age=3600; path=/; Secure; SameSite=Strict";
// ── Third-party cookie (SameSite=None requires Secure) ───────
document.cookie = "tracking=id; SameSite=None; Secure";
// ── HttpOnly cookies CANNOT be set from JS — server-side only
// Set-Cookie: authToken=secret; HttpOnly; Secure; SameSite=Strict
Cookies vs localStorage vs sessionStorage
All three browser storage mechanisms solve different problems. Choosing the right one depends on lifetime, server access, and storage size:
Security Best Practices
Cookies store sensitive data like session tokens, so security matters. Follow these practices to protect your users:
HttpOnly on auth cookies from the
server. This prevents JavaScript from accessing the cookie, stopping XSS attacks from
stealing session tokens.Secure flag so cookies are only sent over
HTTPS. This prevents man-in-the-middle attacks from intercepting cookie values on plain
HTTP.SameSite=Strict on sensitive cookies (like
CSRF tokens) to prevent them from being sent in cross-site requests, blocking Cross-Site
Request Forgery (CSRF) attacks.max-age and refresh them
on each login. Long-lived cookies are more dangerous if compromised.// ── Server sets a secure auth cookie (Node.js/Express) ───────
res.setHeader("Set-Cookie", "authToken=secret123; HttpOnly; Secure; SameSite=Strict; Max-Age=3600; Path=/");
// ── This cookie is INVISIBLE to document.cookie in the browser
console.log(document.cookie); // authToken will NOT appear here
// ── From JavaScript — avoid storing sensitive data in cookies
// ❌ BAD — do not store tokens from client-side JS
document.cookie = "authToken=secret123"; // XSS can read this!
// ✅ GOOD — use cookies only for non-sensitive preferences from JS
document.cookie = "theme=dark; max-age=2592000; path=/; SameSite=Lax";
// ── Always encode values to prevent injection ────────────────
const username = "Alice Smith";
document.cookie = `username=${encodeURIComponent(username)}; max-age=86400; path=/`;
// stores: username=Alice%20Smith
Real-World Use Cases
Cookies are the backbone of most web application state management. Here are the most common real-world scenarios:
Try It — Live Editor
Experiment with cookies below. Set, read, update and delete cookies and watch the cookie viewer update in real time.
Common Patterns & Recipes
These practical cookie patterns will cover almost every real-world scenario you'll encounter:
// ── Full cookie utility object ───────────────────────────────
const Cookie = {
// Set a cookie — days defaults to session if 0
set(name, value, days = 0, path = "/") {
let cookie = `${name}=${encodeURIComponent(value)}; path=${path}`;
if (days) cookie += ` ;max-age=${days * 86400}`;
document.cookie = cookie;
},
// Get a cookie value — returns null if not found
get(name) {
const match = document.cookie
.split(";")
.find(c => c.trim().startsWith(name + "="));
return match ? decodeURIComponent(match.split("=")[1]) : null;
},
// Check if a cookie exists
has(name) { return this.get(name) !== null; },
// Delete a cookie
delete(name, path = "/") {
document.cookie = `${name}=; max-age=0; path=${path}`;
},
// Get all cookies as an object
getAll() {
return Object.fromEntries(
document.cookie.split(";").filter(Boolean).map(c => {
const [k, ...v] = c.trim().split("=");
return [k, decodeURIComponent(v.join("="))];
})
);
}
};
// ── Usage examples ───────────────────────────────────────────
Cookie.set("theme", "dark", 30); // persist 30 days
Cookie.set("lang", "en-US"); // session cookie
Cookie.get("theme"); // "dark"
Cookie.has("lang"); // true
Cookie.getAll(); // { theme: "dark", lang: "en-US" }
Cookie.delete("theme"); // remove it
Cookie.has("theme"); // false
document.cookie = "a=1" do when other cookies already
exist?document.cookie?- A cookie is a small key-value string stored by the browser and sent to the server with every HTTP request — ideal for authentication and server-readable preferences.
- Set cookies via
document.cookie = "name=value; attributes". Each assignment adds or updates one cookie — it does not replace all cookies. - Read all cookies via
document.cookiewhich returns a semicolon-separated string. You must parse it to find a specific cookie value. - Delete a cookie by setting
max-age=0or anexpiresdate in the past on the same name and path. - Key attributes: expires / max-age (lifetime), path (URL scope), domain (subdomain sharing), Secure (HTTPS only), HttpOnly (server-only), SameSite (CSRF protection).
- Always use
encodeURIComponent()when setting anddecodeURIComponent()when reading to handle special characters safely. - Prefer localStorage for large client-side data and cookies for data that needs to be sent to the server. Cookies are limited to ~4 KB per cookie.
- Auth tokens should always be set as HttpOnly + Secure + SameSite=Strict from the server — never from client-side JavaScript.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.