Prompt and Applicable Context
An offline-first site must notice login-cookie changes in a Service Worker and update its cache policy. Design a Cookie Store API approach covering subscription scope, event semantics, races, and fallback for unsupported browsers.
The Cookie Store API provides asynchronous cookie reads and writes and lets Service Workers subscribe to matching cookie changes. It is an alternative to blocking document.cookie, but it does not change same-origin, path, Secure, HttpOnly, or SameSite constraints.
What the Interviewer Evaluates
Cover the difference between the page API and the Service Worker subscription API, the fact that cookiechange concerns script-visible changes, name and URL filtering, duplicate subscriptions, event races, and why cookies are not a reliable cross-context database.
Clarifying Questions
Confirm whether the cookie is HttpOnly, whether its scope crosses paths, whether the page and Service Worker are same-origin, and which browsers must work. Ask whether login, logout, and refresh can race, whether cache changes must be immediate, and how long stale session state is acceptable offline.
30-Second Answer Framework
“I would subscribe in the Service Worker to the required cookie names and URLs, then reread only the relevant cookies after cookiechange and advance an idempotent session state machine or monotonic cache version. Cookie Store is asynchronous, events cover script-visible changes only, and they do not provide a transaction or global order, so the handler must deduplicate and reread current state. Unsupported browsers retain server-side cookie checks and explicit page synchronization; stale cache is never proof of authentication.”
Step-by-Step Deep Dive
Step 1: Define the API boundary
Pages can asynchronously read and write through window.cookieStore; a Service Worker manages subscriptions through registration.cookies and receives cookiechange. Both remain subject to cookie policy and cannot read an HttpOnly value.
Step 2: Create the smallest subscription
Subscribe only to the required cookie names and restrict the URL when needed. Cookies with the same name on different paths can coexist, so the handler must use event information and the current URL to identify the target instead of guessing from the name alone.
self.addEventListener("activate", (event) => {
event.waitUntil(
self.registration.cookies.subscribe([
{ name: "session", url: self.registration.scope },
]),
);
});Step 3: Treat events as notifications, not snapshots
The event describes cookie changes, but another change may happen before asynchronous handling runs. Reread current state with get() or getAll(), and make processing idempotent. Do not treat the event object as a transaction log or final truth.
Step 4: Separate script-visible and HttpOnly changes
The specification only requires notifications for script-visible cookie changes. A server can set or delete an HttpOnly cookie without exposing its value to the Service Worker. Authentication conclusions still come from server responses, not from a missing event.
Step 5: Model the session explicitly
Use states such as unknown, verified, logged out, and expired, and advance them from response versions, expiry times, or revalidation results. A cookie change triggers a check; it does not itself prove login or logout.
Step 6: Handle races across tabs
Several pages can refresh or delete a cookie simultaneously. Coalesce short bursts, apply one cache update from the latest read, and use a session version so an old event cannot overwrite newer state. Cache deletion and precaching should also be idempotent.
Step 7: Design an unsupported-browser fallback
When Cookie Store is unavailable, perform explicit synchronization after important navigation or network responses while the server remains authoritative. Do not poll document.cookie for an HttpOnly value or loosen cache authentication because the API is missing.
Step 8: Minimize privacy and security exposure
Subscribe only to business-required names and URLs. Never write cookie values to logs, Cache Storage, or postMessage. Keep Secure, HttpOnly, SameSite, Path, and sensible expiry settings, and clear client caches during logout.
High-Quality Sample Answer
I would use Cookie Store as a change notifier, not an authentication database. During Service Worker activation, create an idempotent subscription for the exact names and scope. On cookiechange, reread the current script-visible state, advance an idempotent session state machine, and update or clear caches using a session version. HttpOnly values remain server-validated, and a missing event never proves that the session is unchanged. Coalesce concurrent refreshes from multiple tabs so an old notification cannot overwrite newer state. For unsupported browsers, keep server validation on critical requests and use explicit page synchronization, never document.cookie polling as a replacement for HttpOnly protection. Scope subscriptions and cache operations, and test logout, expiry, offline use, and Service Worker updates.
Common Mistakes
Treating cookiechange as a complete audit log
It is a notification, not a cross-process transaction sequence. The handler must reread current state and tolerate duplicate work.
Assuming a Service Worker can read HttpOnly cookies
HttpOnly still blocks script reads. A Service Worker can ask the server to validate a session through a request, but Cookie Store does not reveal the secret value.
Letting any cookie change decide cache authentication
Changes can come from refresh, expiry, or another path. Wait for server validation and version state before changing authentication-sensitive caches.
Follow-Up Questions and Responses
How do you avoid deleting the wrong same-name cookie on another path?
Preserve URL scope while subscribing and reading, and delete with the exact name, URL, Path, and other attributes. If the target cannot be identified, let a server response perform cleanup instead of issuing a broad delete.
Can a Service Worker update lose subscriptions?
During the new worker's activate phase, idempotently ensure the subscription exists and reread current cookie state to rebuild caches. Do not rely on the old worker's memory; initialization must run after an update.
What if a cookie expires offline and there is no network?
Mark local state as unverified and limit offline capabilities; offline mode cannot extend a server session. Revalidate first when connectivity returns, then restore, clear, or downgrade the cache.