How to use multiple KV in a worker?

I even can’t make a single KV work.

Here’s what I did:

  1. Create a KV in cloudflare, let’s say it’s call xxx;
  2. Run this command: wrangler kv:key put --binding=xxx “yyy” “zzz”, successed.
  3. Add it in wrangler.towl:
    kv_namespaces = [
    { binding = “xxxt”, id = “*************************************” }
  4. Use it in worker.ts file:
    const x=xxx.get(yyy);
    it says: Cannot find name ‘xxx’.ts(2304)

Just notice there’s a typo here:
kv_namespaces = [
{ binding = “xxxt”, id = “*******************************************” }
it’s just in this topic, not in towl, so, I still need help on this.

Are you using module syntax (export default { fetch() } rather than addEventListener)? If so, you access the bindings from the env property like so:

export default {
  fetch(req, env) {
    await env.KV.get();

If not, please share your code and actual wrangler.toml (nothing in there is sensitive) so we can help debug.

1 Like

Yeah, you are right, problem solved.
Sorry, I’m not familiar with these things, but as I see, now that module syntax was used by default, cloudflare’s document should at least mention how to use it in this way, right?
Thank you so much for the help, @Walshy

Hi, @Walshy ,

‘await env.KV.get();’ solved my coding issue, but stucked on running.
Below is the whole list of error:

.internal-6d5dc2e3-0…d8e3-facade-1.js:14 TypeError: Cannot read properties of undefined (reading ‘get’)
at Object.fetch (worker.js:19:18)
at facade_modules_fetch (.internal-6d5dc2e3-0…8e3-loader.js:23:17)
at facade_invokeChain (.internal-6d5dc2e3-0…8e3-common.js:16:10)
at (.internal-6d5dc2e3-0…8e3-common.js:13:14)
at jsonError (.internal-6d5dc2e3-0…3-facade-1.js:12:32)
at facade_invokeChain (.internal-6d5dc2e3-0…8e3-common.js:16:10)
at (.internal-6d5dc2e3-0…8e3-common.js:13:14)
at scheduled (.internal-6d5dc2e3-0…e3-facade-0.js:9:24)
at facade_invokeChain (.internal-6d5dc2e3-0…8e3-common.js:16:10)
at facade_invoke (.internal-6d5dc2e3-0…8e3-common.js:19:10)

I’m sure I added the 2 KVs in wrangler.toml…

You may think I don’t have to use env.KV.get().
But I have to, because I also need to use R2 in same worker.

What’s the binding name you set in the wrangler.toml? You will need to use that in place of KV

e.g. if your wrangler.toml was

kv_namespaces = [
  { binding = "KV", id = "..." }

Then env.KV would work since you’re setting the binding to live on KV

But if it was like:

kv_namespaces = [
  { binding = "FILES", id = "..." }

Then you’d want to be accessing through env.FILES


Got it, I fixed it as you told.

Sorry I misunderstood the KV…

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.