List core web vital metrics trend

Lists the core web vital metrics trend over time for a specific page.

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
 * List core web vital metrics trend
8
 * Lists the core web vital metrics trend over time for a specific page.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  url: string,
14
  region:
15
    | "asia-east1"
16
    | "asia-northeast1"
17
    | "asia-northeast2"
18
    | "asia-south1"
19
    | "asia-southeast1"
20
    | "australia-southeast1"
21
    | "europe-north1"
22
    | "europe-southwest1"
23
    | "europe-west1"
24
    | "europe-west2"
25
    | "europe-west3"
26
    | "europe-west4"
27
    | "europe-west8"
28
    | "europe-west9"
29
    | "me-west1"
30
    | "southamerica-east1"
31
    | "us-central1"
32
    | "us-east1"
33
    | "us-east4"
34
    | "us-south1"
35
    | "us-west1"
36
    | undefined,
37
  deviceType: "DESKTOP" | "MOBILE" | undefined,
38
  start: string | undefined,
39
  end: string | undefined,
40
  tz: string | undefined,
41
  metrics: string | undefined
42
) {
43
  const url_ = new URL(
44
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/speed_api/pages/${url}/trend`
45
  );
46
  for (const [k, v] of [
47
    ["region", region],
48
    ["deviceType", deviceType],
49
    ["start", start],
50
    ["end", end],
51
    ["tz", tz],
52
    ["metrics", metrics],
53
  ]) {
54
    if (v !== undefined && v !== "") {
55
      url_.searchParams.append(k, v);
56
    }
57
  }
58
  const response = await fetch(url_, {
59
    method: "GET",
60
    headers: {
61
      "X-AUTH-EMAIL": auth.email,
62
      "X-AUTH-KEY": auth.key,
63
      Authorization: "Bearer " + auth.token,
64
    },
65
    body: undefined,
66
  });
67
  if (!response.ok) {
68
    const text = await response.text();
69
    throw new Error(`${response.status} ${text}`);
70
  }
71
  return await response.json();
72
}
73