I was recently reading an excellent article about headers that can be used for cache control. One of the headers that was mentioned which I did not know about yet was the clear-site-data header. With it you can tell a browser to clear a specific set of local data. Both the working draft and the MDN article are good resources to learn more about it.

With this new working draft, we can add a header like this to one of our server responses:

Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"

As you can see, you can pick just what the browser should delete. The spec contains detailed information about just what data all of those switches clear. The example above is called the Kill Switch in the spec as it clears just about everything that the browser has stored for the website. This can be very helpful when you have a single page app and you realized that you made a mistake and need to invalidate your caches. Especially when you have installed a fancy service worker that would usually cache data locally very aggressively.

The header is still in draft state but experimental implementations exist for Chrome, Edge, Firefox and Opera. So as long as you are not using IE or Safari, you can try it out already today.

I wanted to try the actual header out so I built a super simple example website here: clear-site-data.k-nut.eu. The source code is on Github. You will see a page that shows a counter. Reloading the page increments the counter by one. The code is super simple:

(function() {
  const cookies = document.cookie;
  let counter = 0;
  if (cookies) {
    const matches = cookies.match(/counter=(\d+)/);
    if (matches && matches.length > 1) {
      counter = parseInt(matches[1], 10);
    }
  }
  document.getElementById('counter').innerText = counter.toString();
  document.cookie = `counter=${counter+1}`
})()

Now, what we want to demonstrate is the clear-site-data header though. There is a simple serverless function registered at /api/send-clear-header which contains the following code:

module.exports = async (req, res) => {
  try {
    res.setHeader('Clear-Site-Data', '"cookies"')
    res.setHeader('Location', "/")
    res.status(302).end();
  } catch (e) {
    console.log(e.message);
  }
};

As you can see, we add the following header: Clear-Site-Data: "cookies" and then redirect back to the main page. This will instruct the browser to delete the cookies so now when you are redirected to the main page, the counter should be at zero again. I encourage you to open your devtools to take a look at the headers in the response.

I think this is pretty cool and am looking forward to trying it in a real life context at some point. Do you see additional use-cases for it? Let me know on twitter.