Cloudflare KV namespace not defined from `wrangler dev`

445 views Asked by At

I've read all the docs and SO posts I can find, but I'm still getting a "sonarkv is not defined" when running my worker locally with wrangler dev. Here what I've done:

  • Created a preview namespace:

$ wrangler kv:namespace create "sonarkv" --preview

  • Added it to wrangler.toml:
kv_namespaces = [
    { binding = "sonarkv", id = "5138eb663ac04eb6af5fe72d11966626", preview_id = "67e98d40e1e74329bf2c30dd92289fce" }
]
  • Verified it:

$ wrangler kv:key list --binding sonarkv --preview

[
  {
    "name": "somekey"
  }
]

$ wrangler kv:key get somekey --binding sonarkv --preview

<...correct value...>
  • And referenced it in my worker script:
    const secret = await sonarkv.get("somekey");
  • Wrangler version:
$ wrangler --version
 ⛅️ wrangler 3.9.0
------------------

What am I missing here? Do I need to bind the preview namespace separately in the dashboard? (When I try it fails with "A variable with that name already exists".)

1

There are 1 answers

0
John Scalo On

Figured it out. Despite this not being documented anywhere that I can find, you now need to pull the namespace binding from the env parameter that's optionally given in fetch(). So:

export default {
    async fetch(request, env) {
    ...
    const secret = await env.sonarkv.get("somekey");
    ...
}