Edit a Page Rule

Updates one or more fields of an existing Page Rule.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Edit a Page Rule
8
 * Updates one or more fields of an existing Page Rule.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  identifier: string,
13
  zone_identifier: string,
14
  body: {
15
    actions?: {
16
      modified_on?: string;
17
      name?: "forward_url";
18
      value?: {
19
        type?: "temporary" | "permanent";
20
        url?: string;
21
        [k: string]: unknown;
22
      };
23
      [k: string]: unknown;
24
    }[];
25
    priority?: number;
26
    status?: "active" | "disabled";
27
    targets?: {
28
      constraint?: {
29
        operator:
30
          | "matches"
31
          | "contains"
32
          | "equals"
33
          | "not_equal"
34
          | "not_contain";
35
        value: string;
36
        [k: string]: unknown;
37
      } & { value?: string; [k: string]: unknown };
38
      target?: "url";
39
      [k: string]: unknown;
40
    }[];
41
    [k: string]: unknown;
42
  }
43
) {
44
  const url = new URL(
45
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/pagerules/${identifier}`
46
  );
47

48
  const response = await fetch(url, {
49
    method: "PATCH",
50
    headers: {
51
      "X-AUTH-EMAIL": auth.email,
52
      "X-AUTH-KEY": auth.key,
53
      "Content-Type": "application/json",
54
      Authorization: "Bearer " + auth.token,
55
    },
56
    body: JSON.stringify(body),
57
  });
58
  if (!response.ok) {
59
    const text = await response.text();
60
    throw new Error(`${response.status} ${text}`);
61
  }
62
  return await response.json();
63
}
64