Skip to content

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.

There are two ways a cookie ends up in the browser’s cookie jar:

Server-set (via Set-Cookie header):

HTTP/1.1 200 OK
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict

The 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.

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 are stored in the browser's cookie jar and sent automatically on every matching HTTP request

The single most important question is: does the server need this value?

Use caseBest choiceWhy
Auth token / session IDCookie (HttpOnly + Secure)Server needs it; HttpOnly prevents XSS theft
CSRF tokenCookieServer sets it; JS reads it to include in request body
User preferences (theme, language)Web StorageClient-only; no need to send to server on every request
Shopping cart (client-only)Web Storage or IndexedDBLarger, richer data; no network overhead
Feature flags from serverCookieServer can vary response before JS loads

The fundamental rule: cookies for anything the server must receive; Web Storage for client-only UI state.

LessonWhat you will learn
This pageWhat cookies are, cookie flow, and cookies vs Web Storage
what-are-cookiesname=value format, size limits, per-domain count limits, automatic request inclusion
reading-writingdocument.cookie quirks, get/set/delete helpers, runnable demo
attributes-and-samesiteExpires, Max-Age, Path, Domain, Secure, HttpOnly, SameSite
cookie-store-apiThe async cookieStore API and feature-detect fallback
What is the key difference between cookies and Web Storage (localStorage/sessionStorage)?
Which storage mechanism is best for storing an authentication session token that the server needs to validate?
Which mechanism should you use to store a user's preferred UI theme that is only needed by client-side JavaScript?