KV Storage

Avatar of Chris Coyier
Chris Coyier on

localStorage is…

  • Good! It’s an incredibly easy API to use.
  • localStorage.setItem('name', 'Chris'); let name = localStorage.getItem('name');
  • Bad! Philip Walton explains why:

localStorage is a synchronous API that blocks the main thread, and any time you access it you potentially prevent your page from being interactive.

Chrome has an idea (here’s the proposal) for reinventing it. Ultimately the API is even simpler:

import { storage } from 'std:kv-storage';
storage.set('name', 'Chris');

But! It’s async, so I can use await before I do those things without blocking anything. This demo will work in Chrome Canary right now:

See the Pen
by Chris Coyier (@chriscoyier)
on CodePen.

What in all heck is up with this line?

import { storage } from 'std:kv-storage';

They are calling it a “built-in module.” In other words, something you can import but it makes no network request because it’s built into the browser. Pretty interesting approach.

Philip continues:

Not exposing built-in modules globally has a lot of advantages: they won’t add any overhead to starting up a new JavaScript runtime context (e.g. a new tab, worker, or service worker), and they won’t consume any memory or CPU unless they’re actually imported. Furthermore, they don’t run the risk of naming collisions with other variables defined in your code.

This is built on top of indexedDB, so if you’re playing with it and need to clear the values or whatever, you do it there (DevTools > Application > Storage > IndexedDB). It’ll be fascinating to see if this catches on and whether new JavaScript features are shipped as built-in modules. I have no sense of whether other browsers think this is a good idea or not.

Direct Link →