Learn JavaScript
❯ browser_dom.cookies

Cookies (document.cookie) in JavaScript

$concept

Cookies are small server-readable client storage: document.cookie reads all visible cookies as one semicolon-joined string (parse it yourself), while assignment (document.cookie = "k=v; Max-Age=3600; Path=/") sets with attributes — Expires/Max-Age lifetime, Path/Domain scope, Secure (HTTPS-only), SameSite (CSRF policy).

HttpOnly cookies stay invisible to JavaScript entirely (XSS-proof session tokens — set them server-side), and ~4KB per-cookie limits plus per-request overhead make cookies wrong for large data (use storage/IndexedDB). Modern defaults (Lax SameSite) secure the common cases automatically.

$how it works
1

Read all, write one

document.cookie returns every visible cookie joined — assignment sets exactly one cookie per statement.

2

Attributes control scope

Max-Age/Expires lifetime, Path/Domain visibility, Secure transport, SameSite cross-site policy.

3

HttpOnly hides from JS

Server-set HttpOnly session cookies never reach document.cookie — XSS cannot steal what JS cannot read.

4

Small and server-bound

~4KB each, sent on every request — session IDs and prefs, never bulk data or secrets in JS-reachable form.

$example
document.cookie = "theme=dark; Max-Age=31536000; Path=/";
console.log(document.cookie.includes("theme=dark"));
Output
true
1Assignment sets one year-lived, site-wide cookie (not overwriting others).
2Reading returns the joined jar — includes finds the theme pair.
3The browser will now send theme=dark with every same-site request for a year.
$use cases
Server-readable session and preference persistence
HttpOnly session tokens immune to script theft
SameSite policies blocking cross-site request forgery
Small data only — bulk client state belongs in storage/IndexedDB

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.