Cookie Store API


The Cookie Store API is a modern asynchronous alternative to document.cookie.

Browser support

The Cookie Store API has been available in Chrome and Edge since version 87, released back in 2020. The API is also available in Safari Technology Preview and Firefox Nightly. Firefox and Safari decided to implement only a subset of the API, which is what I will cover in this article. A polyfill is available.

await cookieStore.set("cookie_test", "123");

To specify more than a name and value, you can pass in an object of options:

await cookieStore.set({
    name: "cookie_test", 
    value: "123",
    domain: "example.com",
    expires: new Date('Wed, 1 Jan 2025 00:00:00 GMT')
});
const cookie = await cookieStore.get("cookie_test");
console.log(cookie);

The get() method returns a promise that resolves with an object that contains a name and value property:

{
name: "cookie_test",
value: "123"
}

In Chrome/Edge/Samsung Internet, some additional properties are included in the cookie object but these are unlikely to be exposed by other browsers.

Get multiple cookies

getAll() returns a promise that resolves with an array of cookie objects.

const cookies = await cookieStore.getAll()
await cookieStore.delete("cookie_test");

The change event is fired every time a cookie is set or deleted.

cookieStore.addEventListener("change", function (event) {
  for (const cookie of event.deleted) {
    console.log(`cookie ${cookie.name} was deleted`);
  }

  for (const cookie of event.changed) {
    console.log(`cookie ${cookie.name} was set`);
  }
});

This event has a deleted property, which is an array containing all cookies that were removed, either because they were explicitly deleted or because they expired, and a changed property, which is an array containing any newly created cookies.

Differences between Chrome/Edge/Samsung Internet and other browsers

MDN currently covers further aspects of the API not mentioned in this article, including features that are only implemented in Chrome/Edge/Samsung Internet and that have not achieved cross-browser consensus. It is likely that the scope of the spec will be reduced inline with the opinions of Safari and Firefox. Safari and Firefox only expose the name and value of cookies returned from get() or getAll(), whereas Chromium-based browsers include additional metadata. Firefox have stated that “At this time we’re not ready to expose ServiceWorkerRegistration.cookies or implement the CookieStoreManager as proposed”.