Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 156 ยท Browser APIs

Cookies

Read, write and delete cookies with document.cookie, understand Expires, Max-Age, Path, Domain, Secure, SameSite and HttpOnly, and meet the Cookie Store API.

A cookie is a small piece of text that a website asks the browser to store and then send back with every request to that site. Cookies are how a server recognizes you between page loads: your login session, your shopping cart, the language you picked. They are older than almost every other browser storage feature, and they're still the backbone of logins on the web.

JavaScript can read and write cookies too, through document.cookie and the newer Cookie Store API. But cookies come with unusual rules, a famously awkward API and real security consequences. This lesson explains how they work, when to use them instead of localStorage, and how to set them safely.

How cookies travel

Cookies live in the browser but exist mainly for the server. The flow looks like this:

  1. The server answers a request with a Set-Cookie header.
  2. The browser stores the cookie for that site.
  3. On every later request to that site, the browser adds a Cookie header containing the matching cookies.
HTTP
HTTP/1.1 200 OK
Set-Cookie: session=8f2c91ab; Path=/; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Max-Age=31536000; Path=/

GET /account HTTP/1.1
Host: shop.example.com
Cookie: session=8f2c91ab; theme=dark

That automatic sending is what makes cookies different from localStorage. It's perfect for session ids, but it also means every cookie you add is uploaded with every request, including requests for images and scripts. Keep cookies few and small: each one is limited to about 4 KB, and browsers cap the number per site.

The sandbox and these examples

The editors on this site can't use cookies. They run in a sandboxed frame with an opaque origin, which has no cookie storage at all: reading document.cookie throws a SecurityError. So the cookie code below is read-only, and the live examples work on cookie strings instead. The parsing and building logic is exactly what you'd use on a real page.

JS Cookies are blocked in the sandbox

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading cookies with document.cookie

document.cookie is a strange property. Reading it gives you one string with all cookies visible to the current page, as name=value pairs separated by "; ". You don't get their expiry dates, paths or any other attributes, only names and values:

JavaScript
document.cookie;
// "theme=dark; cart_items=3; consent=analytics%3Dno"

To find one cookie, you split that string yourself. A small parser that decodes values is worth keeping around:

JS Parsing a cookie string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Splitting at the first = only matters: values may legally contain =. Like URL parameters, cookie values are always strings, so convert them as needed.

Writing cookies

Writing is the other strange half. Assigning to document.cookie does not replace the whole string. It sets or updates one cookie, described in the same format as a Set-Cookie header: name=value, followed by optional attributes.

JavaScript
document.cookie = "theme=dark; Max-Age=31536000; Path=/; SameSite=Lax";
document.cookie = "cart_items=3; Path=/";   // the theme cookie stays

document.cookie;  // "theme=dark; cart_items=3"

Cookie values can't contain semicolons, commas or spaces, so encode anything that isn't a simple word with encodeURIComponent(). Building the string by hand is error-prone; a small helper keeps it tidy:

JS A safe cookie-string builder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There is no "delete" method. To remove a cookie, you set it again with the same name, path and domain and an expiry in the past (Max-Age=0 is the clearest way). If the path or domain doesn't match, you create a second cookie instead of deleting the first, which is a common source of "cookie that won't go away" bugs.

The attributes decide how long a cookie lives, which requests carry it and who can read it.

Attribute What it does
Expires=<date> Deletes the cookie at that date (in UTC, from toUTCString()).
Max-Age=<seconds> Deletes it after that many seconds. Wins over Expires if both are set. 0 or negative deletes now.
Path=/some/path Sends the cookie only for URLs under that path. Use Path=/ for the whole site.
Domain=example.com Also sends it to subdomains (shop.example.com, blog.example.com). Leave it out to limit the cookie to the exact host, which is safer.
Secure Sends the cookie only over HTTPS.
SameSite=Strict / Lax / None Controls whether the cookie is sent on requests that come from other sites (see below).
HttpOnly Hides the cookie from JavaScript entirely. Only the server can set this.
Partitioned Keeps a third-party cookie separate per top-level site (newer; used for embedded widgets).

Without Expires or Max-Age, a cookie is a session cookie: it's deleted when the browser session ends. (Some browsers restore sessions on restart, so "session" can last longer than you expect.)

SameSite

SameSite is one of the most important security settings on the web. It decides whether the browser attaches the cookie when a request to your site is triggered by another site, for example a form on evil.example that posts to bank.example:

  • Strict: only sent when the request starts on your own site. Even following a link from another site to yours arrives without the cookie.
  • Lax: also sent on top-level navigations from other sites using safe methods like clicking a link (GET), but not on cross-site form posts, iframes, images or fetch. This is the default in Chromium-based browsers when you don't set it, and the right choice for most session cookies.
  • None: sent with every cross-site request. It must be combined with Secure, and is needed only for genuine third-party use, such as an embedded widget. Many browsers restrict or block third-party cookies regardless.

