Cookies
What are cookies?
Section titled “What are cookies?”Cookies are small strings — each up to about 4 KB — that the browser stores per-domain and automatically includes in every matching HTTP request. This automatic network transmission is what sets cookies apart from every other browser storage mechanism.
When your server sends a Set-Cookie response header, the browser stores that cookie and sends it back on every subsequent request to that domain (subject to the cookie’s Path, Domain, Secure, and SameSite attributes).
When your JavaScript calls document.cookie = 'name=value', it sets a cookie on the client side — but the browser will still send that cookie to your server on the next request.
Client-set vs server-set cookies
Section titled “Client-set vs server-set cookies”There are two ways a cookie ends up in the browser’s cookie jar:
Server-set (via Set-Cookie header):
HTTP/1.1 200 OKSet-Cookie: session=abc123; HttpOnly; Secure; SameSite=StrictThe server controls the cookie’s value and attributes. An HttpOnly cookie is completely invisible to JavaScript — document.cookie will never return it.
Client-set (via document.cookie):
document.cookie = 'theme=dark; Max-Age=86400; SameSite=Lax';JavaScript can set, read, and delete cookies that are not marked HttpOnly.
Cookie flow
Section titled “Cookie flow”flowchart LR Browser -->|HTTP Request + Cookie header| Server Server -->|HTTP Response + Set-Cookie header| Browser Browser -->|stores| CookieJar[(Cookie Jar)] CookieJar -->|sent on every matching request| Server
Cookies vs Web Storage: when to use which
Section titled “Cookies vs Web Storage: when to use which”The single most important question is: does the server need this value?
| Use case | Best choice | Why |
|---|---|---|
| Auth token / session ID | Cookie (HttpOnly + Secure) | Server needs it; HttpOnly prevents XSS theft |
| CSRF token | Cookie | Server sets it; JS reads it to include in request body |
| User preferences (theme, language) | Web Storage | Client-only; no need to send to server on every request |
| Shopping cart (client-only) | Web Storage or IndexedDB | Larger, richer data; no network overhead |
| Feature flags from server | Cookie | Server can vary response before JS loads |
The fundamental rule: cookies for anything the server must receive; Web Storage for client-only UI state.
What this module covers
Section titled “What this module covers”| Lesson | What you will learn |
|---|---|
| This page | What cookies are, cookie flow, and cookies vs Web Storage |
what-are-cookies | name=value format, size limits, per-domain count limits, automatic request inclusion |
reading-writing | document.cookie quirks, get/set/delete helpers, runnable demo |
attributes-and-samesite | Expires, Max-Age, Path, Domain, Secure, HttpOnly, SameSite |
cookie-store-api | The async cookieStore API and feature-detect fallback |