-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver-env.ts
More file actions
60 lines (44 loc) · 1.49 KB
/
server-env.ts
File metadata and controls
60 lines (44 loc) · 1.49 KB
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
import 'server-only';
import { RUNTIME_ENV } from './runtime-env.generated';
type NetlifyEnv = {
get?: (key: string) => string | undefined;
};
type NetlifyRuntime = {
env?: NetlifyEnv;
};
declare const Netlify: NetlifyRuntime | undefined;
function getNetlifyRuntime(): NetlifyRuntime | undefined {
const fromGlobalThis = (globalThis as { Netlify?: NetlifyRuntime }).Netlify;
if (fromGlobalThis) return fromGlobalThis;
if (typeof Netlify !== 'undefined') return Netlify;
return undefined;
}
function readFromNetlifyEnv(key: string): string | undefined {
const runtime = getNetlifyRuntime();
const value = runtime?.env?.get?.(key);
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
const GENERATED_FALLBACK_KEYS = new Set([
'APP_ENV',
'CONTEXT',
'NETLIFY',
'DATABASE_URL',
'DATABASE_URL_LOCAL',
'AUTH_SECRET',
'CSRF_SECRET',
]);
function canUseGeneratedFallback(key: string): boolean {
return GENERATED_FALLBACK_KEYS.has(key);
}
export function readServerEnv(key: string): string | undefined {
const fromProcess = process.env[key]?.trim();
if (fromProcess) return fromProcess;
const fromNetlify = readFromNetlifyEnv(key);
if (fromNetlify) return fromNetlify;
if (!canUseGeneratedFallback(key)) return undefined;
return readFromGeneratedRuntimeEnv(key);
}
function readFromGeneratedRuntimeEnv(key: string): string | undefined {
const value = RUNTIME_ENV[key];
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}