0

Update env var

by
Published Oct 17, 2025

Updates an existing environment variable and all of its values. Existing values will be replaced by values provided.

Script netlify Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Netlify = {
3
  token: string;
4
};
5
/**
6
 * Update env var
7
 * Updates an existing environment variable and all of its values. Existing values will be replaced by values provided.
8
 */
9
export async function main(
10
  auth: Netlify,
11
  account_id: string,
12
  key: string,
13
  site_id: string | undefined,
14
  body: {
15
    key?: string;
16
    scopes?: "builds" | "functions" | "runtime" | "post-processing"[];
17
    values?: {
18
      id?: string;
19
      value?: string;
20
      context?:
21
        | "all"
22
        | "dev"
23
        | "branch-deploy"
24
        | "deploy-preview"
25
        | "production"
26
        | "branch";
27
      context_parameter?: string;
28
    }[];
29
    is_secret?: false | true;
30
  },
31
) {
32
  const url = new URL(
33
    `https://api.netlify.com/api/v1/accounts/${account_id}/env/${key}`,
34
  );
35
  for (const [k, v] of [["site_id", site_id]]) {
36
    if (v !== undefined && v !== "" && k !== undefined) {
37
      url.searchParams.append(k, v);
38
    }
39
  }
40
  const response = await fetch(url, {
41
    method: "PUT",
42
    headers: {
43
      "Content-Type": "application/json",
44
      Authorization: "Bearer " + auth.token,
45
    },
46
    body: JSON.stringify(body),
47
  });
48
  if (!response.ok) {
49
    const text = await response.text();
50
    throw new Error(`${response.status} ${text}`);
51
  }
52
  return await response.json();
53
}
54