2 min read

Cookie Store API

The Cookie Store API provides an asynchronous, Promise-based API for managing cookies. It is a modern replacement for the synchronous and clunky document.cookie interface.

1. Why use it?

The traditional document.cookie API has several issues:

  • Synchronous: Accessing cookies blocks the main thread.
  • String Parsing: You have to manually parse a long string of key-value pairs.
  • No Service Worker Support: document.cookie is not available in Service Workers.

The Cookie Store API solves these problems by being asynchronous and providing a structured way to access cookies.

2. Getting Cookies

You can retrieve a single cookie or all cookies.

cookieStore.get(name)

Returns a Promise that resolves to the first cookie with the given name.

try {
  const cookie = await cookieStore.get('session_id');
  if (cookie) {
    console.log(`Found session: ${cookie.value}`);
  }
} catch (e) {
  console.error('Cookie retrieval failed:', e);
}

cookieStore.getAll()

Returns a Promise that resolves to a list of all cookies (or those matching a specific name/options).

const cookies = await cookieStore.getAll();
cookies.forEach(cookie => {
  console.log(`${cookie.name}: ${cookie.value}`);
});

3. Setting Cookies

To set a cookie, use cookieStore.set(). It takes either a name and value, or an options object.

// Simple
await cookieStore.set('theme', 'dark');

// With options
await cookieStore.set({
  name: 'user_preference',
  value: 'settings_v1',
  domain: 'example.com',
  path: '/',
  expires: Date.now() + 86400000 // 1 day
});
console.log('Cookie set!');

4. Deleting Cookies

To delete a cookie, use cookieStore.delete(name).

await cookieStore.delete('session_id');
console.log('Session cookie deleted');

5. Listening for Changes

You can listen for the change event to detect when cookies are added, changed, or removed.

cookieStore.addEventListener('change', (event) => {
  for (const cookie of event.changed) {
    console.log(`Cookie changed: ${cookie.name} = ${cookie.value}`);
  }

  for (const cookie of event.deleted) {
    console.log(`Cookie deleted: ${cookie.name}`);
  }
});

6. Service Workers

One of the biggest advantages is that cookieStore is available inside Service Workers, allowing you to manage session state directly from the worker.

programming/javascript/vanilla/javascript programming/javascript/vanilla/web-storage programming/javascript/vanilla/service-workers-and-pwa programming/javascript/vanilla/promises-async-await