skip to content

Cookies from JavaScript

You will learn the awkward document.cookie string API and, more importantly, what your script cannot see or do. Interviewers ask this to reach the HttpOnly answer: the cookie you most want is the one JS must never touch.

on this pageshow

questions

5

A single-page app cannot find its session cookie in `document.cookie` after login, yet its requests are authenticated. Why is that cookie invisible to script, and how should the app decide whether the user is signed in?

level: middleimportance: must knowfreq 66%

basics

~20 s

The server marked the cookie HttpOnly, so the browser withholds it from document.cookie while still attaching it to matching requests. The app should learn its signed-in state from an API call such as a session endpoint, never by looking for the cookie.

open as a page

A page already has three cookies. What happens when script runs `document.cookie = "theme=dark; path=/; max-age=3600"`, and which parts of that string can ever be read back?

level: middleimportance: must knowfreq 63%

basics

~20 s

Assigning to document.cookie adds or replaces exactly one cookie and leaves the other three untouched — it is not a normal property assignment. Only the name=value part is ever readable afterwards; path and max-age are write-only.

open as a page

A logout handler runs `document.cookie = "session=; max-age=0"`, but the cookie is still sent on the next request. Give every reason a JavaScript cookie deletion can silently fail, and the correct way to delete one.

level: seniorimportance: should knowfreq 49%

basics

~20 s

There is no delete API — you expire a cookie by rewriting it with the same name, path and domain plus max-age=0. A mismatched path or domain writes a different cookie, and an HttpOnly or Secure cookie cannot be touched from script at all.

open as a page

The `cookieStore` API is offered as a modern replacement for `document.cookie`. What does it change about reading, writing and observing cookies, and what stays exactly the same?

level: seniorimportance: nice to knowfreq 27%

basics

~20 s

cookieStore is a promise-based API returning cookie objects with their attributes, usable in service workers, with a change event instead of polling. The security model is unchanged: HttpOnly cookies stay invisible, and it is secure-context only.

open as a page