I was trying to connect my Netlify Edge Function to _any_ KV store and was having trouble finding on

I was trying to connect my Netlify Edge Function to any KV store and was having trouble finding one that would work (I've even written my own KV JS library in the past); so ended up creating a thin wrapper around Cloudflare's REST API that worked great!

const baseUrl = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT}/storage/kv/namespaces/${CLOUDFLARE_NAMESPACE}`;
const headers = { ... };  // Auth stuff

class CloudflareRest {
  EXPIRES = true;

  async get(key) {
    const res = await fetch(`${baseUrl}/values/${key}`, { headers });
    if (res.status === 404) return null; // It does not exist
    const data = await (res.headers.get("content-type").includes("json")
      ? res.json()
      : res.text());
    if (typeof data !== "string") return null;
    return JSON.parse(data);
  }

  async set(key, body, { expires }) {
    const expiration = expires ? `expiration_ttl=${expires}&` : "";
    await fetch(`${baseUrl}/values/${key}?${expiration}`, {
      method: "PUT",
      headers,
      body: JSON.stringify(body),
    });
    return key;
  }

  async keys(prefix) {
    const res = await fetch(`${baseUrl}/keys`, { headers });
    const data = await res.json();
    return data.result
      .map((it) => it.name)
      .filter((key) => key.startsWith(prefix));
  }

  async *iterate(prefix) {
    // ...
  }
}

const store = kv(CloudflareRest);
// console.log(await store.get("hello"));
// console.log(await store.set("hello", { world: "spins" }));
// console.log(await store.get("hello"));
Was this page helpful?