Cookie Store API: Modern Cookies Without String Parsing


The Cookie Store API gives web apps an asynchronous, promise-based replacement for most document.cookie work—and, crucially, makes selected cookie changes observable from a service worker. Now that it is Baseline Newly available, teams can start designing a progressive migration: keep the server’s Set-Cookie contract, move browser-readable state behind a small adapter, and use change events only where they genuinely improve offline or multi-tab behaviour. This is an API modernization, not a reason to put secrets in JavaScript-readable cookies.

TL;DR

document.cookie is synchronous, string-based and unavailable to service workers. The Cookie Store API replaces its parsing and concatenation with await cookieStore.get(), set() and delete(), and supports cookie-change subscriptions in service workers. Use feature detection and an adapter because support on older browsers still matters. Keep authentication session cookies HttpOnly; client JavaScript cannot—and should not—read them with either API.

Table of contents

What problem does the Cookie Store API solve?

The original browser cookie interface is a property containing one semicolon-delimited string. Reading a single value means reading and parsing the whole visible cookie string; writing one means constructing a correctly formatted attribute string and hoping the browser accepts it. The Cookie Store API standard calls out the awkwardness of that synchronous, single-threaded model. MDN now marks the API as Baseline Newly available since June 2025, which makes it a practical progressive enhancement rather than a curiosity.

The improvement is more than syntax. Cookie access is asynchronous, operations return promises, and a window or service worker gets structured records rather than strings to split. That matters most in applications that already treat browser state as an asynchronous boundary: PWAs, complex dashboards, checkout flows, and shared-device experiences.

It also closes an architectural gap. A service worker has no document, so it could never use document.cookie. The Cookie Store API is available in service workers and can notify them about subscribed, script-visible cookie changes. That opens a narrow, useful path to respond to a preference or account-context change without polling.

This does not make cookies a general client database. Cookie size limits, request overhead, privacy restrictions and server semantics are still real. If the state is local-only, the Storage Buckets API or IndexedDB is usually the better home.

What does the API look like in practice?

For a browser-readable preference, the difference is pleasantly direct. The example below saves a colour scheme while retaining a conventional Path, expiration and secure transport requirement.

js
async function saveTheme(theme) {
  await cookieStore.set({
    name: 'theme',
    value: theme,
    path: '/',
    expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
    sameSite: 'lax',
    secure: true,
  });
}

async function readTheme() {
  return (await cookieStore.get('theme'))?.value ?? 'system';
}

get() returns a cookie record or null; getAll() can filter by name, URL or matching attributes. The exact matching rules and cookie attributes come from the Cookie Store specification and HTTP’s evolving cookie specification. Treat those attributes as part of application policy, not incidental boilerplate.

In a React or Next.js client component, avoid firing reads during render. Read asynchronously in an effect or in the event that needs the value, then update UI state. That keeps client-only persistence separate from server rendering—the same boundary that makes cache components easier to reason about. It also makes hydration deterministic: render an explicit default first, then reconcile an optional client preference after the component has mounted.

js
export async function getPreference(name) {
  if ('cookieStore' in window) {
    return (await window.cookieStore.get(name))?.value;
  }

  const prefix = `${encodeURIComponent(name)}=`;
  return document.cookie
    .split('; ')
    .find((part) => part.startsWith(prefix))
    ?.slice(prefix.length);
}

The fallback is intentionally small. Centralizing it prevents a half-migration where several components still hand-roll slightly different cookie parsers.

How do service worker cookie changes work?

A service worker can subscribe to changes for a specific cookie and receive a cookiechange event when a matching script-visible cookie changes. Registration is explicit, which keeps it from becoming a noisy “watch every cookie” channel.

js
// After navigator.serviceWorker.ready in the page
const registration = await navigator.serviceWorker.ready;
await registration.cookies.subscribe([{ name: 'activeWorkspace' }]);

// sw.js
self.addEventListener('cookiechange', (event) => {
  for (const changed of event.changed) {
    if (changed.name === 'activeWorkspace') {
      // Invalidate workspace-specific cached data or notify open clients.
    }
  }
});

This is a good fit for cache partitioning: a user switches an explicitly client-readable workspace cookie, and the service worker can clear or revalidate cached workspace data before the next navigation. It is not a substitute for validating authorization on the server. A server may change cookies outside the scenarios an application expects, and browser privacy features can affect cookie availability.

The API’s service-worker relationship is defined in the Cookie Store API standard; build the worker lifecycle around the Service Workers specification, including versioning and cache cleanup. If invalidation is expensive, send a message to clients and let the next user action trigger the refresh rather than performing broad work in every event.

Which cookies should an application manage?

The dividing line is security, not convenience.

  • Good candidates: a non-sensitive theme, locale, consent state, a UI experiment bucket, or a client-readable workspace label.
  • Server-owned candidates: HttpOnly session identifiers, refresh tokens, privilege assertions and anything that authorizes a request.
  • Usually better elsewhere: large preferences, drafts, cached API data and offline queues. Cookies are sent with requests; local persistence is not.

Neither document.cookie nor cookieStore can read an HttpOnly cookie. Preserve that boundary. The usual secure session pattern remains: the server sets an HttpOnly, Secure, appropriately scoped cookie; the browser includes it automatically; the server verifies it. A UI can keep harmless display state separately. Modern identity work such as passkeys reduces password exposure, but it does not remove the need for careful session handling.

Also review SameSite, Secure, Path, Domain, expiry and, where relevant, partitioning. The Cookie Store API makes these choices easier to express; it cannot choose correct cross-site policy for you.

How can a team migrate safely?

Start with one low-risk cookie, not authentication. A compact rollout plan looks like this:

  1. Inventory all client writes to document.cookie and label each cookie: authentication, server-controlled, client preference or legacy integration.
  2. Select one browser-readable preference and create a getCookie, setCookie, deleteCookie adapter backed by Cookie Store with a tested legacy fallback.
  3. Preserve the existing name, path, expiry and SameSite policy so the server contract does not accidentally change.
  4. Add telemetry for failed writes or unexpected missing values—without logging cookie values.
  5. Only then evaluate a service-worker subscription for a concrete invalidation problem.

Test in the browsers and embedded webviews your customers use. “Baseline Newly available” means the feature is broadly available in current engines, not that every managed device is current. Feature detection is clearer than user-agent detection:

js
const supportsCookieStore =
  typeof window !== 'undefined' && 'cookieStore' in window;

On the server, test the same request flows before and after the migration. Cookie APIs are deceptively small changes with outsized effects when a path or SameSite default shifts. Include subdomains, deep links, sign-out, expired cookies and the first request after a preference update—not just the happy path in one browser tab.

Where does this fit in a modern web architecture?

The Cookie Store API is part of a larger move from synchronous document-era primitives to explicit, asynchronous platform APIs. The same direction appears in the Navigation API, scheduler.postTask() and local-first storage. The practical benefit is not novelty; it is clearer boundaries.

Use cookies for compact, request-relevant state. Use a service worker for controlled offline and cache behaviour. Use server-side validation for authority. Use IndexedDB or OPFS for client data that should not ride on every request. Once those responsibilities are separated, a Cookie Store adapter becomes a modest upgrade with a clean rollback path.

For teams maintaining long-lived applications, that is the real payoff: replacing brittle string manipulation with a standard API while leaving security-critical server ownership exactly where it belongs.

FAQ

Can Cookie Store API replace every use of document.cookie?

No. It can progressively replace browser-side reads and writes where supported, but a fallback remains sensible for older clients. It also cannot read HttpOnly cookies and should not replace server-side session validation.

Does Cookie Store API make authentication safer?

Not by itself. Its key benefits are asynchronous structured access and service-worker integration. Keep session tokens in HttpOnly, Secure cookies and enforce authorization on the server.

Should a service worker subscribe to every cookie change?

No. Subscribe only to named, script-visible cookies where a change has a defined cache or UI consequence. Broad subscriptions make invalidation harder to reason about.

Is Cookie Store API ready for production?

It is Baseline Newly available, but production readiness depends on your supported browser and webview estate. Use feature detection, retain a fallback, and test the exact cookie attributes your app relies on.

Frequently Asked Questions

Can Cookie Store API replace every use of document.cookie?

No. Use it progressively with a fallback, and keep HttpOnly session cookies server-owned.

Does Cookie Store API make authentication safer?

No. It improves client-side ergonomics; secure session design still requires HttpOnly, Secure cookies and server validation.

Is Cookie Store API ready for production?

It is Baseline Newly available, but use feature detection and verify your supported browsers and webviews.