0

Change variants setting

by
Published Nov 16, 2023

Variant support enables caching variants of images with certain file extensions in addition to the original. This only applies when the origin server sends the 'Vary: Accept' response header. If the origin server sends 'Vary: Accept' but does not serve the variant requested, the response will not be cached. This will be indicated with BYPASS cache status in the response headers.

Script cloudflare Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 403 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Change variants setting
8
 * Variant support enables caching variants of images with certain file extensions in addition to the original. This only applies when the origin server sends the 'Vary: Accept' response header. If the origin server sends 'Vary: Accept' but does not serve the variant requested, the response will not be cached. This will be indicated with BYPASS cache status in the response headers.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone_identifier: string,
13
  body: {
14
    value: {
15
      avif?: unknown[];
16
      bmp?: unknown[];
17
      gif?: unknown[];
18
      jp2?: unknown[];
19
      jpeg?: unknown[];
20
      jpg?: unknown[];
21
      jpg2?: unknown[];
22
      png?: unknown[];
23
      tif?: unknown[];
24
      tiff?: unknown[];
25
      webp?: unknown[];
26
      [k: string]: unknown;
27
    };
28
    [k: string]: unknown;
29
  }
30
) {
31
  const url = new URL(
32
    `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/cache/variants`
33
  );
34

35
  const response = await fetch(url, {
36
    method: "PATCH",
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