Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Created March 6, 2023 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/e5128b8ae10dcd069771248ba1368367 to your computer and use it in GitHub Desktop.
Save rstacruz/e5128b8ae10dcd069771248ba1368367 to your computer and use it in GitHub Desktop.
Using miniflare for Cloudflare Worker KV in Astro
import { getRuntime } from "@astrojs/cloudflare/runtime";
import type { KVNamespace } from "@cloudflare/workers-types";
/** The KV key (eg, env["KV"]) */
const KV_KEY = "KV" as const;
/**
* Returns a Cloudflare Worker KV store.
* In dev, it returns a mock one based on Miniflare.
*/
export async function getKV(request: Request): Promise<KVNamespace> {
if (import.meta.env.DEV) return getMockKV();
const kv = getRuntimeKV(request);
if (kv) return kv;
throw "No KV provider available";
}
type Env = {
[key in typeof KV_KEY]: KVNamespace;
}
export async function getRuntimeKV(request: Request): Promise<KVNamespace> {
const runtime = getRuntime<Env>(request);
// runtime: { env: { KV: KVNamespace {}, ASSETS: Fetcher {} }, name: 'cloudflare' }
const kv = runtime?.env[KV_KEY];
return kv;
}
export async function getMockKV(): Promise<KVNamespace> {
(global as any).miniflare ??= await (async () => {
const { Miniflare } = await import("miniflare");
return new Miniflare({
kvNamespaces: [KV_KEY],
script: '',
});
})();
return (global as any).miniflare.getKVNamespace(KV_KEY);
}
// Example: using miniflare for Cloudflare Worker KV in Astro
//
// Running astro in development mode (`astro dev`) won't allow you to
// use Cloudflare features like KV. To get around this, we can use
// `miniflare`.
import { getKV } from "./get_kv";
// instead of using `getRuntime(request).env.KV` to get the KV instance,
// use this:
const kv = getKV();
kv.put("hello", "world");
kv.delete("hello");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment