KV.list with prefix - includes mismatches when paginating

Within a JS worker, when calling KV.list({prefix: "foo") that contains more than 1000 results, the result set must be de-paginated. Consider the example code that demonstrates this:

  async getKeys(kv, prefix) {
    let matches = await kv.list({prefix});
    const results = [...matches.keys];
    while (!matches.list_complete) { // Depaginate the whole KV.
      matches = await kv.list({cursor: matches.cursor});
      results.push(...matches.keys);
    }
    return results;
  },

It’s not currently documented in the pagination docs that the prefix must be passed in for all successive calls.

The correct code would look like this:

  async getKeys(kv, prefix) {
    let matches = await kv.list({prefix});
    const results = [...matches.keys];
    while (!matches.list_complete) { // Depaginate the whole KV.
      matches = await kv.list({prefix, cursor: matches.cursor});
      results.push(...matches.keys);
    }
    return results;
  },

Posting for posterity!

2 Likes

Good catch! I would recommend opening an issue on the Cloudflare docs so this can be tracked and fixed: GitHub - cloudflare/cloudflare-docs: Cloudflare’s documentation

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