-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpublicEnvVariables.ts
67 lines (61 loc) · 2.17 KB
/
publicEnvVariables.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
export const isRecord = (obj: unknown): obj is Record<string, unknown> =>
obj instanceof Object;
type rootLoaderType = {
root: {
envStuff: {
ENV: {
PUBLIC_API_URL?: string;
PUBLIC_AUTH_URL?: string;
PUBLIC_CLIENT_SENTRY_DSN?: string;
PUBLIC_SITE_URL?: string;
};
};
};
};
export const isRootLoaderData = (obj: unknown): obj is rootLoaderType =>
isRecord(obj) &&
isRecord(obj.root) &&
isRecord(obj.root.envStuff) &&
isRecord(obj.root.envStuff.ENV) &&
(typeof obj.root.envStuff.ENV.PUBLIC_API_URL === "string" ||
typeof obj.root.envStuff.ENV.PUBLIC_API_URL === "undefined") &&
(typeof obj.root.envStuff.ENV.PUBLIC_AUTH_URL === "string" ||
typeof obj.root.envStuff.ENV.PUBLIC_AUTH_URL === "undefined") &&
(typeof obj.root.envStuff.ENV.PUBLIC_CLIENT_SENTRY_DSN === "string" ||
typeof obj.root.envStuff.ENV.PUBLIC_CLIENT_SENTRY_DSN === "undefined") &&
(typeof obj.root.envStuff.ENV.PUBLIC_SITE_URL === "string" ||
typeof obj.root.envStuff.ENV.PUBLIC_SITE_URL === "undefined");
export type publicEnvVariablesKeys =
| "SITE_URL"
| "API_URL"
| "AUTH_URL"
| "CLIENT_SENTRY_DSN";
export type PublicPrefix<envVariable extends string> = `PUBLIC_${envVariable}`;
export type publicEnvVariables = Partial<{
[key in PublicPrefix<publicEnvVariablesKeys>]: string | undefined;
}>;
export function getPublicEnvVariables(
vars: PublicPrefix<publicEnvVariablesKeys>[]
): publicEnvVariables {
const returnedVars: publicEnvVariables = {};
if (typeof process !== "undefined" && process.env) {
vars.forEach((envVar) => {
if (envVar.startsWith("PUBLIC_") && envVar in process.env) {
returnedVars[envVar] = process.env[envVar];
}
});
} else if (
typeof window !== "undefined" &&
typeof window.__remixContext.state.loaderData !== "undefined" &&
isRootLoaderData(window.__remixContext.state.loaderData)
) {
const availableENV =
window.__remixContext.state.loaderData.root.envStuff.ENV;
vars.forEach((envVar) => {
if (envVar.startsWith("PUBLIC_") && envVar in availableENV) {
returnedVars[envVar] = availableENV[envVar];
}
});
}
return returnedVars;
}