</>
Skip to content
JavaScript lessons (61/64)

JavaScript — Cookies

What cookies are

Small key-value strings a site stores in the browser — automatically attached to matching HTTP requests. Classic jobs:

sessions · preferences · authentication state · analytics

The awkward API: document.cookie

Reading returns ALL cookies as one string:

console.log(document.cookie);
// "theme=dark; language=en"

Setting writes ONE cookie (assignment never replaces the others!):

document.cookie = "theme=dark";
document.cookie = "language=en";    // both now exist

Expiration & lifetime

// session cookie — dies when browser closes:
document.cookie = "tmp=1";

// fixed date:
document.cookie = "theme=dark; expires=Wed, 31 Dec 2026 23:59:59 GMT";

// relative seconds (preferred):
document.cookie = "theme=dark; max-age=3600";      // one hour

// deletion = expired + matching path:
document.cookie = "theme=; max-age=0; path=/";

Scope & security attributes

document.cookie =
    "pref=compact; path=/; Secure; SameSite=Lax";
AttributeMeaning
path=/visible across whole site (default = current dir)
SecureHTTPS-only transmission
SameSite=Lax/Strict/Nonecross-site request behavior (CSRF defense)
HttpOnlyinvisible to JavaScript — server-set only

The auth pattern: sensitive session cookies are set by the server with HttpOnly; Secure; SameSite=Lax. HttpOnly means XSS scripts can't steal them — that's why real auth lives server-side.

Parsing document.cookie

const cookies = Object.fromEntries(
    document.cookie.split("; ").map(c => c.split("="))
);

cookies.theme;   // "dark"

Encode values containing special characters:

document.cookie = `msg=${encodeURIComponent("hello world")}`;
decodeURIComponent("hello%20world");

Cookies vs localStorage

CookieslocalStorage
Sent to serverautomatically per-requestnever
Size~4KB~5–10MB
Expirycontrollableuntil cleared
JS-readableunless HttpOnlyalways
Best forsession/auth (server-set)client preferences/data

Rule: server needs it → cookie; only the page needs it → localStorage.

Mini Practice

  1. Set two cookies; read them back via the parse helper.
  2. Set max-age=10; watch it vanish.
  3. Delete one correctly (match its path).
  4. Encode/decode a value with spaces and =.
  5. Store a theme in localStorage vs cookie — list which fits and why.
  6. Explain in one line each: HttpOnly, Secure, SameSite.

Next: events →

Related Topics

Frequently Asked Questions about Cookies

What is Cookies in JavaScript?

Cookies is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Cookies?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Cookies.

Why is Cookies important in JavaScript?

Cookies is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.