What is the Cookie Store API?

The Cookie Store API provides developers with an asynchronous alternative to Document. Cookie.

  1. Asynchronously access cookies to avoid main thread stalling.
  2. Avoid polling cookies, because cookie changes can be observed.
  3. Expose HTTP cookies to Service Workers (PWA).

How to use

Documents and Service Workers can both access the same API through cookieStore on the global object.

All methods in the Cookie Store API return promises.

The insecure domain name cookieStore is not defined(except localhost). Set and delete methods can be used only in HTTPS environment.

To get a cookie


  1. Await cookiestore. get gets a cookie. The return value is a CookieListItem object.
  2. Await cookiestore. getAll to getAll cookies. Array that returns the value CookieListItem

Await the Promise object after the await command, and the result may be rejected, so it is better to await the await command in the try… In the catch block.

  dictionary CookieListItem {
    USVString name;
    USVString value;
    USVString? domain;
    USVString path;
    DOMTimeStamp? expires;
    boolean secure;
    CookieSameSite sameSite; / / Cookie allows the server to request a Cookie when cross-site request will not be sent none | strict | lax
  }
Copy the code

These two method arguments can take strings or objects. When using objects, the key can only be name or URL (it must be document. url, otherwise an error will be reported).

interface Option { name? : string, url? :document.URL
  }
  
  try {
    const cookie = await cookieStore.get(name:String|options:Option)
  } catch(e) {
    console.error('Failed to get cookie:${e}`)}Copy the code

CookieStore considers key to be an empty object when it does not have one of the two values.

Modify the cookie


Set and delete can be operated only in HTTPS environment; otherwise, errors will be reported.

Await cookiestore.set Sets cookies. Return value is null

  try {
    await cookieStore.set('test'.'1');
  } catch (e) {
    console.error('Failed to write cookie:${e}`);
  }
Copy the code

The above is a shorthand for the following.

  await cookieStore.set({
    name: 'test'.value: '1'.expires: null.// Do not set the time, the default is session cookie.

    // Default is the current domain name.
    domain: self.location.host,
    path: '/'.Secure cookies are created on secure sources by default.
    secure: self.location.protocol === 'https:'.sameSite: 'lax'});Copy the code

Expires sidesteps the date resolution problem by accepting only timestamps (milliseconds since the UNIX era).

Await cookiestore. delete Delete cookie. Return value is null

  try {
    await cookieStore.delete('test');
  } catch (e) {
    console.error('Failed to delete cookie:${e}`);
  }
Copy the code

You can also delete it by setting the expiration time directly before it.

  try {
    await cookieStore.set({
      name: 'test'.value: 1.expires: Date.now() - 2 *  24 * 60 * 60 * 1000})}catch (e) {
    console.error('Failed to delete cookie:${e}`);
  }
Copy the code

Change event


CookieStore includes an API for observing cookie changes, designed to address all use cases that currently need to poll Document.cookie. The API has the following steps:

  1. Watch the cookie change
  2. Handle cookie change events
  cookieStore.addEventListener('change'.(event) = > {
    console.log(`${event.changed.length} changed cookies`);
    for (const cookie in event.changed) {
      console.log(`Cookie ${cookie.name} changed to ${cookie.value}`);
    } 
    console.log(`${event.deleted.length} deleted cookies`);
    for (const cookie in event.deleted) {
      console.log(`Cookie ${cookie.name} deleted`); }});Copy the code

compatibility

It’s just that the Cookie Store API isn’t very compatible, and it’s just that the Chrome OS supports Cookie Store. Chrome was added after Chrome87. It will be some time before they are actually used.

conclusion

The Cookie Store API is much simpler to write and understand than the Document. Cookie method. The disadvantages are obvious, such as compatibility issues, and can only be used in HTTPS environments. I’m still looking forward to using it.

The above content gives us a brief understanding of how to use the Cookie Store API. If there is any inaccurate statement, please correct it.

reference

  1. Cookies are summarized
  2. Cookie Store API
  3. Cookie Store API Explainer