Cookie Store API: Async Cookie Management in JS

This article provides an overview of the modern Cookie Store API in JavaScript, detailing how it modernizes client-side cookie management. It explains how this Promise-based interface replaces the legacy, synchronous document.cookie model with an asynchronous, non-blocking approach that functions seamlessly across both the main window and Service Worker environments.

Historically, managing cookies in JavaScript required using document.cookie. This legacy approach has significant drawbacks:

The Cookie Store API is a modern web standard that provides an asynchronous, Promise-based alternative for interacting with browser cookies via the global cookieStore object. Because it returns Promises, it allows developers to manage cookies using standard async/await syntax without blocking UI rendering.

Core Methods and Usage

The API provides clear, structured methods for reading, writing, and deleting cookies.

Instead of formatting a raw string, cookieStore.set() accepts an object containing standard cookie attributes:

await cookieStore.set({
  name: 'session_token',
  value: 'xyz123abc',
  expires: Date.now() + 24 * 60 * 60 * 1000,
  path: '/',
  sameSite: 'lax'
});

To retrieve a cookie, call cookieStore.get(), which returns a Promise resolving to a structured cookie object or null if the cookie is not found:

const sessionCookie = await cookieStore.get('session_token');
if (sessionCookie) {
  console.log(sessionCookie.value);
}

To fetch multiple cookies at once, use cookieStore.getAll(), which can also filter by name or URL.

Deleting a cookie simply requires passing the cookie name (and matching attributes if specified during creation):

await cookieStore.delete('session_token');
cookieStore.addEventListener('change', (event) => {
  for (const cookie of event.changed) {
    console.log(`Cookie modified: ${cookie.name}`);
  }
  for (const cookie of event.deleted) {
    console.log(`Cookie removed: ${cookie.name}`);
  }
});

The Cookie Store API provides a cleaner, faster, and more robust foundation for modern client-side cookie operations.