Create a Page Rule

Creates a new 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
 * Create a Page Rule
8
 * Creates a new Page Rule.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  body: {
14
    actions: {
15
      modified_on?: string;
16
      name?: "forward_url";
17
      value?: {
18
        type?: "temporary" | "permanent";
19
        url?: string;
20
        [k: string]: unknown;
21
      };
22
      [k: string]: unknown;
23
    }[];
24
    priority?: number;
25
    status?: "active" | "disabled";
26
    targets: {
27
      constraint?: {
28
        operator:
29
          | "matches"
30
          | "contains"
31
          | "equals"
32
          | "not_equal"
33
          | "not_contain";
34
        value: string;
35
        [k: string]: unknown;
36
      } & { value?: string; [k: string]: unknown };
37
      target?: "url";
38
      [k: string]: unknown;
39
    }[];
40
    [k: string]: unknown;
41
  }
42
) {
43
  const url = new URL(
44
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/pagerules`
45
  );
46

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