cookieStore: Async Cookie API

By  on  

One pattern in the JavaScript API world that web development veterans will notice is that we've been creating new methods to accomplish what older, grosser APIs once achieved. XMLHttpRequest became the fetch API, some APIs like Battery became async, and there are dozens of other examples. Another API desperately in need of updating is the cookie API...and we've finally got it: cookieStore.

The new cookie API, cookieStore, is asynchronous and provides a logical method for cookie management. You have to remember that the previous method of getting and setting cookies completely revolved around concatenating and parsing document.cookie as a string. Don't believe me? Check out this monstrosity!

document.cookie =
  '__Secure-COOKIENAME=cookie-value' +
  '; Path=/' +
  '; expires=Fri, 12 Aug 2016 23:05:17 GMT' +
  '; Secure' +
  '; Domain=example.org';
// now we could assume the write succeeded, but since
// failure is silent it is difficult to tell, so we
// read to see whether the write succeeded
var successRegExp =
  /(^|; ?)__Secure-COOKIENAME=cookie-value(;|$)/;
if (String(document.cookie).match(successRegExp)) {
  console.log('It worked!');
} else {
  console.error('It did not work, and we do not know why');
}

Let's focus on using this new API, cookieStore, to bring sanity to cookies!

If you really want to see how cookies are presented to you now, go to your favorite website and type document.cookie . The horror!

Set a Cookie

cookieStore.set allows you to set a cookie with name, value, and other specifics:

// All cookieStore methods are async, so you can `await` or `then`/`catch`
await cookieStore.set({ 
  name: "dw-test", 
  value: 1, 
  domain: 'davidwalsh.name', 
  // Very far in the future!
  expires: Date.now() + Date.now() 
});

// Quick, naive set
await cookieStore.set('key', 'value');

This is so much better than concatenating an odd string onto and already odd document.cookie!

Get a Cookie

cookieStore.get provides a method for getting the value of a specific cookie:

const testCookie = await cookieStore.get('dw-test');

{
  domain: "davidwalsh.name",
  expires: 3206289322149,
  name: "dw-test",
  path: "/",
  sameSite: "strict",
  secure: true,
  value: "1",
}

If the cookie exists and hasn't expired, the value and much more about the cookie will be returned. Yes -- a simple get method instead of parsing a string! Tears in my eyes!

Delete a Cookie

We can use cookieStore.delete to remove a cookie:

await cookieStore.delete('dw-test');

Just as simple as you'd expect!

Cookie Change Event

If you'd like to know when cookies are being created, deleted, or modified, you can listen for the change event on the cookieStore:

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`);
});

I'm so happy that the old document.cookie is essentially getting replaced with this awesome but simple cookieStore API. Onward and upward with JavaScript APIs! Which legacy API would you like to see improved next?

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    Duplicate the jQuery Homepage Tooltips Using Dojo

    The jQuery homepage has a pretty suave tooltip-like effect as seen below: Here's how to accomplish this same effect using Dojo. The XHTML The above HTML was taken directly from the jQuery homepage -- no changes. The CSS The above CSS has been slightly modified to match the CSS rules already...

  • By
    Google Extension Effect with CSS or jQuery or MooTools JavaScript

    Both of the two great browser vendors, Google and Mozilla, have Extensions pages that utilize simple but classy animation effects to enhance the page. One of the extensions used by Google is a basic margin-top animation to switch between two panes: a graphic pane...

Discussion

  1. Finally! This looks amazing!

    Is there any info on when this new API is coming to browsers? I could only find the cookies API which seems to only be for browser extensions: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies

  2. Oscar

    Thanks for this David. Do you know something about this new API in regards of security? Like being a valid alternative over HTTPOnly

  3. I recently made a best-attempt at a quick shim for this, but it’s not capable of the same things. The getter doesn’t have access to things like path or expires, and I cannot easily dispatch events when cookies are changed via HTTP.

    I’ll be glad when cookieStore is finalized and has good support. I’m wondering how much it’ll change, since there is some opposition regarding privacy.

  4. Hi, David. There are no any cookie store API in MS Edge for now. Is it only Fire Fox solution in present days?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!