Support for KV Binding
The #54 PR seems to add support for local KV testing and KV items uploading, while I didn't find a way setting KV bindings (like in wrangler.toml) using @cfworker/dev. It would be great to have such a feature.
Also, lots of thanks for maintaining these great packages. Packages like dev and web just work like a charm.
hey @equt - there's a --kv flag you can use to bind a json file to a kv namespace. Apologies, there's no docs for this yet. Here's how it works:
Assuming you have the following files:
/abc/xyz/GREETINGS.json
[
{ "key": "hello", "value": "world", "base64": false }
]
/worker.js
addEventListener('fetch', async e => {
const body = await GREETINGS.get('hello', 'text');
e.respondWith(new Response(body));
});
Then the following command should work:
cfworker run worker.js --kv abc/xyz/GREETINGS.json
More info:
-
cfworker uses the basename of the json file as the KV namespace.
-
You can use the
--kvparameter multiple times if you need to bind multiple namespaces:cfworker run worker.js --kv namspace1.json --kv namespace2.json -
Changes to the namespace by the worker script via the put and delete methods are not persisted to the file.
-
The
--watchparameter will also cause the --kv files to be watched. *soon- there's a bug: #137 -
The
base64property isn't required in the JSON, it's included in case you need to seed the namespace with some binary data. -
The runtime implementation your worker will be interacting with is here, most features are implemented, including expiration however the
listmethod is not. Could be added.
That was brilliant, and I find it way better than creating a preview_id. Also, the missing list method doesn't bother me since I barely use it.
But there seems to have no way of binding KV namespaces environment in production for now (like what wrangler does). I've done some quick research on Cloudflare API, maybe it's because wrangler used some private APIs?
But there seems to have no way of binding KV namespaces environment in production for now (like what wrangler does). I've done some quick research on Cloudflare API, maybe it's because wrangler used some private APIs?
@equt is this to say while debugging locally with cfworker run you'd like to connect to production KV? Could probably build an alternate implementation of MemoryKVNamespace which uses the kv rest api.
https://github.com/cfworker/cfworker/blob/main/packages/dev/src/cloudflare-api.js#L468
Sorry for the unclear, it's to say that wrangler supports binding, so every time after deployment, I could see the namespaces automatically available to that specific worker in the Cloudflare dashboard like following.

However, using the dev package's deployment command will lose the bindings, and break the worker. This is a pretty fundamental functionality, perhaps I just missed something in the documentation.