Properly configuring D1 for local development

I have a very basic SvelteKit project that is deployed using Cloudflare Pages. I have configured a D1 database, set up the appropriate bindings and can successfully connect to that database in production. However, I am unable to figure out the correct way to configure D1/Wrangler to support local development.

In Production, I can access my D1 instance through the platform.env.<BINDING>. property:

// +page.server.ts
export async function load({ platform }) {
  const { results } = await platform.env.MY_DB.prepare(...).all(...)
}

The SvelteKit docs state that platform.env is only available in production builds and that we should use Wrangler to “test it locally”:

  • https://kit.svelte.dev/docs/adapter-cloudflare#environment-variables

But it’s not entirely clear how to follow the Wrangler documentation to wire this all up. What should go in the wrangler.toml file? How should wrangler dev be called?

Can anyone provide some guidance on how to make local D1 development work from within a SvelteKit application, as opposed to just from within a normal Cloudflare Worker?

Thanks in advance.

2 Likes

I’d like to know answer too.

I created an API endpoint, secured with a header token, which enables my local dev to call production api on Cloudflare to use D1.

I’ve found a myriad of instructions involving vite proxies, miniflare, etc. but have not been to get any of it to work and as far as I can tell maybe there is not a viable solution for testing this locally with a sveltkit app/vite preview.

I was able to make this work today locally, see https://github.com/cloudflare/workers-sdk/issues/3622#issuecomment-1773909149