0

List DNS Records

by
Published today

List a zone's DNS records, optionally filtered by type, name or content.

Script cloudflare Verified

The script

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

3
export type DynSelect_zone_id = string
4

5
// Dropdown of the account's zones so users pick a domain instead of pasting its 32-char id.
6
// ponytail: first 50 zones only (API max per_page); paste the id directly beyond that.
7
export async function zone_id(auth: RT.Cloudflare) {
8
  const response = await fetch(
9
    "https://api.cloudflare.com/client/v4/zones?per_page=50",
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20
  const { result } = (await response.json()) as {
21
    result: { id: string; name: string }[]
22
  }
23
  return result.map((z) => ({ value: z.id, label: z.name }))
24
}
25

26
/**
27
 * List DNS Records
28
 * List a zone's DNS records, optionally filtered by type, name or content.
29
 */
30
export async function main(
31
  auth: RT.Cloudflare,
32
  zone_id: DynSelect_zone_id,
33
  type:
34
    | "A"
35
    | "AAAA"
36
    | "CNAME"
37
    | "MX"
38
    | "TXT"
39
    | "NS"
40
    | "SRV"
41
    | "CAA"
42
    | "PTR"
43
    | "HTTPS"
44
    | "SVCB"
45
    | "LOC"
46
    | "NAPTR"
47
    | "CERT"
48
    | "DNSKEY"
49
    | "DS"
50
    | "SMIMEA"
51
    | "SSHFP"
52
    | "TLSA"
53
    | "URI"
54
    | "OPENPGPKEY"
55
    | undefined,
56
  name: string | undefined,
57
  content: string | undefined,
58
  page: number | undefined,
59
  per_page: number | undefined
60
) {
61
  const url = new URL(
62
    `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records`
63
  )
64
  for (const [k, v] of Object.entries({
65
    type,
66
    name,
67
    content,
68
    page,
69
    per_page,
70
  })) {
71
    if (v != null && v !== "") url.searchParams.append(k, String(v))
72
  }
73

74
  const response = await fetch(url, {
75
    headers: {
76
      Authorization: `Bearer ${auth.token}`,
77
      Accept: "application/json",
78
    },
79
  })
80

81
  if (!response.ok) {
82
    throw new Error(`${response.status} ${await response.text()}`)
83
  }
84

85
  return await response.json()
86
}
87