0

List KV Keys

by
Published today

List the keys in a KV namespace, optionally by prefix. Pass the returned result_info.cursor to get the next page.

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
export type DynSelect_namespace_id = string
4

5
// Dropdown of the account's KV namespaces, by title.
6
export async function namespace_id(auth: RT.Cloudflare) {
7
  const response = await fetch(
8
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces?per_page=100`,
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { result } = (await response.json()) as {
20
    result: { id: string; title: string }[]
21
  }
22
  return result.map((n) => ({ value: n.id, label: n.title }))
23
}
24

25
/**
26
 * List KV Keys
27
 * List the keys in a KV namespace, optionally by prefix. Pass the returned result_info.cursor to get the next page.
28
 */
29
export async function main(
30
  auth: RT.Cloudflare,
31
  namespace_id: DynSelect_namespace_id,
32
  prefix: string | undefined,
33
  limit: number | undefined,
34
  cursor: string | undefined
35
) {
36
  const url = new URL(
37
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces/${namespace_id}/keys`
38
  )
39
  for (const [k, v] of Object.entries({ prefix, limit, cursor })) {
40
    if (v != null && v !== "") url.searchParams.append(k, String(v))
41
  }
42

43
  const response = await fetch(url, {
44
    headers: {
45
      Authorization: `Bearer ${auth.token}`,
46
      Accept: "application/json",
47
    },
48
  })
49

50
  if (!response.ok) {
51
    throw new Error(`${response.status} ${await response.text()}`)
52
  }
53

54
  return await response.json()
55
}
56