Create routing rule

Rules consist of a set of criteria for matching emails (such as an email being sent to a specific custom email address) plus a set of actions to take on the email (like forwarding it to a specific destination address).

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 routing rule
8
 * Rules consist of a set of criteria for matching emails (such as an email being sent to a specific custom email address) plus a set of actions to take on the email (like forwarding it to a specific destination address).
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  body: {
14
    actions: {
15
      type: "drop" | "forward" | "worker";
16
      value: string[];
17
      [k: string]: unknown;
18
    }[];
19
    enabled?: true | false;
20
    matchers: {
21
      field: "to";
22
      type: "literal";
23
      value: string;
24
      [k: string]: unknown;
25
    }[];
26
    name?: string;
27
    priority?: number;
28
    [k: string]: unknown;
29
  }
30
) {
31
  const url = new URL(
32
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/email/routing/rules`
33
  );
34

35
  const response = await fetch(url, {
36
    method: "POST",
37
    headers: {
38
      "X-AUTH-EMAIL": auth.email,
39
      "X-AUTH-KEY": auth.key,
40
      "Content-Type": "application/json",
41
      Authorization: "Bearer " + auth.token,
42
    },
43
    body: JSON.stringify(body),
44
  });
45
  if (!response.ok) {
46
    const text = await response.text();
47
    throw new Error(`${response.status} ${text}`);
48
  }
49
  return await response.json();
50
}
51