SameSite=Lax or Strict is a strong defense against cross-site request forgery (CSRF), where another site tricks your browser into sending an authenticated request. The security lesson puts this together with other defenses.

HttpOnly: why session cookies hide from JavaScript

A cookie marked HttpOnly never appears in document.cookie, and JavaScript can't set, change or delete it. That sounds like a limitation, but it's a vital protection: if an attacker manages to inject a script into your page (an XSS attack), that script can't steal the session cookie.

So the rule for logins is: the server sets the session cookie with HttpOnly; Secure; SameSite=Lax, and your JavaScript never touches it. Use JavaScript-readable cookies only for harmless preferences that the server also needs, such as a theme or language.

Two special name prefixes make the browser enforce safe settings:

  • __Secure-name is accepted only with Secure, from an HTTPS page.
  • __Host-name additionally requires Path=/ and no Domain, so the cookie is locked to one exact host and can't be overwritten by a subdomain.
HTTP
Set-Cookie: __Host-session=8f2c91ab; Path=/; Secure; HttpOnly; SameSite=Lax

To see how the browser matches cookies to requests, here's a simplified cookie jar in plain JavaScript. It handles Path and Max-Age the way a browser does, so you can experiment with them even though the sandbox has no real cookies:

JS Simulating how a browser stores and sends cookies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that /shopping doesn't get the /shop cookie: paths match whole segments. Real browsers also check the domain, Secure, SameSite and more, but the core idea is the same.

document.cookie is synchronous, string-based and gives no way to see when a cookie changes. The newer Cookie Store API fixes all three with a promise-based interface on cookieStore:

JavaScript
if ("cookieStore" in window) {
  await cookieStore.set({
    name: "theme",
    value: "dark",
    expires: Date.now() + 365 * 24 * 60 * 60 * 1000, // a timestamp in ms
    sameSite: "lax",
  });

  const theme = await cookieStore.get("theme"); // { name, value, ... } or null
  console.log(theme?.value);

  const all = await cookieStore.getAll();
  await cookieStore.delete("theme");

  cookieStore.addEventListener("change", (event) => {
    console.log("changed:", event.changed, "deleted:", event.deleted);
  });
}

It only works on secure (HTTPS or localhost) pages, it still can't see HttpOnly cookies, and it is also available inside service workers. It has been in Chromium-based browsers for several years and reached Safari and Firefox more recently, so feature-detect it and keep a document.cookie fallback if you support older browsers.

Cookies or Web Storage?

Cookies localStorage / sessionStorage
Sent to the server Automatically, with every request Never
Size About 4 KB per cookie About 5 MB per origin
Can hide from JavaScript Yes, HttpOnly No
Expiry Expires / Max-Age localStorage: never; sessionStorage: tab close
Best for Sessions and data the server needs Client-only preferences and drafts

A simple rule: if the server needs it on every request, use a cookie (ideally set by the server). If only your JavaScript needs it, use Web Storage or IndexedDB, and save the bandwidth.

Privacy laws apply. In many regions, including the EU and UK, storing non-essential data on a user's device (analytics or advertising cookies, but also localStorage used for tracking) needs the user's consent first. Strictly necessary cookies, such as a login session or a shopping cart, are generally exempt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does document.cookie = "lang=fr; Path=/" do?

    Each assignment to document.cookie sets one cookie. Reading the property returns all visible cookies as one string.
  2. 2. Why should a login session cookie be marked HttpOnly?

    HttpOnly cookies are invisible to JavaScript. The browser still sends them to the server.
  3. 3. Which SameSite value requires the Secure attribute?

    SameSite=None sends the cookie on cross-site requests, so browsers insist it is only sent over HTTPS.
  4. 4. You set token=abc; Path=/app and later try to delete it with token=; Max-Age=0; Path=/. What happens?

    A cookie is identified by name, path and domain. Deleting requires the same path; otherwise you address a different cookie.
  5. 5. What does reading document.cookie in this site's sandboxed editors do?

    Sandboxed frames without allow-same-origin have an opaque origin, and accessing cookies there throws.

Summary

  • Cookies are small strings the browser stores per site and sends with every request in the Cookie header.
  • Reading document.cookie returns all visible name=value pairs; writing it sets one cookie with optional attributes.
  • Encode values with encodeURIComponent(); delete by re-setting with the same name, path and domain and Max-Age=0.
  • Secure, HttpOnly, SameSite=Lax and the __Host- prefix are the safe defaults for session cookies, which the server should set.
  • The Cookie Store API (cookieStore.get/set/delete, change events) is a modern promise-based alternative; feature-detect it.

Next: URLs, Location and History โ€” read and build URLs and change the address bar without reloading.