0

Create env vars

by
Published Oct 17, 2025

Creates new environment variables. Granular scopes are available on Pro plans and above.

Script netlify Verified

The script

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