Cloudflare Workers – using KV in ‘dev’ or ‘preview’

Overview

When developing Cloudflare Workers which make use of Cloudflare KV there’s an error message you might get which reads like this :

Error: In order to preview a worker with KV namespaces, you must designate a preview_id in your configuration file for each KV namespace you'd like to preview.

What’s going on ?

There’s a couple of things it’s useful to know when resolving this, and as far as I can see it’s not clearly documented in the Cloudflare Workers, or KV documentation.

If you’re seeing this you need to go and inspect your wrangler.toml file. You probably have something that looks like this :

kv_namespaces = [
{ binding = "FOO", id = "bb12cc34dd56eebb12cc34dd56eebb12" }
]

Or you may have no kv_name_spaces entry at all. Either way this is how to resolve the situation.

How to fix this

Execute the following command.

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

If you do have an existing entry for kv_namespaces be sure to use the binding property value that’s already in use, in this example ‘FOO’, otherwise use whatever name you want as your namespace name.

Once you’ve executed that command you should see output which looks like the following :

Add the following to your configuration file in your kv_namespaces array:{ binding = "FOO", preview_id = "d94ab232f1ef23acdeaeef0add746a48", id = "bb12cc34dd56eebb12cc34dd56eebb12" }

Go ahead and place that in the wrangler.toml and you should find the …

Error: In order to preview a worker with KV namespaces, you must designate a preview_id in your configuration file for each KV namespace you'd like to preview.

… message doesn’t appear any longer when using wrangler dev or wrangler preview.

Leave a Reply

Your email address will not be published. Required fields are marked *