0

Read KV Value

by
Published today

Read the value stored under a key in a KV namespace (returned as text).

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
 * Read KV Value
27
 * Read the value stored under a key in a KV namespace (returned as text).
28
 */
29
export async function main(
30
  auth: RT.Cloudflare,
31
  namespace_id: DynSelect_namespace_id,
32
  key: string
33
) {
34
  const response = await fetch(
35
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces/${namespace_id}/values/${encodeURIComponent(key)}`,
36
    { headers: { Authorization: `Bearer ${auth.token}` } }
37
  )
38

39
  if (!response.ok) {
40
    throw new Error(`${response.status} ${await response.text()}`)
41
  }
42

43
  return await response.text()
44
}
45