0

Write KV Pairs

by
Published today

Write one or more key-value pairs to a KV namespace in a single bulk request (up to 10,000 pairs).

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
 * Write KV Pairs
27
 * Write one or more key-value pairs to a KV namespace in a single bulk request (up to 10,000 pairs).
28
 */
29
export async function main(
30
  auth: RT.Cloudflare,
31
  namespace_id: DynSelect_namespace_id,
32
  pairs: { key: string; value: string; expiration_ttl?: number }[]
33
) {
34
  const response = await fetch(
35
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces/${namespace_id}/bulk`,
36
    {
37
      method: "PUT",
38
      headers: {
39
        Authorization: `Bearer ${auth.token}`,
40
        "Content-Type": "application/json",
41
        Accept: "application/json",
42
      },
43
      body: JSON.stringify(pairs),
44
    }
45
  )
46

47
  if (!response.ok) {
48
    throw new Error(`${response.status} ${await response.text()}`)
49
  }
50

51
  return await response.json()
52
}
53