How to send a GET request to my KV namespace to get all the values?

See the code below. The first problem I have is value is not displayed on the screen when I run wrangler dev. I tried json.stringify and it didn’t work. How can I see the value corresponding to key1?

Another problem is, is there a way to render all values in a KV namespace at once, rather than accessing each key individually? Thank you so much!

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let value = await hireKV.get('key1');
  return new Response(value);
}

Do you have a value in your KV namespace? I’d try to console.log it and see what you’re getting. It would also be helpful to know what you’re seeing

You can’t read in bulk but maybe you could put everything into a array and save that? Otherwise, list + get will probably be your friends.

  1. Thank you! I solved the first problem:)
  2. If I understood you correctly, you’re saying we can first use NAMESPACE.list() to get the keys, and then use a loop and NAMESPACE.get(key) to get all the values right? As a result of running the following code,
async function handleRequest(request) {
  let list = await NAMESPACE.list(); 
  console.log(JSON.stringify(list["keys"]));

console.log prints out

[
  {
    "name": "key1"
  },
  {
    "name": "key2"
  }
]

which I know is in string format, so how can I access each “key1” and “key2” from this string and get their corresponding values?

Correct!

Code like this:

const list = await KV.list();
for (const key of list.keys) {
  const value = await KV.get(key.name);
  // use the value as you wish
}

You may also be interested in the available options for the list operation - https://developers.cloudflare.com/workers/runtime-apis/kv#listing-keys

1 Like

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