Change Browser Cache TTL setting

Browser Cache TTL (in seconds) specifies how long Cloudflare-cached resources will remain on your visitors' computers. Cloudflare will honor any larger times specified by your server. (https://support.cloudflare.com/hc/en-us/articles/200168276).

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
 * Change Browser Cache TTL setting
8
 * Browser Cache TTL (in seconds) specifies how long Cloudflare-cached resources will remain on your visitors' computers. Cloudflare will honor any larger times specified by your server. (https://support.cloudflare.com/hc/en-us/articles/200168276).
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  body: {
14
    value:
15
      | 0
16
      | 30
17
      | 60
18
      | 120
19
      | 300
20
      | 1200
21
      | 1800
22
      | 3600
23
      | 7200
24
      | 10800
25
      | 14400
26
      | 18000
27
      | 28800
28
      | 43200
29
      | 57600
30
      | 72000
31
      | 86400
32
      | 172800
33
      | 259200
34
      | 345600
35
      | 432000
36
      | 691200
37
      | 1382400
38
      | 2073600
39
      | 2678400
40
      | 5356800
41
      | 16070400
42
      | 31536000;
43
    [k: string]: unknown;
44
  }
45
) {
46
  const url = new URL(
47
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/settings/browser_cache_ttl`
48
  );
49

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