@werker/cloudflare-kv-storage

An implementation of the std:kv-storage interface wrapping Cloudflare's KV storage

Usage no npm install needed!

<script type="module">
  import werkerCloudflareKvStorage from 'https://cdn.skypack.dev/@werker/cloudflare-kv-storage';
</script>

README

Cloudflare Storage Area

An implementation of the StorageArea (1,2,3) interface using Cloudflare Worker's KV storage as a backing store.

The goal of this class is ease of use and compatibility with other Storage Area implementations, such as kv-storage-polyfill.

While work on the specification itself has stopped, it's still a good interface for asynchronous data access that feels native to JavaScript.

Usage

import { StorageArea, CloudflareStorageArea } from '@werker/cloudflare-kv-storage';

// Pass a `KVNamespace` or the name of a kv namespace bound to this worker:
const storage = new CloudflareStorageArea('MY_FIRST_KV');

You can now write cross-platform, cross-worker-env code:

async function myFunc(sto: StorageArea) {
  await sto.set(['foo', 1], ['bar', 2], { expirationTtl: 5 * 60 });
  await sto.get(['foo', 1]); // => ['bar', 2]
}

Note that some of the underlying features of Cloudflare KV, such as expirationTtl, are still exposed via the optional options parameter[^1]. If the underlying implementation isn't a CloudflareStorageArea, the setting simply won't have an effect.

Disclaimers

Note that efficiency is not a goal. Specifically, if you have sizable ArrayBuffers, it's much better to use Cloudflare's KV directly.


[^1]: I took the liberty of adding the options record to the base interface, since a) standardization has stopped anyway b) if an extra parameters were to be added to the spec, there's a good chance it will be an record as well.