Ch 58 / 78
Chapter 58 Intermediate 6 min read JavaScript

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 you'll learn
What cookies are and how they work in the browser
How to set, read, update, and delete cookies with JavaScript
Cookie attributes — expires, max-age, path, domain
Security flags — Secure, HttpOnly, SameSite
Cookies vs localStorage vs sessionStorage
Reusable helper functions for cookie management

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:

Set Cookie
Write to Browser
Assign document.cookie with a key=value pair plus optional attributes. Each assignment adds or updates one cookie — it does not overwrite all cookies.
Example: document.cookie = "theme=dark; max-age=86400"
Read Cookie
Parse from String
Reading document.cookie returns all cookies as a single semicolon-separated string of key=value pairs. You must parse it to find a specific value.
Example: "username=Alice; theme=dark; lang=en"
Delete Cookie
Expire Immediately
To delete a cookie, set its expires attribute to a past date or set max-age=0. The browser removes it automatically.
Example: document.cookie = "username=; max-age=0"

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:

JavaScript — Reading Cookies
// ── 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;
}
Tip
Always use 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:

JavaScript — Update & Delete
// ── 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

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:

localStorage
Lifetime Forever until manually cleared
Size ~5–10 MB per origin
Sent to server No — client-only
JS access Yes — full access
Use for User settings, cached data, app state
sessionStorage
Lifetime Tab session — cleared on tab close
Size ~5–10 MB per origin
Sent to server No — client-only
JS access Yes — full access
Use for Wizard state, one-time data, form drafts

Security Best Practices

Cookies store sensitive data like session tokens, so security matters. Follow these practices to protect your users:

HttpOnly
Always set HttpOnly on auth cookies from the server. This prevents JavaScript from accessing the cookie, stopping XSS attacks from stealing session tokens.
Secure
Use the 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
Set 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.
Short max-age
Give auth cookies a short max-age and refresh them on each login. Long-lived cookies are more dangerous if compromised.
HTTP — Secure Cookie from Server (Set-Cookie header)
// ── 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:

Session Authentication
Server sets an HttpOnly session cookie after login. The browser sends it on every request so the server knows who you are.
User Preferences
Store theme (dark/light), language, or region settings so preferences persist across browser restarts and are available server-side for SSR.
CSRF Protection
A CSRF token stored in a SameSite=Strict cookie protects state-changing requests (POST, PUT, DELETE) from cross-site forgery attacks.
Shopping Cart
E-commerce sites store a cart ID in a cookie so items persist between visits and are sent to the server to load the correct cart.
Analytics Tracking
Analytics tools use cookies with long expiry to track returning visitors, session counts, and user journeys across multiple visits.
Cookie Consent
A cookie remembers that a user accepted or declined the GDPR consent banner so it doesn't appear on every page load.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Cookies, localStorage & Web Storage — all on one page.
Get Sheet

Try It — Live Editor

Experiment with cookies below. Set, read, update and delete cookies and watch the cookie viewer update in real time.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These practical cookie patterns will cover almost every real-world scenario you'll encounter:

JavaScript — Cookie Utility Library
// ── 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
Quick Check
What does document.cookie = "a=1" do when other cookies already exist?
Quick Check
Which cookie attribute prevents JavaScript from accessing the cookie value via document.cookie?
Chapter Summary
  • 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.cookie which returns a semicolon-separated string. You must parse it to find a specific cookie value.
  • Delete a cookie by setting max-age=0 or an expires date 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 and decodeURIComponent() 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel