I’m new to Cloudflare Workers and can’t seem to get past this problem with KV. When run locally, any attempt to get()
a value for a key returns null.
wrangler kv:key
seems to be telling me the key/values are there:
$ wrangler kv:key get somekey --binding deletemekv --preview false
somevalue
$ wrangler kv:key get somekey --binding deletemekv --preview
somevalue-preview
Running wrangler dev
seems to tell me that the worker has access to the binding:
$ wrangler dev
⛅️ wrangler 3.9.0
------------------
...
Your worker has access to the following bindings:
- KV Namespaces:
- deletemekv: 1eb11b1465f4433d82e8fbbb371184d2
- Vars:
- ENVIRONMENT: "production"
⎔ Starting local server...
And yet with this bit of test code:
export default {
async fetch(request, env) {
try {
var test = await env.deletemekv.get('somekey');
console.log("somekey: " + test);
} catch (error) {
console.error("Error fetching from KV:", error);
}
return handleRequest(request);
}
}
I get
somekey: null
On the other hand if I deploy and look at wrangler tail
I get the expected:
(log) somekey: somevalue
Looking at the KV dashboard for 1eb11b1465f4433d82e8fbbb371184d2
, the somekey
key is there.
Here’s my wrangler.toml file:
name = "sonar-get-token"
main = "src/index.js"
compatibility_date = "2023-09-18"
kv_namespaces = [
{ binding = "deletemekv", id = "43254afb2b444325aa57cd65e2249991", preview_id = "1eb11b1465f4433d82e8fbbb371184d2" }
]
[vars]
ENVIRONMENT = "production"
[env.test]
vars = { DEBUG = "1", ENVIRONMENT = "test" }
kv_namespaces = [
{ binding = "deletemekv", id = "43254afb2b444325aa57cd65e2249991", preview_id = "1eb11b1465f4433d82e8fbbb371184d2" }
]
Any hints on what I’m missing here? TY