Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

vercel-env.mjs

55 lines1.7 KB

1import { readFile } from "node:fs/promises";
2import { parseEnv } from "node:util";
3import { execFileSync } from "node:child_process";
4const environment = process.argv[2] ?? "preview";
5if (!["preview", "production"].includes(environment))
6 throw new Error("Choose preview or production");
7const values = parseEnv(
8 await readFile(new URL("../.env.local", import.meta.url), "utf8"),
9);
10const project = JSON.parse(
11 await readFile(new URL("../.vercel/project.json", import.meta.url), "utf8"),
12);
13for (const key of [
14 "DATABASE_URL",
15 "DATABASE_URL_UNPOOLED",
16 "NEON_REALTIME_SECRET",
17 "NEXT_PUBLIC_NEON_REALTIME_URL",
18]) {
19 if (!values[key]) throw new Error(`Missing ${key}`);
20 // Feed credentials over stdin, never as command arguments or in logs.
21 if (key.startsWith("NEXT_PUBLIC_")) {
22 const url = new URL(values[key]);
23 if (url.protocol !== "wss:" || url.username || url.password || url.search)
24 throw new Error(
25 "The browser URL must be a public WebSocket endpoint without credentials",
26 );
27 execFileSync(
28 "vercel",
29 [
30 "api",
31 `/v10/projects/${project.projectId}/env?upsert=true&teamId=${project.orgId}`,
32 "--method",
33 "POST",
34 "--input",
35 "-",
36 "--silent",
37 ],
38 {
39 input: JSON.stringify({
40 key,
41 value: url.href,
42 type: "plain",
43 target: [environment],
44 }),
45 stdio: ["pipe", "ignore", "inherit"],
46 },
47 );
48 } else
49 execFileSync(
50 "vercel",
51 ["env", "add", key, environment, "--force", "--yes"],
52 { input: values[key], stdio: ["pipe", "ignore", "inherit"] },
53 );
54 console.log(`Configured ${key} (${environment})`);