0

Set env var value

by
Published Oct 17, 2025

Updates or creates a new value for an existing environment variable.

Script netlify Verified

The script

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