Skip to content

Instantly share code, notes, and snippets.

@thonkinator
Last active October 27, 2023 11:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thonkinator/a4a73bbeb5b09f3c95fa5b769c8bd71c to your computer and use it in GitHub Desktop.
Save thonkinator/a4a73bbeb5b09f3c95fa5b769c8bd71c to your computer and use it in GitHub Desktop.
Miniflare in Sveltekit

Miniflare in SvelteKit!

This requires the package miniflare (NOT any of the @miniflare/-scoped packages), as well as @cloudflare/workers-types if you're using TypeScript. For setting up @sveltejs/adapter-cloudflare, see https://kit.svelte.dev/docs/adapter-cloudflare

// src/hooks.server.ts
import { dev } from "$app/environment";
import type { Miniflare } from "miniflare";

let mf: Miniflare;

export async function handle({ event, resolve }) {
	if (dev) {
		if (!mf) {
			const { Miniflare, Log, LogLevel } = await import("miniflare");
			mf = new Miniflare({
				log: new Log(LogLevel.INFO),
				kvPersist: "./kv-data",
				kvNamespaces: ["KV"],
				d1Persist: "./d1-data",
				d1Databases: ["D1"],
				// you should also be able to add durable objects & r2
				script: "",
				modules: true,
			});
		}
		event.platform = { env: await mf.getBindings() };
	}
	return resolve(event);
}
// app.d.ts
import type { D1Database, KVNamespace } from "@cloudflare/workers-types";

declare global {
	namespace App {
		// interface Error {}
		// interface Locals {}
		// interface PageData {}
		interface Platform {
        		// remember to add these bindings in your cloudflare dashboard!
        		// should be in Workers & Pages > [your site] > Settings > Functions > scroll down to the bindings settings
			env: {
				KV: KVNamespace;
				D1: D1Database;
			};
		}
	}
}
@thonkinator
Copy link
Author

Also check out https://github.com/sdarnell/cf-svelte for a version that reads bindings from wrangler.toml, so you can properly integrate Miniflare with your local wrangler data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment