node-env-resolver 6.5.1 → 6.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +708 -400
- package/dist/builder.cjs +1 -1
- package/dist/builder.d.cts +1 -1
- package/dist/builder.d.ts +1 -1
- package/dist/builder.js +1 -1
- package/dist/chunk-3EWCMDFP.js +9 -0
- package/dist/chunk-BFLXBLZ3.cjs +1 -0
- package/dist/chunk-CDXO2XX3.cjs +2 -0
- package/dist/chunk-CTJYBBOB.js +2 -0
- package/dist/chunk-DIJNUFGZ.cjs +15 -0
- package/dist/chunk-DYFRO3NM.cjs +9 -0
- package/dist/chunk-K4NIC5T3.js +9 -0
- package/dist/chunk-WVMDTD6J.cjs +9 -0
- package/dist/chunk-ZMRT37K3.js +1 -0
- package/dist/chunk-ZSM2NDX5.js +15 -0
- package/dist/cli/bin.cjs +74 -0
- package/dist/cli/bin.js +74 -0
- package/dist/cli.d.cts +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +59 -3
- package/dist/index.d.ts +59 -3
- package/dist/index.js +1 -1
- package/dist/provider-kit.cjs +2 -0
- package/dist/provider-kit.d.cts +50 -0
- package/dist/provider-kit.d.ts +50 -0
- package/dist/provider-kit.js +2 -0
- package/dist/resolver.cjs +1 -1
- package/dist/resolver.d.cts +1 -1
- package/dist/resolver.d.ts +1 -1
- package/dist/resolver.js +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +2 -27
- package/dist/resolvers.d.ts +2 -27
- package/dist/resolvers.js +1 -1
- package/dist/runtime/index.cjs +1 -0
- package/dist/runtime/index.d.cts +161 -0
- package/dist/runtime/index.d.ts +161 -0
- package/dist/runtime/index.js +1 -0
- package/dist/types--RcOnfdl.d.cts +284 -0
- package/dist/types--RcOnfdl.d.ts +284 -0
- package/dist/types.cjs +1 -1
- package/dist/types.d.cts +1 -129
- package/dist/types.d.ts +1 -129
- package/dist/types.js +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.d.cts +56 -12
- package/dist/utils.d.ts +56 -12
- package/dist/utils.js +1 -1
- package/dist/valibot.cjs +1 -1
- package/dist/valibot.d.cts +12 -25
- package/dist/valibot.d.ts +12 -25
- package/dist/valibot.js +1 -1
- package/dist/validators.cjs +2 -2
- package/dist/validators.d.cts +25 -48
- package/dist/validators.d.ts +25 -48
- package/dist/validators.js +2 -2
- package/dist/web.cjs +5 -5
- package/dist/web.d.cts +3 -1
- package/dist/web.d.ts +3 -1
- package/dist/web.js +5 -5
- package/dist/zod.cjs +1 -1
- package/dist/zod.d.cts +12 -25
- package/dist/zod.d.ts +12 -25
- package/dist/zod.js +1 -1
- package/package.json +26 -31
- package/binding.gyp +0 -9
- package/dist/chunk-2IQQVAXA.cjs +0 -9
- package/dist/chunk-46CBATKM.js +0 -1
- package/dist/chunk-C34FGZOG.js +0 -9
- package/dist/chunk-FNF55TN4.cjs +0 -1
- package/dist/chunk-G36OESVW.cjs +0 -1
- package/dist/chunk-I5UKYTX6.js +0 -1
- package/dist/chunk-MFFH2ZXS.js +0 -17
- package/dist/chunk-QCKMQEJP.cjs +0 -17
- package/dist/chunk-S7AB6UX7.cjs +0 -9
- package/dist/chunk-TGIYWWDY.js +0 -9
- package/dist/chunk-VUUPIWFJ.js +0 -9
- package/dist/chunk-ZDRU3RSU.cjs +0 -9
- package/dist/cli-main.cjs +0 -4
- package/dist/cli-main.js +0 -4
- package/dist/redaction.cjs +0 -1
- package/dist/redaction.d.cts +0 -54
- package/dist/redaction.d.ts +0 -54
- package/dist/redaction.js +0 -1
- package/dist/typegen.cjs +0 -1
- package/dist/typegen.d.cts +0 -52
- package/dist/typegen.d.ts +0 -52
- package/dist/typegen.js +0 -1
- package/index.js +0 -1
- /package/dist/{cli-main.d.cts → cli/bin.d.cts} +0 -0
- /package/dist/{cli-main.d.ts → cli/bin.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Type-safe environment variable resolution with zero dependencies and ultra-small
|
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/node-env-resolver)
|
|
6
6
|
|
|
7
|
-
**Bundle Size:** ~
|
|
7
|
+
**Bundle Size:** ~6.3KB gzipped (core), code-splits for advanced features
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -19,6 +19,7 @@ This package uses modern [package.json `exports`](https://nodejs.org/api/package
|
|
|
19
19
|
**What to change:**
|
|
20
20
|
|
|
21
21
|
If your `tsconfig.json` has:
|
|
22
|
+
|
|
22
23
|
```json
|
|
23
24
|
{
|
|
24
25
|
"compilerOptions": {
|
|
@@ -29,16 +30,18 @@ If your `tsconfig.json` has:
|
|
|
29
30
|
```
|
|
30
31
|
|
|
31
32
|
**Change it to:**
|
|
33
|
+
|
|
32
34
|
```json
|
|
33
35
|
{
|
|
34
36
|
"compilerOptions": {
|
|
35
|
-
"module": "NodeNext",
|
|
37
|
+
"module": "NodeNext", // Changed from "CommonJS"
|
|
36
38
|
"moduleResolution": "NodeNext" // Changed from "node"
|
|
37
39
|
}
|
|
38
40
|
}
|
|
39
41
|
```
|
|
40
42
|
|
|
41
43
|
**Alternative options:**
|
|
44
|
+
|
|
42
45
|
- For bundler projects (Vite, Webpack, etc.): Use `"moduleResolution": "bundler"` (you can keep `"module": "CommonJS"` or use `"ESNext"`)
|
|
43
46
|
- For Node.js projects: Use `"moduleResolution": "node16"` with `"module": "node16"`
|
|
44
47
|
|
|
@@ -52,14 +55,18 @@ If you see module resolution errors, see the [Troubleshooting](#troubleshooting)
|
|
|
52
55
|
```ts
|
|
53
56
|
import { resolve } from 'node-env-resolver';
|
|
54
57
|
import { string } from 'node-env-resolver/validators';
|
|
58
|
+
import { protect } from 'node-env-resolver/runtime';
|
|
55
59
|
|
|
56
60
|
const config = resolve({
|
|
57
61
|
PORT: 3000,
|
|
58
62
|
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
59
63
|
DEBUG: false,
|
|
60
|
-
API_KEY: string({optional:true})
|
|
64
|
+
API_KEY: string({ optional: true }),
|
|
61
65
|
});
|
|
62
66
|
|
|
67
|
+
// Redact secrets from all console output in one call
|
|
68
|
+
const unprotect = protect(config);
|
|
69
|
+
|
|
63
70
|
// Resulting type (fully inferred):
|
|
64
71
|
// type config = {
|
|
65
72
|
// PORT: number;
|
|
@@ -69,10 +76,10 @@ const config = resolve({
|
|
|
69
76
|
// }
|
|
70
77
|
|
|
71
78
|
// TypeScript knows the exact types:
|
|
72
|
-
config.PORT;
|
|
73
|
-
config.NODE_ENV;
|
|
74
|
-
config.DEBUG;
|
|
75
|
-
config.API_KEY;
|
|
79
|
+
config.PORT; // number
|
|
80
|
+
config.NODE_ENV; // 'development' | 'production' | 'test'
|
|
81
|
+
config.DEBUG; // boolean
|
|
82
|
+
config.API_KEY; // string | undefined
|
|
76
83
|
```
|
|
77
84
|
|
|
78
85
|
## Quick start (with custom resolvers)
|
|
@@ -86,26 +93,32 @@ import { awsSecrets, gcpSecrets, vaultSecrets } from 'node-env-resolver-aws';
|
|
|
86
93
|
// Synchronous with custom resolver (object syntax)
|
|
87
94
|
const config = resolve({
|
|
88
95
|
resolvers: [
|
|
89
|
-
[
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
+
[
|
|
97
|
+
dotenv(),
|
|
98
|
+
{
|
|
99
|
+
PORT: 3000,
|
|
100
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
101
|
+
DEBUG: false,
|
|
102
|
+
API_KEY: string({ optional: true }),
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
],
|
|
96
106
|
});
|
|
97
107
|
|
|
98
108
|
// Asynchronous with any resolvers (both sync and async work!)
|
|
99
109
|
const config = await resolveAsync({
|
|
100
110
|
resolvers: [
|
|
101
|
-
[
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
111
|
+
[
|
|
112
|
+
dotenv(),
|
|
113
|
+
{
|
|
114
|
+
PORT: 3000,
|
|
115
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
116
|
+
DEBUG: false,
|
|
117
|
+
API_KEY: string({ optional: true }),
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
[awsSecrets(), { DATABASE_URL: url() }],
|
|
121
|
+
],
|
|
109
122
|
});
|
|
110
123
|
|
|
111
124
|
// Resulting type (fully inferred):
|
|
@@ -124,9 +137,9 @@ const config = await resolveAsync({
|
|
|
124
137
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
125
138
|
[awsSecrets(), { API_KEY: string() }],
|
|
126
139
|
[gcpSecrets(), { JWT_SECRET: string() }],
|
|
127
|
-
[vaultSecrets(), { REDIS_URL: redis() }]
|
|
140
|
+
[vaultSecrets(), { REDIS_URL: redis() }],
|
|
128
141
|
],
|
|
129
|
-
options: { priority: 'last' }
|
|
142
|
+
options: { priority: 'last' },
|
|
130
143
|
});
|
|
131
144
|
```
|
|
132
145
|
|
|
@@ -148,7 +161,8 @@ const config = await resolveAsync({
|
|
|
148
161
|
- [Safe error handling](#safe-error-handling)
|
|
149
162
|
- [Synchronous resolution](#synchronous-resolution)
|
|
150
163
|
- [Advanced features](#advanced-features)
|
|
151
|
-
- [
|
|
164
|
+
- [TTL caching](#ttl-caching)
|
|
165
|
+
- [Polling remote config](#polling-remote-config)
|
|
152
166
|
- [API Reference](#api-reference)
|
|
153
167
|
- [Configuration Options](#configuration-options)
|
|
154
168
|
- [Framework examples](#framework-examples)
|
|
@@ -168,8 +182,8 @@ import { resolve } from 'node-env-resolver';
|
|
|
168
182
|
import { postgres, string } from 'node-env-resolver/validators';
|
|
169
183
|
|
|
170
184
|
const config = resolve({
|
|
171
|
-
DATABASE_URL: postgres(),
|
|
172
|
-
API_KEY: string()
|
|
185
|
+
DATABASE_URL: postgres(), // Required PostgreSQL URL
|
|
186
|
+
API_KEY: string(), // Required
|
|
173
187
|
});
|
|
174
188
|
```
|
|
175
189
|
|
|
@@ -181,9 +195,9 @@ Provide a default value to use when the environment variable is not set:
|
|
|
181
195
|
import { resolve } from 'node-env-resolver';
|
|
182
196
|
|
|
183
197
|
const config = resolve({
|
|
184
|
-
PORT: 3000,
|
|
185
|
-
DEBUG: false,
|
|
186
|
-
LOG_LEVEL: 'info'
|
|
198
|
+
PORT: 3000, // Defaults to 3000
|
|
199
|
+
DEBUG: false, // Defaults to false
|
|
200
|
+
LOG_LEVEL: 'info', // Defaults to 'info'
|
|
187
201
|
});
|
|
188
202
|
```
|
|
189
203
|
|
|
@@ -195,9 +209,9 @@ Use the `{optional: true}` option to make a value optional:
|
|
|
195
209
|
import { string, url, number } from 'node-env-resolver/validators';
|
|
196
210
|
|
|
197
211
|
const config = resolve({
|
|
198
|
-
API_KEY: string({optional: true}),
|
|
199
|
-
REDIS_URL: url({optional: true}),
|
|
200
|
-
MAX_RETRIES: number({optional: true}) // number | undefined
|
|
212
|
+
API_KEY: string({ optional: true }), // string | undefined
|
|
213
|
+
REDIS_URL: url({ optional: true }), // string | undefined
|
|
214
|
+
MAX_RETRIES: number({ optional: true }), // number | undefined
|
|
201
215
|
});
|
|
202
216
|
```
|
|
203
217
|
|
|
@@ -210,11 +224,11 @@ import { resolve } from 'node-env-resolver';
|
|
|
210
224
|
|
|
211
225
|
const config = resolve({
|
|
212
226
|
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
213
|
-
LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
|
|
227
|
+
LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const,
|
|
214
228
|
});
|
|
215
229
|
|
|
216
230
|
// TypeScript knows the exact types
|
|
217
|
-
config.NODE_ENV;
|
|
231
|
+
config.NODE_ENV; // 'development' | 'production' | 'test'
|
|
218
232
|
config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
|
|
219
233
|
```
|
|
220
234
|
|
|
@@ -234,7 +248,9 @@ const config = resolve({
|
|
|
234
248
|
PROTOCOL: optional(['http', 'grpc'] as const),
|
|
235
249
|
|
|
236
250
|
// Optional enum - Method 2: enumOf() function (explicit)
|
|
237
|
-
LOG_LEVEL: enumOf(['error', 'warn', 'info', 'debug'] as const, {
|
|
251
|
+
LOG_LEVEL: enumOf(['error', 'warn', 'info', 'debug'] as const, {
|
|
252
|
+
optional: true,
|
|
253
|
+
}),
|
|
238
254
|
|
|
239
255
|
// Enum with default value
|
|
240
256
|
COMPRESSION: enumOf(['gzip', 'brotli', 'none'] as const, { default: 'gzip' }),
|
|
@@ -254,6 +270,7 @@ The library validates environment variable names to prevent shell errors and ens
|
|
|
254
270
|
### Supported Name Formats
|
|
255
271
|
|
|
256
272
|
Variable names can use:
|
|
273
|
+
|
|
257
274
|
- **Letters** (both uppercase and lowercase): `A-Z`, `a-z`
|
|
258
275
|
- **Numbers** (not as first character): `0-9`
|
|
259
276
|
- **Underscores**: `_`
|
|
@@ -265,12 +282,12 @@ import { resolve } from 'node-env-resolver';
|
|
|
265
282
|
import { string } from 'node-env-resolver/validators';
|
|
266
283
|
|
|
267
284
|
const config = resolve({
|
|
268
|
-
PORT: 3000,
|
|
269
|
-
port: 3000,
|
|
270
|
-
myApiKey: string(),
|
|
271
|
-
my_api_key: string(),
|
|
272
|
-
API_KEY_V2: string(),
|
|
273
|
-
_PRIVATE: string()
|
|
285
|
+
PORT: 3000, // ✅ SCREAMING_SNAKE_CASE (traditional)
|
|
286
|
+
port: 3000, // ✅ lowercase
|
|
287
|
+
myApiKey: string(), // ✅ camelCase
|
|
288
|
+
my_api_key: string(), // ✅ snake_case
|
|
289
|
+
API_KEY_V2: string(), // ✅ with numbers (not first char)
|
|
290
|
+
_PRIVATE: string(), // ✅ starting with underscore
|
|
274
291
|
});
|
|
275
292
|
```
|
|
276
293
|
|
|
@@ -281,11 +298,11 @@ import { resolve } from 'node-env-resolver';
|
|
|
281
298
|
import { string } from 'node-env-resolver/validators';
|
|
282
299
|
|
|
283
300
|
const config = resolve({
|
|
284
|
-
'123PORT': 3000,
|
|
285
|
-
'API-KEY': string(),
|
|
286
|
-
'API.KEY': string(),
|
|
287
|
-
'API KEY': string(),
|
|
288
|
-
'API@KEY': string()
|
|
301
|
+
'123PORT': 3000, // ❌ Starts with number
|
|
302
|
+
'API-KEY': string(), // ❌ Contains hyphen
|
|
303
|
+
'API.KEY': string(), // ❌ Contains dot
|
|
304
|
+
'API KEY': string(), // ❌ Contains space
|
|
305
|
+
'API@KEY': string(), // ❌ Special characters
|
|
289
306
|
});
|
|
290
307
|
```
|
|
291
308
|
|
|
@@ -307,13 +324,14 @@ const config = await resolveAsync({
|
|
|
307
324
|
resolvers: [
|
|
308
325
|
[processEnv(), { PORT: 3000 }],
|
|
309
326
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
310
|
-
[awsSecrets(), { API_KEY: string() }]
|
|
311
|
-
]
|
|
327
|
+
[awsSecrets(), { API_KEY: string() }],
|
|
328
|
+
],
|
|
312
329
|
// Perfect for complex microservice architectures!
|
|
313
330
|
});
|
|
314
331
|
```
|
|
315
332
|
|
|
316
333
|
**Benefits:**
|
|
334
|
+
|
|
317
335
|
- **No artificial limits** - use as many resolvers as needed
|
|
318
336
|
- **Better type inference** - proper schema merging with full TypeScript support
|
|
319
337
|
- **Cleaner code** - single implementation instead of multiple overloads
|
|
@@ -323,13 +341,15 @@ const config = await resolveAsync({
|
|
|
323
341
|
|
|
324
342
|
The library uses a two-tier validation strategy with lazy-loaded validators:
|
|
325
343
|
|
|
326
|
-
**Basic types** (~
|
|
344
|
+
**Basic types** (~6.3KB core - inline validation):
|
|
345
|
+
|
|
327
346
|
- `string`, `number`, `boolean` (with min/max validation)
|
|
328
347
|
- `enum` (array validation)
|
|
329
348
|
- `pattern` (regex validation)
|
|
330
349
|
- `custom` (validator functions)
|
|
331
350
|
|
|
332
351
|
**Advanced types** (+1KB when used - lazy-loaded):
|
|
352
|
+
|
|
333
353
|
- Database URLs: `postgres`, `mysql`, `mongodb`, `redis`
|
|
334
354
|
- Web types: `http`, `https`, `url`, `email`
|
|
335
355
|
- Format types: `json`, `date`, `timestamp`, `port`
|
|
@@ -346,18 +366,17 @@ const config = resolve({
|
|
|
346
366
|
PORT: 3000,
|
|
347
367
|
DATABASE_URL: postgres(),
|
|
348
368
|
API_URL: url(),
|
|
349
|
-
NODE_ENV: ['development', 'production'] as const
|
|
369
|
+
NODE_ENV: ['development', 'production'] as const,
|
|
350
370
|
});
|
|
351
371
|
|
|
352
372
|
// Also works with async resolvers
|
|
353
373
|
const config = await resolveAsync({
|
|
354
|
-
resolvers: [
|
|
355
|
-
[awsSecrets(), { DATABASE_URL: postgres(), API_URL: url() }]
|
|
356
|
-
]
|
|
374
|
+
resolvers: [[awsSecrets(), { DATABASE_URL: postgres(), API_URL: url() }]],
|
|
357
375
|
});
|
|
358
376
|
```
|
|
359
377
|
|
|
360
|
-
### What's in the
|
|
378
|
+
### What's in the 6.3KB core?
|
|
379
|
+
|
|
361
380
|
- Core resolver logic (async/sync resolution)
|
|
362
381
|
- Schema normalization & type coercion
|
|
363
382
|
- Basic validation (string, number, boolean, enum, pattern, custom)
|
|
@@ -365,7 +384,9 @@ const config = await resolveAsync({
|
|
|
365
384
|
- Provenance tracking & error handling
|
|
366
385
|
|
|
367
386
|
### Code Splitting Architecture
|
|
387
|
+
|
|
368
388
|
The library uses intelligent code splitting to keep the core minimal:
|
|
389
|
+
|
|
369
390
|
- **Advanced validators** (~1KB): Lazy-loaded when using types like `url`, `email`, `postgres`
|
|
370
391
|
- **Audit logging** (~150 bytes): Lazy-loaded when `enableAudit: true`
|
|
371
392
|
- **dotenv parser** (~1.6KB): Separate import from `'node-env-resolver/resolvers'`
|
|
@@ -392,7 +413,7 @@ const config = resolve({ PORT: 3000 }, { enableAudit: true });
|
|
|
392
413
|
Import only what you need for optimal bundle size:
|
|
393
414
|
|
|
394
415
|
```ts
|
|
395
|
-
// Core (~
|
|
416
|
+
// Core (~6.3KB) - Main API
|
|
396
417
|
import { resolve, safeResolve } from 'node-env-resolver';
|
|
397
418
|
|
|
398
419
|
// Resolvers (separate chunk) - .env file parsing
|
|
@@ -410,7 +431,7 @@ import { resolveValibot } from 'node-env-resolver/valibot';
|
|
|
410
431
|
import { awsSecrets } from 'node-env-resolver-aws';
|
|
411
432
|
```
|
|
412
433
|
|
|
413
|
-
**Most apps only need the core (~
|
|
434
|
+
**Most apps only need the core (~6.3KB)!**
|
|
414
435
|
|
|
415
436
|
## Custom validators
|
|
416
437
|
|
|
@@ -436,7 +457,7 @@ const isValidEmail = (value: string): string => {
|
|
|
436
457
|
|
|
437
458
|
const config = resolve({
|
|
438
459
|
CUSTOM_PORT: isValidPort,
|
|
439
|
-
ADMIN_EMAIL: isValidEmail
|
|
460
|
+
ADMIN_EMAIL: isValidEmail,
|
|
440
461
|
});
|
|
441
462
|
```
|
|
442
463
|
|
|
@@ -454,17 +475,17 @@ const validateMarketingUrl = (value: string): string => {
|
|
|
454
475
|
if (!result.valid) {
|
|
455
476
|
throw new Error(result.error || 'Invalid URL');
|
|
456
477
|
}
|
|
457
|
-
|
|
478
|
+
|
|
458
479
|
// Add custom business logic
|
|
459
480
|
if (!value.includes('marketing.example.com')) {
|
|
460
481
|
throw new Error('Must be a marketing domain URL');
|
|
461
482
|
}
|
|
462
|
-
|
|
483
|
+
|
|
463
484
|
return value;
|
|
464
485
|
};
|
|
465
486
|
|
|
466
487
|
const config = resolve({
|
|
467
|
-
MARKETING_URL: validateMarketingUrl
|
|
488
|
+
MARKETING_URL: validateMarketingUrl,
|
|
468
489
|
});
|
|
469
490
|
```
|
|
470
491
|
|
|
@@ -473,6 +494,7 @@ Available validation functions: `validatePostgres`, `mysql`, `mongodb`, `redis`,
|
|
|
473
494
|
## Multiple sources
|
|
474
495
|
|
|
475
496
|
Load configuration from multiple sources. By default, later sources override earlier ones:
|
|
497
|
+
|
|
476
498
|
```ts
|
|
477
499
|
import { resolve, resolveAsync } from 'node-env-resolver';
|
|
478
500
|
import { processEnv, dotenv, json } from 'node-env-resolver/resolvers';
|
|
@@ -482,23 +504,29 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
482
504
|
// Async mode - supports both sync and async resolvers
|
|
483
505
|
const config = await resolveAsync({
|
|
484
506
|
resolvers: [
|
|
485
|
-
[
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
507
|
+
[
|
|
508
|
+
processEnv(),
|
|
509
|
+
{
|
|
510
|
+
PORT: 3000,
|
|
511
|
+
NODE_ENV: ['development', 'production'] as const,
|
|
512
|
+
},
|
|
513
|
+
],
|
|
514
|
+
[
|
|
515
|
+
dotenv(),
|
|
516
|
+
{
|
|
517
|
+
DATABASE_URL: postgres(),
|
|
518
|
+
API_KEY: string(),
|
|
519
|
+
},
|
|
520
|
+
],
|
|
521
|
+
],
|
|
494
522
|
});
|
|
495
523
|
|
|
496
524
|
// Sync mode - supports multiple SYNC resolvers
|
|
497
525
|
const config = resolve({
|
|
498
526
|
resolvers: [
|
|
499
527
|
[dotenv(), { PORT: 3000 }],
|
|
500
|
-
[json('config.json'), { DATABASE_URL: postgres() }]
|
|
501
|
-
]
|
|
528
|
+
[json('config.json'), { DATABASE_URL: postgres() }],
|
|
529
|
+
],
|
|
502
530
|
// Both resolvers must have loadSync() method
|
|
503
531
|
});
|
|
504
532
|
|
|
@@ -507,9 +535,9 @@ const config = await resolveAsync({
|
|
|
507
535
|
resolvers: [
|
|
508
536
|
[processEnv(), { PORT: 3000 }],
|
|
509
537
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
510
|
-
[awsSecrets(), { API_KEY: string() }]
|
|
538
|
+
[awsSecrets(), { API_KEY: string() }],
|
|
511
539
|
],
|
|
512
|
-
options: { priority: 'last' }
|
|
540
|
+
options: { priority: 'last' },
|
|
513
541
|
});
|
|
514
542
|
```
|
|
515
543
|
|
|
@@ -527,8 +555,8 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
527
555
|
const config = await resolveAsync({
|
|
528
556
|
resolvers: [
|
|
529
557
|
[processEnv(), { DATABASE_URL: postgres() }],
|
|
530
|
-
[awsSecrets(), { DATABASE_URL: postgres() }]
|
|
531
|
-
]
|
|
558
|
+
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
559
|
+
],
|
|
532
560
|
// AWS wins
|
|
533
561
|
});
|
|
534
562
|
|
|
@@ -536,9 +564,9 @@ const config = await resolveAsync({
|
|
|
536
564
|
const config = await resolveAsync({
|
|
537
565
|
resolvers: [
|
|
538
566
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
539
|
-
[awsSecrets(), { DATABASE_URL: postgres() }]
|
|
567
|
+
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
540
568
|
],
|
|
541
|
-
options: { priority: 'first' }
|
|
569
|
+
options: { priority: 'first' },
|
|
542
570
|
// dotenv wins
|
|
543
571
|
});
|
|
544
572
|
|
|
@@ -546,9 +574,9 @@ const config = await resolveAsync({
|
|
|
546
574
|
const config = resolve({
|
|
547
575
|
resolvers: [
|
|
548
576
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
549
|
-
[json('config.json'), { DATABASE_URL: postgres() }]
|
|
577
|
+
[json('config.json'), { DATABASE_URL: postgres() }],
|
|
550
578
|
],
|
|
551
|
-
options: { priority: 'first' }
|
|
579
|
+
options: { priority: 'first' },
|
|
552
580
|
// dotenv wins
|
|
553
581
|
});
|
|
554
582
|
```
|
|
@@ -572,9 +600,9 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
572
600
|
const config = await resolveAsync({
|
|
573
601
|
resolvers: [
|
|
574
602
|
[dotenv(), { DATABASE_URL: postgres(), API_KEY: string(), PORT: 3000 }],
|
|
575
|
-
[awsSecrets(), { DATABASE_URL: postgres(), API_KEY: string(), PORT: 3000 }]
|
|
603
|
+
[awsSecrets(), { DATABASE_URL: postgres(), API_KEY: string(), PORT: 3000 }],
|
|
576
604
|
],
|
|
577
|
-
options: { priority: 'first' }
|
|
605
|
+
options: { priority: 'first' },
|
|
578
606
|
});
|
|
579
607
|
// If dotenv() provides all required keys, awsSecrets() is never called!
|
|
580
608
|
```
|
|
@@ -601,9 +629,9 @@ import { awsSecrets, awsSsm } from 'node-env-resolver-aws';
|
|
|
601
629
|
|
|
602
630
|
const config = await resolveAsync({
|
|
603
631
|
resolvers: [
|
|
604
|
-
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
632
|
+
[awsSecrets(), { DATABASE_URL: postgres() }], // 100ms
|
|
605
633
|
[awsSsm(), { API_KEY: string() }], // 100ms
|
|
606
|
-
]
|
|
634
|
+
],
|
|
607
635
|
// Default: priority: 'last'
|
|
608
636
|
});
|
|
609
637
|
// Total time: ~100ms (parallel) instead of ~300ms (sequential)
|
|
@@ -628,15 +656,15 @@ import { number, postgres } from 'node-env-resolver/validators';
|
|
|
628
656
|
// Synchronous safe resolve
|
|
629
657
|
const result = safeResolve({
|
|
630
658
|
PORT: number(),
|
|
631
|
-
DATABASE_URL: postgres()
|
|
659
|
+
DATABASE_URL: postgres(),
|
|
632
660
|
});
|
|
633
661
|
|
|
634
662
|
// Asynchronous safe resolve
|
|
635
663
|
const result = await safeResolveAsync({
|
|
636
664
|
resolvers: [
|
|
637
665
|
[processEnv(), { PORT: number() }],
|
|
638
|
-
[awsSecrets(), { DATABASE_URL: postgres() }]
|
|
639
|
-
]
|
|
666
|
+
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
667
|
+
],
|
|
640
668
|
});
|
|
641
669
|
|
|
642
670
|
if (result.success) {
|
|
@@ -667,9 +695,9 @@ const config = resolve({
|
|
|
667
695
|
PORT: 3000,
|
|
668
696
|
NODE_ENV: ['development', 'production'] as const,
|
|
669
697
|
API_KEY: string(),
|
|
670
|
-
API_URL: url(),
|
|
698
|
+
API_URL: url(), // Advanced types work synchronously!
|
|
671
699
|
DATABASE_URL: postgres(),
|
|
672
|
-
DEBUG: false
|
|
700
|
+
DEBUG: false,
|
|
673
701
|
});
|
|
674
702
|
```
|
|
675
703
|
|
|
@@ -684,124 +712,164 @@ import { postgres, url } from 'node-env-resolver/validators';
|
|
|
684
712
|
const config = await resolveAsync({
|
|
685
713
|
resolvers: [
|
|
686
714
|
[processEnv(), { PORT: 3000 }],
|
|
687
|
-
[dotenv(), { DATABASE_URL: postgres(), API_URL: url() }]
|
|
688
|
-
]
|
|
715
|
+
[dotenv(), { DATABASE_URL: postgres(), API_URL: url() }],
|
|
716
|
+
],
|
|
689
717
|
});
|
|
690
718
|
```
|
|
691
719
|
|
|
692
720
|
## Advanced features
|
|
693
721
|
|
|
694
|
-
### CLI
|
|
722
|
+
### CLI
|
|
695
723
|
|
|
696
|
-
|
|
724
|
+
The `ner` CLI ships with the package. Install globally or run via `npx ner`.
|
|
725
|
+
|
|
726
|
+
#### `ner scan` — secret scanner
|
|
727
|
+
|
|
728
|
+
Scans files for hardcoded secrets (Stripe keys, GitHub tokens, JWTs, DB connection strings, AWS keys, private keys, and more):
|
|
729
|
+
|
|
730
|
+
```bash
|
|
731
|
+
# Scan a directory
|
|
732
|
+
ner scan src/
|
|
733
|
+
|
|
734
|
+
# Scan only git-staged files (ideal for pre-commit hooks)
|
|
735
|
+
ner scan --staged
|
|
736
|
+
|
|
737
|
+
# Show surrounding line context
|
|
738
|
+
ner scan --context src/
|
|
739
|
+
|
|
740
|
+
# Exclude patterns
|
|
741
|
+
ner scan --ignore "fixtures" --ignore "\.test\." src/
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
**Pre-commit hook setup:**
|
|
745
|
+
|
|
746
|
+
```bash
|
|
747
|
+
echo 'ner scan --staged' >> .git/hooks/pre-commit
|
|
748
|
+
chmod +x .git/hooks/pre-commit
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
#### `ner run` — run with resolved env vars
|
|
752
|
+
|
|
753
|
+
Loads a `.env` file, resolves any reference URIs, then spawns your command. No code changes needed in your app.
|
|
754
|
+
|
|
755
|
+
```bash
|
|
756
|
+
# Basic usage
|
|
757
|
+
ner run -- node server.js
|
|
758
|
+
|
|
759
|
+
# Use a different env file
|
|
760
|
+
ner run --env .env.staging -- node deploy.js
|
|
761
|
+
|
|
762
|
+
# Skip reference resolution (equivalent to node --env-file)
|
|
763
|
+
ner run --no-resolve -- node server.js
|
|
764
|
+
|
|
765
|
+
# Warn if .env contains hardcoded secrets before running
|
|
766
|
+
ner run --scan -- node server.js
|
|
767
|
+
```
|
|
768
|
+
|
|
769
|
+
**Reference resolution** — the key differentiator from `node --env-file`:
|
|
770
|
+
|
|
771
|
+
```bash
|
|
772
|
+
# .env
|
|
773
|
+
DATABASE_URL=aws-sm://prod/database-credentials
|
|
774
|
+
API_KEY=aws-ssm://prod/payments/api-key
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
```bash
|
|
778
|
+
# ner run resolves these before process start:
|
|
779
|
+
ner run -- node server.js
|
|
780
|
+
# → DATABASE_URL and API_KEY injected as their real values
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
Requires `node-env-resolver-aws` for `aws-sm://` and `aws-ssm://` support:
|
|
784
|
+
|
|
785
|
+
```bash
|
|
786
|
+
npm install node-env-resolver-aws
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
### Runtime Protection
|
|
790
|
+
|
|
791
|
+
Prevent accidental secret leaks in console output and HTTP responses.
|
|
792
|
+
|
|
793
|
+
#### One-call setup
|
|
697
794
|
|
|
698
795
|
```ts
|
|
699
|
-
import {
|
|
700
|
-
import { processEnv } from 'node-env-resolver/resolvers';
|
|
701
|
-
import { postgres } from 'node-env-resolver/validators';
|
|
702
|
-
import { cliArgs } from 'node-env-resolver/cli';
|
|
796
|
+
import { protect } from 'node-env-resolver/runtime';
|
|
703
797
|
|
|
704
|
-
|
|
798
|
+
const config = resolve({ DATABASE_URL: postgres(), API_KEY: string() });
|
|
705
799
|
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
VERBOSE: false
|
|
712
|
-
}],
|
|
713
|
-
[cliArgs(), {
|
|
714
|
-
PORT: 3000,
|
|
715
|
-
DATABASE_URL: postgres(),
|
|
716
|
-
VERBOSE: false
|
|
717
|
-
}]
|
|
718
|
-
]
|
|
719
|
-
});
|
|
800
|
+
// Patches all console methods to redact secrets automatically
|
|
801
|
+
const unprotect = protect(config);
|
|
802
|
+
|
|
803
|
+
console.log('DB:', config.DATABASE_URL); // DB: [REDACTED]
|
|
804
|
+
console.log('Key:', config.API_KEY); // Key: [REDACTED]
|
|
720
805
|
|
|
721
|
-
//
|
|
722
|
-
|
|
723
|
-
// config.VERBOSE === true (from CLI flag)
|
|
806
|
+
// Restore originals when done (e.g. in tests)
|
|
807
|
+
unprotect();
|
|
724
808
|
```
|
|
725
809
|
|
|
726
|
-
**
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
810
|
+
**Options:**
|
|
811
|
+
|
|
812
|
+
```ts
|
|
813
|
+
protect(config, {
|
|
814
|
+
console: {
|
|
815
|
+
methods: ['log', 'error', 'warn'], // which methods to patch (default: all)
|
|
816
|
+
enabled: true,
|
|
817
|
+
},
|
|
818
|
+
// console: false — disable console patching entirely
|
|
819
|
+
});
|
|
820
|
+
```
|
|
731
821
|
|
|
732
|
-
|
|
822
|
+
#### Response middleware (Express / Connect / Hono)
|
|
733
823
|
|
|
734
|
-
|
|
824
|
+
Intercepts `res.end()` to scan outgoing responses for secret leaks:
|
|
735
825
|
|
|
736
|
-
|
|
826
|
+
```ts
|
|
827
|
+
import { createResponseMiddleware } from 'node-env-resolver/runtime';
|
|
737
828
|
|
|
738
|
-
|
|
829
|
+
app.use(createResponseMiddleware(config, { mode: 'redact' }));
|
|
830
|
+
// mode: 'redact' — replace secrets in response body
|
|
831
|
+
// mode: 'warn' — log a warning, pass body through (default in production)
|
|
832
|
+
// mode: 'throw' — throw on any detected leak (default in development)
|
|
833
|
+
```
|
|
739
834
|
|
|
740
|
-
|
|
835
|
+
#### Edge runtime (Cloudflare Workers, Deno Deploy)
|
|
741
836
|
|
|
742
837
|
```ts
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
schema: {
|
|
750
|
-
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
751
|
-
PORT: number({ default: 3000 }),
|
|
752
|
-
API_KEY: string({ optional: true, sensitive: true }),
|
|
753
|
-
FEATURE_FLAGS: json(), // parsed JSON → unknown
|
|
838
|
+
import { wrapFetchResponse } from 'node-env-resolver/runtime';
|
|
839
|
+
|
|
840
|
+
export default {
|
|
841
|
+
async fetch(request: Request) {
|
|
842
|
+
const response = await handler(request);
|
|
843
|
+
return wrapFetchResponse(response, config, { mode: 'redact' });
|
|
754
844
|
},
|
|
755
|
-
resolvers: [
|
|
756
|
-
[processEnv(), {}],
|
|
757
|
-
[dotenv(), {}],
|
|
758
|
-
],
|
|
759
845
|
};
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
#### Low-level primitives
|
|
849
|
+
|
|
850
|
+
```ts
|
|
851
|
+
import {
|
|
852
|
+
createRedactor,
|
|
853
|
+
extractSensitiveValues,
|
|
854
|
+
createConsoleRedactor,
|
|
855
|
+
scanBodyForSecrets,
|
|
856
|
+
} from 'node-env-resolver/runtime';
|
|
857
|
+
|
|
858
|
+
// Build a redactor from a config object
|
|
859
|
+
const secrets = extractSensitiveValues(config); // Map of sensitive key→value pairs
|
|
860
|
+
const redactor = createRedactor(secrets);
|
|
861
|
+
redactor.redactString('key is sk_live_abc123'); // 'key is [REDACTED]'
|
|
862
|
+
redactor.maskValue('super-secret'); // 'su****et'
|
|
863
|
+
redactor.createFingerprint('secret'); // 'sha256:a1b2c3d4'
|
|
760
864
|
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
- Pretty table (default):
|
|
770
|
-
```bash
|
|
771
|
-
node-env-resolver load
|
|
772
|
-
node-env-resolver load --config ./env.config.mjs
|
|
773
|
-
```
|
|
774
|
-
- JSON output (honours sensitive redaction):
|
|
775
|
-
```bash
|
|
776
|
-
node-env-resolver load --format=json
|
|
777
|
-
node-env-resolver load --format=json --reveal # show secrets in plaintext
|
|
778
|
-
```
|
|
779
|
-
- `.env`-style output (good for scripting):
|
|
780
|
-
```bash
|
|
781
|
-
node-env-resolver load --format=env > .env.local
|
|
782
|
-
```
|
|
783
|
-
|
|
784
|
-
- **`run`** – resolve config and run a child process with injected env:
|
|
785
|
-
```bash
|
|
786
|
-
node-env-resolver run -- npm run migrate
|
|
787
|
-
node-env-resolver run --config ./env.config.mjs -- npm run start
|
|
788
|
-
node-env-resolver run --no-redact -- node scripts/print-env.ts
|
|
789
|
-
```
|
|
790
|
-
|
|
791
|
-
- Merges resolved values on top of `process.env`.
|
|
792
|
-
- By default, stdout/stderr are **redacted** using the same sensitive key detection as the library.
|
|
793
|
-
- Use `--no-redact` to disable stream redaction when you need raw logs.
|
|
794
|
-
|
|
795
|
-
- **`typegen`** – generate `EnvSchema` and `process.env` / `import.meta.env` types:
|
|
796
|
-
```bash
|
|
797
|
-
node-env-resolver typegen --output env.d.ts
|
|
798
|
-
node-env-resolver typegen --config ./env.config.mjs --output ./src/env.d.ts
|
|
799
|
-
```
|
|
800
|
-
|
|
801
|
-
This uses the same generator as `node-env-resolver/typegen`, including:
|
|
802
|
-
- `json()` → `unknown` in `EnvSchema` (parsed JSON)
|
|
803
|
-
- Correct optional flags based on `{ optional: true }`
|
|
804
|
-
- String-oriented types for `process.env`/`import.meta.env` augmentation
|
|
865
|
+
// Scan a response body manually
|
|
866
|
+
const { safe, redacted } = scanBodyForSecrets(body, config);
|
|
867
|
+
|
|
868
|
+
// Custom sensitive key patterns
|
|
869
|
+
const secrets2 = extractSensitiveValues(config, {
|
|
870
|
+
sensitiveKeys: ['MY_PREFIX'],
|
|
871
|
+
});
|
|
872
|
+
```
|
|
805
873
|
|
|
806
874
|
### Computed fields
|
|
807
875
|
|
|
@@ -815,54 +883,55 @@ const config = resolve({
|
|
|
815
883
|
HOST: 'localhost',
|
|
816
884
|
PORT: 3000,
|
|
817
885
|
SSL_ENABLED: false,
|
|
818
|
-
NODE_ENV: ['development', 'production'] as const
|
|
886
|
+
NODE_ENV: ['development', 'production'] as const,
|
|
819
887
|
});
|
|
820
888
|
|
|
821
889
|
// Add computed properties
|
|
822
890
|
const appConfig = withComputed(config, {
|
|
823
891
|
// Build URLs from components
|
|
824
892
|
url: (c) => `${c.SSL_ENABLED ? 'https' : 'http'}://${c.HOST}:${c.PORT}`,
|
|
825
|
-
|
|
893
|
+
|
|
826
894
|
// Environment checks
|
|
827
895
|
isProd: (c) => c.NODE_ENV === 'production',
|
|
828
896
|
isDev: (c) => c.NODE_ENV === 'development',
|
|
829
|
-
|
|
897
|
+
|
|
830
898
|
// Complex derived config
|
|
831
899
|
serverOptions: (c) => ({
|
|
832
900
|
host: c.HOST,
|
|
833
901
|
port: c.PORT,
|
|
834
902
|
cors: c.NODE_ENV !== 'production',
|
|
835
|
-
compression: c.NODE_ENV === 'production'
|
|
836
|
-
})
|
|
903
|
+
compression: c.NODE_ENV === 'production',
|
|
904
|
+
}),
|
|
837
905
|
});
|
|
838
906
|
|
|
839
|
-
console.log(appConfig.url);
|
|
840
|
-
console.log(appConfig.isProd);
|
|
907
|
+
console.log(appConfig.url); // 'http://localhost:3000'
|
|
908
|
+
console.log(appConfig.isProd); // false
|
|
841
909
|
console.log(appConfig.serverOptions); // { host: 'localhost', ... }
|
|
842
910
|
```
|
|
843
911
|
|
|
844
912
|
**Common patterns:**
|
|
913
|
+
|
|
845
914
|
```ts
|
|
846
915
|
// Build database connection URLs
|
|
847
916
|
withComputed(config, {
|
|
848
|
-
databaseUrl: (c) =>
|
|
849
|
-
`postgres://${c.DB_USER}:${c.DB_PASSWORD}@${c.DB_HOST}:${c.DB_PORT}/${c.DB_NAME}
|
|
917
|
+
databaseUrl: (c) =>
|
|
918
|
+
`postgres://${c.DB_USER}:${c.DB_PASSWORD}@${c.DB_HOST}:${c.DB_PORT}/${c.DB_NAME}`,
|
|
850
919
|
});
|
|
851
920
|
|
|
852
921
|
// Derive API endpoints
|
|
853
922
|
withComputed(config, {
|
|
854
923
|
endpoints: (c) => ({
|
|
855
924
|
users: `${c.API_BASE_URL}/${c.API_VERSION}/users`,
|
|
856
|
-
posts: `${c.API_BASE_URL}/${c.API_VERSION}/posts
|
|
857
|
-
})
|
|
925
|
+
posts: `${c.API_BASE_URL}/${c.API_VERSION}/posts`,
|
|
926
|
+
}),
|
|
858
927
|
});
|
|
859
928
|
|
|
860
929
|
// Feature flags based on environment
|
|
861
930
|
withComputed(config, {
|
|
862
931
|
features: (c) => ({
|
|
863
932
|
analytics: c.ENABLE_ANALYTICS && c.NODE_ENV === 'production',
|
|
864
|
-
debug: c.NODE_ENV === 'development'
|
|
865
|
-
})
|
|
933
|
+
debug: c.NODE_ENV === 'development',
|
|
934
|
+
}),
|
|
866
935
|
});
|
|
867
936
|
```
|
|
868
937
|
|
|
@@ -874,7 +943,7 @@ Use Zod schemas for powerful validation:
|
|
|
874
943
|
|
|
875
944
|
```ts
|
|
876
945
|
import { resolveZod } from 'node-env-resolver/zod';
|
|
877
|
-
import * as z from 'zod';
|
|
946
|
+
import * as z from 'zod'; // ✅ Recommended import pattern (better tree-shaking)
|
|
878
947
|
|
|
879
948
|
const schema = z.object({
|
|
880
949
|
PORT: z.coerce.number().default(3000),
|
|
@@ -895,7 +964,7 @@ import * as z from 'zod';
|
|
|
895
964
|
|
|
896
965
|
const schema = z.object({
|
|
897
966
|
PORT: z.coerce.number(),
|
|
898
|
-
DATABASE_URL: z.string().url()
|
|
967
|
+
DATABASE_URL: z.string().url(),
|
|
899
968
|
});
|
|
900
969
|
|
|
901
970
|
const result = await safeResolveZod(schema);
|
|
@@ -903,8 +972,8 @@ const result = await safeResolveZod(schema);
|
|
|
903
972
|
if (result.success) {
|
|
904
973
|
console.log(result.data.PORT);
|
|
905
974
|
} else {
|
|
906
|
-
console.error(result.error);
|
|
907
|
-
result.issues.forEach(issue => {
|
|
975
|
+
console.error(result.error); // Summary message
|
|
976
|
+
result.issues.forEach((issue) => {
|
|
908
977
|
// Field-level details: path, message, code
|
|
909
978
|
console.log(`${issue.path.join('.')}: ${issue.message}`);
|
|
910
979
|
});
|
|
@@ -924,7 +993,7 @@ Use Valibot for lightweight, modular validation:
|
|
|
924
993
|
|
|
925
994
|
```ts
|
|
926
995
|
import { resolveValibot } from 'node-env-resolver/valibot';
|
|
927
|
-
import * as v from 'valibot';
|
|
996
|
+
import * as v from 'valibot'; // User imports valibot separately
|
|
928
997
|
|
|
929
998
|
const schema = v.object({
|
|
930
999
|
PORT: v.pipe(v.string(), v.transform(Number)),
|
|
@@ -944,7 +1013,7 @@ import * as v from 'valibot';
|
|
|
944
1013
|
|
|
945
1014
|
const schema = v.object({
|
|
946
1015
|
PORT: v.pipe(v.string(), v.transform(Number)),
|
|
947
|
-
DATABASE_URL: v.pipe(v.string(), v.url())
|
|
1016
|
+
DATABASE_URL: v.pipe(v.string(), v.url()),
|
|
948
1017
|
});
|
|
949
1018
|
|
|
950
1019
|
const result = await safeResolveValibot(schema);
|
|
@@ -952,8 +1021,8 @@ const result = await safeResolveValibot(schema);
|
|
|
952
1021
|
if (result.success) {
|
|
953
1022
|
console.log(result.data.PORT);
|
|
954
1023
|
} else {
|
|
955
|
-
console.error(result.error);
|
|
956
|
-
result.issues.forEach(issue => {
|
|
1024
|
+
console.error(result.error); // Summary message
|
|
1025
|
+
result.issues.forEach((issue) => {
|
|
957
1026
|
// Same format as Zod - consistent across validators!
|
|
958
1027
|
console.log(`${issue.path.join('.')}: ${issue.message}`);
|
|
959
1028
|
});
|
|
@@ -982,19 +1051,50 @@ const databaseResolver: Resolver = {
|
|
|
982
1051
|
name: 'database',
|
|
983
1052
|
async load() {
|
|
984
1053
|
const rows = await db.query('SELECT key, value FROM config');
|
|
985
|
-
return Object.fromEntries(rows.map(r => [r.key, r.value]));
|
|
986
|
-
}
|
|
1054
|
+
return Object.fromEntries(rows.map((r) => [r.key, r.value]));
|
|
1055
|
+
},
|
|
987
1056
|
};
|
|
988
1057
|
|
|
989
1058
|
const config = await resolveAsync({
|
|
990
1059
|
resolvers: [
|
|
991
1060
|
[processEnv(), { PORT: 3000 }],
|
|
992
|
-
[databaseResolver, { API_KEY: string() }]
|
|
993
|
-
]
|
|
1061
|
+
[databaseResolver, { API_KEY: string() }],
|
|
1062
|
+
],
|
|
994
1063
|
});
|
|
995
1064
|
```
|
|
996
1065
|
|
|
997
|
-
###
|
|
1066
|
+
### Built-in process-env references
|
|
1067
|
+
|
|
1068
|
+
Use `process-env://...` when one config value should resolve from another environment variable.
|
|
1069
|
+
This keeps reference-style config consistent across backends such as `process-env://`, `aws-sm://`, or `vault://`, without requiring a custom handler.
|
|
1070
|
+
`process-env` is built in, so no `references` object is required.
|
|
1071
|
+
|
|
1072
|
+
```ts
|
|
1073
|
+
import { resolve } from 'node-env-resolver';
|
|
1074
|
+
import { string } from 'node-env-resolver/validators';
|
|
1075
|
+
|
|
1076
|
+
process.env.API_KEY = 'real-secret-value';
|
|
1077
|
+
process.env.OPENAI_API_KEY = 'process-env://API_KEY';
|
|
1078
|
+
|
|
1079
|
+
const config = resolve(
|
|
1080
|
+
{
|
|
1081
|
+
OPENAI_API_KEY: string(),
|
|
1082
|
+
},
|
|
1083
|
+
);
|
|
1084
|
+
|
|
1085
|
+
console.log(config.OPENAI_API_KEY); // real-secret-value
|
|
1086
|
+
```
|
|
1087
|
+
|
|
1088
|
+
This keeps `OPENAI_API_KEY` from containing the raw secret directly, but it does not protect secrets from code that can already read `process.env`.
|
|
1089
|
+
For stronger secret isolation, prefer an external secret backend such as AWS Secrets Manager or Vault.
|
|
1090
|
+
|
|
1091
|
+
```env
|
|
1092
|
+
OPENAI_API_KEY=process-env://API_KEY
|
|
1093
|
+
```
|
|
1094
|
+
|
|
1095
|
+
This is useful when you want `OPENAI_API_KEY` to point at `API_KEY` without duplicating the raw value in the config entry.
|
|
1096
|
+
|
|
1097
|
+
### AWS Secrets Manager & SSM
|
|
998
1098
|
|
|
999
1099
|
Install the AWS package:
|
|
1000
1100
|
|
|
@@ -1002,21 +1102,60 @@ Install the AWS package:
|
|
|
1002
1102
|
npm install node-env-resolver-aws
|
|
1003
1103
|
```
|
|
1004
1104
|
|
|
1005
|
-
|
|
1105
|
+
#### Reference URIs (recommended)
|
|
1106
|
+
|
|
1107
|
+
Store references in your `.env` and resolve at startup — no AWS SDK imports needed in app code:
|
|
1108
|
+
|
|
1109
|
+
```bash
|
|
1110
|
+
# .env
|
|
1111
|
+
DATABASE_URL=aws-sm://prod/database-credentials
|
|
1112
|
+
DB_PASSWORD=aws-sm://prod/database#password # extract a JSON key
|
|
1113
|
+
API_KEY=aws-ssm://prod/payments/api-key
|
|
1114
|
+
```
|
|
1006
1115
|
|
|
1007
1116
|
```ts
|
|
1008
|
-
import {
|
|
1117
|
+
import { resolveAsync } from 'node-env-resolver';
|
|
1118
|
+
import { dotenv } from 'node-env-resolver/resolvers';
|
|
1009
1119
|
import { postgres, string } from 'node-env-resolver/validators';
|
|
1120
|
+
import {
|
|
1121
|
+
createAwsSecretHandler,
|
|
1122
|
+
createAwsSsmHandler,
|
|
1123
|
+
} from 'node-env-resolver-aws';
|
|
1010
1124
|
|
|
1011
|
-
const config = await
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1125
|
+
const config = await resolveAsync({
|
|
1126
|
+
resolvers: [
|
|
1127
|
+
[
|
|
1128
|
+
dotenv(),
|
|
1129
|
+
{ DATABASE_URL: postgres(), DB_PASSWORD: string(), API_KEY: string() },
|
|
1130
|
+
],
|
|
1131
|
+
],
|
|
1132
|
+
references: {
|
|
1133
|
+
handlers: {
|
|
1134
|
+
'aws-sm': createAwsSecretHandler({ region: 'us-east-1' }),
|
|
1135
|
+
'aws-ssm': createAwsSsmHandler({ region: 'us-east-1' }),
|
|
1136
|
+
},
|
|
1137
|
+
},
|
|
1138
|
+
});
|
|
1139
|
+
```
|
|
1140
|
+
|
|
1141
|
+
Or use the pre-configured singletons (picks up `AWS_REGION` from environment):
|
|
1142
|
+
|
|
1143
|
+
```ts
|
|
1144
|
+
import { awsSecretHandler, awsSsmHandler } from 'node-env-resolver-aws';
|
|
1145
|
+
|
|
1146
|
+
const config = await resolveAsync({
|
|
1147
|
+
resolvers: [[dotenv(), schema]],
|
|
1148
|
+
references: {
|
|
1149
|
+
handlers: { 'aws-sm': awsSecretHandler, 'aws-ssm': awsSsmHandler },
|
|
1150
|
+
},
|
|
1016
1151
|
});
|
|
1017
1152
|
```
|
|
1018
1153
|
|
|
1019
|
-
|
|
1154
|
+
Each `createAwsSecretHandler()` / `createAwsSsmHandler()` call creates its own SDK client, so multi-region setups work correctly without interference.
|
|
1155
|
+
|
|
1156
|
+
#### Resolver pattern (bulk load)
|
|
1157
|
+
|
|
1158
|
+
Loads all keys from a secret or parameter path as a resolver:
|
|
1020
1159
|
|
|
1021
1160
|
```ts
|
|
1022
1161
|
import { resolveAsync } from 'node-env-resolver';
|
|
@@ -1028,12 +1167,12 @@ const config = await resolveAsync({
|
|
|
1028
1167
|
resolvers: [
|
|
1029
1168
|
[processEnv(), { PORT: 3000 }],
|
|
1030
1169
|
[awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: postgres() }],
|
|
1031
|
-
[awsSsm({ path: '/app/config' }), { API_KEY: string() }]
|
|
1032
|
-
]
|
|
1170
|
+
[awsSsm({ path: '/app/config' }), { API_KEY: string() }],
|
|
1171
|
+
],
|
|
1033
1172
|
});
|
|
1034
1173
|
```
|
|
1035
1174
|
|
|
1036
|
-
See the [AWS package documentation](../node-env-resolver-aws/README.md) for
|
|
1175
|
+
See the [AWS package documentation](../node-env-resolver-aws/README.md) for credentials, caching, and best practices.
|
|
1037
1176
|
|
|
1038
1177
|
### TTL caching
|
|
1039
1178
|
|
|
@@ -1048,14 +1187,14 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1048
1187
|
export const getConfig = async () => {
|
|
1049
1188
|
return await resolveAsync({
|
|
1050
1189
|
resolvers: [
|
|
1051
|
-
[
|
|
1052
|
-
awsSecrets({ secretId: 'app/secrets' }),
|
|
1053
|
-
{
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
]
|
|
1190
|
+
[
|
|
1191
|
+
cached(awsSecrets({ secretId: 'app/secrets' }), { ttl: TTL.minutes5 }),
|
|
1192
|
+
{
|
|
1193
|
+
DATABASE_URL: postgres(),
|
|
1194
|
+
API_KEY: string(),
|
|
1195
|
+
},
|
|
1196
|
+
],
|
|
1197
|
+
],
|
|
1059
1198
|
});
|
|
1060
1199
|
};
|
|
1061
1200
|
|
|
@@ -1073,6 +1212,60 @@ Performance:
|
|
|
1073
1212
|
|
|
1074
1213
|
**Important:** Call `resolve()` every time. The `cached()` wrapper handles the caching.
|
|
1075
1214
|
|
|
1215
|
+
### Polling remote config
|
|
1216
|
+
|
|
1217
|
+
Use `poll()` when you need to observe changes over time, such as re-reading AWS Secrets Manager on a schedule.
|
|
1218
|
+
It is polling, not push-based events, so it fits cases where you want periodic refresh and change detection.
|
|
1219
|
+
|
|
1220
|
+
```ts
|
|
1221
|
+
import { resolveAsync } from 'node-env-resolver';
|
|
1222
|
+
import { cached, poll } from 'node-env-resolver/utils';
|
|
1223
|
+
import { postgres, string } from 'node-env-resolver/validators';
|
|
1224
|
+
import { awsSecrets } from 'node-env-resolver-aws';
|
|
1225
|
+
|
|
1226
|
+
export const getConfig = async () => {
|
|
1227
|
+
return resolveAsync({
|
|
1228
|
+
resolvers: [
|
|
1229
|
+
[
|
|
1230
|
+
cached(awsSecrets({ secretId: 'app/secrets' }), { ttl: 10_000 }),
|
|
1231
|
+
{
|
|
1232
|
+
DATABASE_URL: postgres(),
|
|
1233
|
+
API_KEY: string(),
|
|
1234
|
+
},
|
|
1235
|
+
],
|
|
1236
|
+
],
|
|
1237
|
+
});
|
|
1238
|
+
};
|
|
1239
|
+
|
|
1240
|
+
const watcher = poll(getConfig, {
|
|
1241
|
+
intervalMs: 10_000,
|
|
1242
|
+
onChange: (next, previous) => {
|
|
1243
|
+
console.log('Config updated', { previous, next });
|
|
1244
|
+
},
|
|
1245
|
+
onError: (error) => {
|
|
1246
|
+
console.error('Polling failed', error);
|
|
1247
|
+
},
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
// Read the last loaded value whenever you need it.
|
|
1251
|
+
console.log(watcher.getCurrent());
|
|
1252
|
+
|
|
1253
|
+
// Stop polling during shutdown.
|
|
1254
|
+
process.on('SIGINT', () => watcher.stop());
|
|
1255
|
+
```
|
|
1256
|
+
|
|
1257
|
+
**When to use this:**
|
|
1258
|
+
|
|
1259
|
+
- You need to detect config changes without restarting the process
|
|
1260
|
+
- You want a small, explicit polling loop instead of an event system
|
|
1261
|
+
- You are reading from a remote source that changes on a schedule
|
|
1262
|
+
|
|
1263
|
+
**When not to use this:**
|
|
1264
|
+
|
|
1265
|
+
- You only need startup-time validation
|
|
1266
|
+
- You want push notifications from a backend that already supports events
|
|
1267
|
+
- You are on the Next.js config path, which must stay synchronous
|
|
1268
|
+
|
|
1076
1269
|
**Advanced caching options:**
|
|
1077
1270
|
|
|
1078
1271
|
```ts
|
|
@@ -1080,15 +1273,15 @@ import { cached, TTL } from 'node-env-resolver/utils';
|
|
|
1080
1273
|
|
|
1081
1274
|
// Stale-while-revalidate: serve stale data while refreshing in background
|
|
1082
1275
|
const resolver = cached(awsSecrets(), {
|
|
1083
|
-
ttl: TTL.minutes5,
|
|
1084
|
-
maxAge: TTL.hour,
|
|
1085
|
-
staleWhileRevalidate: true
|
|
1276
|
+
ttl: TTL.minutes5, // Fresh for 5 minutes
|
|
1277
|
+
maxAge: TTL.hour, // Force refresh after 1 hour
|
|
1278
|
+
staleWhileRevalidate: true, // Serve stale data during refresh
|
|
1086
1279
|
});
|
|
1087
1280
|
|
|
1088
1281
|
// Custom cache key for debugging
|
|
1089
1282
|
const resolver = cached(awsSecrets(), {
|
|
1090
1283
|
ttl: TTL.minutes15,
|
|
1091
|
-
key: 'prod-secrets-v2'
|
|
1284
|
+
key: 'prod-secrets-v2',
|
|
1092
1285
|
});
|
|
1093
1286
|
```
|
|
1094
1287
|
|
|
@@ -1096,12 +1289,12 @@ const resolver = cached(awsSecrets(), {
|
|
|
1096
1289
|
|
|
1097
1290
|
### Function variants
|
|
1098
1291
|
|
|
1099
|
-
| Function
|
|
1100
|
-
|
|
1101
|
-
| `resolve()`
|
|
1102
|
-
| `safeResolve()`
|
|
1103
|
-
| `resolveAsync()`
|
|
1104
|
-
| `safeResolveAsync()` | Async, returns result object | Multiple sources with error handling
|
|
1292
|
+
| Function | Behaviour | Use case |
|
|
1293
|
+
| -------------------- | ---------------------------- | -------------------------------------------- |
|
|
1294
|
+
| `resolve()` | Sync, throws on error | Most applications (reading from process.env) |
|
|
1295
|
+
| `safeResolve()` | Sync, returns result object | Graceful error handling |
|
|
1296
|
+
| `resolveAsync()` | Async, throws on error | Multiple sources (dotenv, AWS, etc.) |
|
|
1297
|
+
| `safeResolveAsync()` | Async, returns result object | Multiple sources with error handling |
|
|
1105
1298
|
|
|
1106
1299
|
### Resolver API Reference
|
|
1107
1300
|
|
|
@@ -1109,44 +1302,58 @@ Import resolver functions from `'node-env-resolver/resolvers'`:
|
|
|
1109
1302
|
|
|
1110
1303
|
```ts
|
|
1111
1304
|
import {
|
|
1112
|
-
string,
|
|
1113
|
-
|
|
1114
|
-
|
|
1305
|
+
string,
|
|
1306
|
+
number,
|
|
1307
|
+
boolean,
|
|
1308
|
+
url,
|
|
1309
|
+
email,
|
|
1310
|
+
port,
|
|
1311
|
+
json,
|
|
1312
|
+
postgres,
|
|
1313
|
+
mysql,
|
|
1314
|
+
mongodb,
|
|
1315
|
+
redis,
|
|
1316
|
+
http,
|
|
1317
|
+
https,
|
|
1318
|
+
date,
|
|
1319
|
+
timestamp,
|
|
1320
|
+
duration,
|
|
1321
|
+
file,
|
|
1115
1322
|
} from 'node-env-resolver/validators';
|
|
1116
1323
|
```
|
|
1117
1324
|
|
|
1118
|
-
| Syntax
|
|
1119
|
-
|
|
1120
|
-
| `string()`
|
|
1121
|
-
| `string({optional: true})`
|
|
1122
|
-
| `number()`
|
|
1123
|
-
| `number({optional: true})`
|
|
1124
|
-
| `boolean()`
|
|
1125
|
-
| `boolean({optional: true})`
|
|
1126
|
-
| `url()`
|
|
1127
|
-
| `url({optional: true})`
|
|
1128
|
-
| `email()`
|
|
1129
|
-
| `port()`
|
|
1130
|
-
| `json()`
|
|
1131
|
-
| `postgres()` or `postgresql()`
|
|
1132
|
-
| `mysql()`
|
|
1133
|
-
| `mongodb()`
|
|
1134
|
-
| `redis()`
|
|
1135
|
-
| `http()`
|
|
1136
|
-
| `https()`
|
|
1137
|
-
| `date()`
|
|
1138
|
-
| `timestamp()`
|
|
1139
|
-
| `duration()`
|
|
1140
|
-
| `file()`
|
|
1141
|
-
| `3000`
|
|
1142
|
-
| `false`
|
|
1143
|
-
| `'defaultValue'`
|
|
1144
|
-
| `['a', 'b'] as const`
|
|
1145
|
-
| `optional(['a', 'b'] as const)`
|
|
1146
|
-
| `enumOf(['a', 'b'] as const)`
|
|
1147
|
-
| `enumOf(['a', 'b'] as const, {optional: true})` | `'a' \| 'b' \| undefined` | Optional enum (explicit function)
|
|
1148
|
-
| `enumOf(['a', 'b'] as const, {default: 'a'})`
|
|
1149
|
-
| `oneOf(['a', 'b'] as const)`
|
|
1325
|
+
| Syntax | Type | Description |
|
|
1326
|
+
| ----------------------------------------------- | ------------------------- | --------------------------------------------------- |
|
|
1327
|
+
| `string()` | `string` | Required string (empty strings rejected by default) |
|
|
1328
|
+
| `string({optional: true})` | `string \| undefined` | Optional string |
|
|
1329
|
+
| `number()` | `number` | Required number (coerced from string) |
|
|
1330
|
+
| `number({optional: true})` | `number \| undefined` | Optional number |
|
|
1331
|
+
| `boolean()` | `boolean` | Required boolean (coerced from string) |
|
|
1332
|
+
| `boolean({optional: true})` | `boolean \| undefined` | Optional boolean |
|
|
1333
|
+
| `url()` | `string` | Validated URL (returns string) |
|
|
1334
|
+
| `url({optional: true})` | `string \| undefined` | Optional URL |
|
|
1335
|
+
| `email()` | `string` | Validated email address |
|
|
1336
|
+
| `port()` | `number` | Validated port number (1-65535) |
|
|
1337
|
+
| `json()` | `unknown` | Parsed JSON (returns object/array) |
|
|
1338
|
+
| `postgres()` or `postgresql()` | `string` | Validated PostgreSQL URL |
|
|
1339
|
+
| `mysql()` | `string` | Validated MySQL connection string |
|
|
1340
|
+
| `mongodb()` | `string` | Validated MongoDB connection string |
|
|
1341
|
+
| `redis()` | `string` | Validated Redis connection string |
|
|
1342
|
+
| `http()` | `string` | HTTP or HTTPS URL |
|
|
1343
|
+
| `https()` | `string` | HTTPS-only URL |
|
|
1344
|
+
| `date()` | `string` | Validated ISO 8601 date |
|
|
1345
|
+
| `timestamp()` | `number` | Validated Unix timestamp |
|
|
1346
|
+
| `duration()` | `number` | Time duration (`5s`, `2m`, `1h` → milliseconds) |
|
|
1347
|
+
| `file()` | `string` | Read content from file path |
|
|
1348
|
+
| `3000` | `number` | Number with default value |
|
|
1349
|
+
| `false` | `boolean` | Boolean with default value |
|
|
1350
|
+
| `'defaultValue'` | `string` | String with default value |
|
|
1351
|
+
| `['a', 'b'] as const` | `'a' \| 'b'` | Required enum (requires `as const`) |
|
|
1352
|
+
| `optional(['a', 'b'] as const)` | `'a' \| 'b' \| undefined` | Optional enum (clean syntax) |
|
|
1353
|
+
| `enumOf(['a', 'b'] as const)` | `'a' \| 'b'` | Required enum (explicit function) |
|
|
1354
|
+
| `enumOf(['a', 'b'] as const, {optional: true})` | `'a' \| 'b' \| undefined` | Optional enum (explicit function) |
|
|
1355
|
+
| `enumOf(['a', 'b'] as const, {default: 'a'})` | `'a' \| 'b'` | Enum with default value |
|
|
1356
|
+
| `oneOf(['a', 'b'] as const)` | `'a' \| 'b'` | Alias for enumOf (backward compatible) |
|
|
1150
1357
|
|
|
1151
1358
|
## Configuration Options
|
|
1152
1359
|
|
|
@@ -1197,12 +1404,15 @@ import { url } from 'node-env-resolver/validators';
|
|
|
1197
1404
|
process.env.BASE_URL = 'https://api.example.com';
|
|
1198
1405
|
process.env.API_ENDPOINT = '${BASE_URL}/v1';
|
|
1199
1406
|
|
|
1200
|
-
const config = resolve(
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1407
|
+
const config = resolve(
|
|
1408
|
+
{
|
|
1409
|
+
BASE_URL: url(),
|
|
1410
|
+
API_ENDPOINT: url(),
|
|
1411
|
+
},
|
|
1412
|
+
{
|
|
1413
|
+
interpolate: true,
|
|
1414
|
+
},
|
|
1415
|
+
);
|
|
1206
1416
|
|
|
1207
1417
|
// config.API_ENDPOINT === 'https://api.example.com/v1'
|
|
1208
1418
|
```
|
|
@@ -1228,25 +1438,25 @@ const flakyResolver = {
|
|
|
1228
1438
|
name: 'external-api',
|
|
1229
1439
|
async load() {
|
|
1230
1440
|
throw new Error('Service unavailable');
|
|
1231
|
-
}
|
|
1441
|
+
},
|
|
1232
1442
|
};
|
|
1233
1443
|
|
|
1234
1444
|
// ❌ Throws immediately
|
|
1235
1445
|
await resolveAsync({
|
|
1236
1446
|
resolvers: [
|
|
1237
1447
|
[flakyResolver, schema],
|
|
1238
|
-
[processEnv(), schema]
|
|
1448
|
+
[processEnv(), schema],
|
|
1239
1449
|
],
|
|
1240
|
-
options: { strict: true }
|
|
1450
|
+
options: { strict: true }, // default
|
|
1241
1451
|
});
|
|
1242
1452
|
|
|
1243
1453
|
// ✅ Continues with processEnv()
|
|
1244
1454
|
await resolveAsync({
|
|
1245
1455
|
resolvers: [
|
|
1246
1456
|
[flakyResolver, schema],
|
|
1247
|
-
[processEnv(), schema]
|
|
1457
|
+
[processEnv(), schema],
|
|
1248
1458
|
],
|
|
1249
|
-
options: { strict: false }
|
|
1459
|
+
options: { strict: false }, // graceful degradation
|
|
1250
1460
|
});
|
|
1251
1461
|
```
|
|
1252
1462
|
|
|
@@ -1275,8 +1485,8 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1275
1485
|
await resolveAsync({
|
|
1276
1486
|
resolvers: [
|
|
1277
1487
|
[processEnv(), { DATABASE_URL: postgres() }],
|
|
1278
|
-
[awsSecrets(), { DATABASE_URL: postgres() }]
|
|
1279
|
-
]
|
|
1488
|
+
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
1489
|
+
],
|
|
1280
1490
|
// priority: 'last' (default) - AWS wins
|
|
1281
1491
|
});
|
|
1282
1492
|
|
|
@@ -1284,9 +1494,9 @@ await resolveAsync({
|
|
|
1284
1494
|
await resolveAsync({
|
|
1285
1495
|
resolvers: [
|
|
1286
1496
|
[dotenv(), { DATABASE_URL: postgres() }],
|
|
1287
|
-
[awsSecrets(), { DATABASE_URL: postgres() }]
|
|
1497
|
+
[awsSecrets(), { DATABASE_URL: postgres() }],
|
|
1288
1498
|
],
|
|
1289
|
-
options: { priority: 'first' }
|
|
1499
|
+
options: { priority: 'first' }, // dotenv wins
|
|
1290
1500
|
});
|
|
1291
1501
|
```
|
|
1292
1502
|
|
|
@@ -1306,7 +1516,7 @@ await resolveAsync({
|
|
|
1306
1516
|
await resolveAsync({
|
|
1307
1517
|
resolvers: [
|
|
1308
1518
|
[processEnv(), schema],
|
|
1309
|
-
[awsSecrets(), schema]
|
|
1519
|
+
[awsSecrets(), schema],
|
|
1310
1520
|
],
|
|
1311
1521
|
options: {
|
|
1312
1522
|
policies: {
|
|
@@ -1316,10 +1526,10 @@ await resolveAsync({
|
|
|
1316
1526
|
// Force secrets to come from AWS
|
|
1317
1527
|
enforceAllowedSources: {
|
|
1318
1528
|
DATABASE_PASSWORD: ['aws-secrets'],
|
|
1319
|
-
API_KEY: ['aws-secrets']
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1529
|
+
API_KEY: ['aws-secrets'],
|
|
1530
|
+
},
|
|
1531
|
+
},
|
|
1532
|
+
},
|
|
1323
1533
|
});
|
|
1324
1534
|
```
|
|
1325
1535
|
|
|
@@ -1343,9 +1553,9 @@ await resolveAsync({
|
|
|
1343
1553
|
await resolveAsync({
|
|
1344
1554
|
resolvers: [
|
|
1345
1555
|
[processEnv(), schema],
|
|
1346
|
-
[awsSecrets(), schema]
|
|
1556
|
+
[awsSecrets(), schema],
|
|
1347
1557
|
],
|
|
1348
|
-
options: { enableAudit: true }
|
|
1558
|
+
options: { enableAudit: true }, // Explicitly enable in development
|
|
1349
1559
|
});
|
|
1350
1560
|
|
|
1351
1561
|
const logs = getAuditLog();
|
|
@@ -1361,17 +1571,18 @@ const logs = getAuditLog();
|
|
|
1361
1571
|
|
|
1362
1572
|
```ts
|
|
1363
1573
|
interface ResolveOptions {
|
|
1364
|
-
interpolate?: boolean;
|
|
1365
|
-
strict?: boolean;
|
|
1366
|
-
priority?: 'first' | 'last';
|
|
1367
|
-
policies?: PolicyOptions;
|
|
1368
|
-
enableAudit?: boolean;
|
|
1369
|
-
secretsDir?: string;
|
|
1574
|
+
interpolate?: boolean; // Variable interpolation (default: true in .async())
|
|
1575
|
+
strict?: boolean; // Fail-fast behaviour (default: true)
|
|
1576
|
+
priority?: 'first' | 'last'; // Merge strategy (default: 'last')
|
|
1577
|
+
policies?: PolicyOptions; // Security policies (default: undefined)
|
|
1578
|
+
enableAudit?: boolean; // Audit logging (default: auto in production)
|
|
1579
|
+
secretsDir?: string; // Base directory for file secrets (Docker/K8s)
|
|
1580
|
+
preventProcessEnvWrite?: boolean; // Keep resolved values out of process.env (default: true)
|
|
1370
1581
|
}
|
|
1371
1582
|
|
|
1372
1583
|
interface PolicyOptions {
|
|
1373
|
-
allowDotenvInProduction?: boolean | string[];
|
|
1374
|
-
enforceAllowedSources?: Record<string, string[]>;
|
|
1584
|
+
allowDotenvInProduction?: boolean | string[]; // .env in production control
|
|
1585
|
+
enforceAllowedSources?: Record<string, string[]>; // Source restrictions
|
|
1375
1586
|
}
|
|
1376
1587
|
```
|
|
1377
1588
|
|
|
@@ -1387,7 +1598,7 @@ import { postgres, string } from 'node-env-resolver/validators';
|
|
|
1387
1598
|
const config = resolve({
|
|
1388
1599
|
PORT: 3000,
|
|
1389
1600
|
DATABASE_URL: postgres(),
|
|
1390
|
-
SESSION_SECRET: string()
|
|
1601
|
+
SESSION_SECRET: string(),
|
|
1391
1602
|
});
|
|
1392
1603
|
|
|
1393
1604
|
const app = express();
|
|
@@ -1408,7 +1619,7 @@ export const env = resolve({
|
|
|
1408
1619
|
},
|
|
1409
1620
|
client: {
|
|
1410
1621
|
NEXT_PUBLIC_APP_URL: url(),
|
|
1411
|
-
}
|
|
1622
|
+
},
|
|
1412
1623
|
});
|
|
1413
1624
|
```
|
|
1414
1625
|
|
|
@@ -1423,13 +1634,15 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1423
1634
|
const getConfig = async () => {
|
|
1424
1635
|
return await resolveAsync({
|
|
1425
1636
|
resolvers: [
|
|
1426
|
-
[
|
|
1427
|
-
awsSecrets({ secretId: 'lambda/config' }),
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1637
|
+
[
|
|
1638
|
+
cached(awsSecrets({ secretId: 'lambda/config' }), {
|
|
1639
|
+
ttl: TTL.minutes5,
|
|
1640
|
+
}),
|
|
1641
|
+
{
|
|
1642
|
+
DATABASE_URL: postgres(),
|
|
1643
|
+
},
|
|
1644
|
+
],
|
|
1645
|
+
],
|
|
1433
1646
|
});
|
|
1434
1647
|
};
|
|
1435
1648
|
|
|
@@ -1457,10 +1670,13 @@ import { postgres } from 'node-env-resolver/validators';
|
|
|
1457
1670
|
// In production (NODE_ENV=production)
|
|
1458
1671
|
const config = await resolveAsync({
|
|
1459
1672
|
resolvers: [
|
|
1460
|
-
[
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1673
|
+
[
|
|
1674
|
+
dotenv(),
|
|
1675
|
+
{
|
|
1676
|
+
DATABASE_URL: postgres(),
|
|
1677
|
+
},
|
|
1678
|
+
],
|
|
1679
|
+
],
|
|
1464
1680
|
});
|
|
1465
1681
|
// ❌ Throws: "DATABASE_URL cannot be sourced from .env files in production"
|
|
1466
1682
|
```
|
|
@@ -1474,15 +1690,18 @@ import { postgres } from 'node-env-resolver/validators';
|
|
|
1474
1690
|
|
|
1475
1691
|
const config = await resolveAsync({
|
|
1476
1692
|
resolvers: [
|
|
1477
|
-
[
|
|
1478
|
-
|
|
1479
|
-
|
|
1693
|
+
[
|
|
1694
|
+
dotenv(),
|
|
1695
|
+
{
|
|
1696
|
+
DATABASE_URL: postgres(),
|
|
1697
|
+
},
|
|
1698
|
+
],
|
|
1480
1699
|
],
|
|
1481
1700
|
options: {
|
|
1482
1701
|
policies: {
|
|
1483
|
-
allowDotenvInProduction: true
|
|
1484
|
-
}
|
|
1485
|
-
}
|
|
1702
|
+
allowDotenvInProduction: true, // Allow all (risky!)
|
|
1703
|
+
},
|
|
1704
|
+
},
|
|
1486
1705
|
});
|
|
1487
1706
|
```
|
|
1488
1707
|
|
|
@@ -1495,17 +1714,20 @@ import { postgres } from 'node-env-resolver/validators';
|
|
|
1495
1714
|
|
|
1496
1715
|
const config = await resolveAsync({
|
|
1497
1716
|
resolvers: [
|
|
1498
|
-
[
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1717
|
+
[
|
|
1718
|
+
dotenv(),
|
|
1719
|
+
{
|
|
1720
|
+
PORT: 3000,
|
|
1721
|
+
DATABASE_URL: postgres(),
|
|
1722
|
+
},
|
|
1723
|
+
],
|
|
1502
1724
|
],
|
|
1503
1725
|
options: {
|
|
1504
1726
|
policies: {
|
|
1505
|
-
allowDotenvInProduction: ['PORT']
|
|
1727
|
+
allowDotenvInProduction: ['PORT'], // Only PORT allowed from .env
|
|
1506
1728
|
// DATABASE_URL must come from process.env or cloud resolvers
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1729
|
+
},
|
|
1730
|
+
},
|
|
1509
1731
|
});
|
|
1510
1732
|
```
|
|
1511
1733
|
|
|
@@ -1521,23 +1743,29 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1521
1743
|
|
|
1522
1744
|
const config = await resolveAsync({
|
|
1523
1745
|
resolvers: [
|
|
1524
|
-
[
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1746
|
+
[
|
|
1747
|
+
processEnv(),
|
|
1748
|
+
{
|
|
1749
|
+
PORT: 3000,
|
|
1750
|
+
},
|
|
1751
|
+
],
|
|
1752
|
+
[
|
|
1753
|
+
awsSecrets({ secretId: 'prod/secrets' }),
|
|
1754
|
+
{
|
|
1755
|
+
DATABASE_PASSWORD: string(),
|
|
1756
|
+
API_KEY: string(),
|
|
1757
|
+
},
|
|
1758
|
+
],
|
|
1531
1759
|
],
|
|
1532
1760
|
options: {
|
|
1533
1761
|
policies: {
|
|
1534
1762
|
enforceAllowedSources: {
|
|
1535
|
-
DATABASE_PASSWORD: ['aws-secrets'],
|
|
1536
|
-
API_KEY: ['aws-secrets']
|
|
1763
|
+
DATABASE_PASSWORD: ['aws-secrets'], // Must come from AWS
|
|
1764
|
+
API_KEY: ['aws-secrets'], // Must come from AWS
|
|
1537
1765
|
// PORT not restricted - can come from any resolver
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1766
|
+
},
|
|
1767
|
+
},
|
|
1768
|
+
},
|
|
1541
1769
|
});
|
|
1542
1770
|
```
|
|
1543
1771
|
|
|
@@ -1552,19 +1780,22 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1552
1780
|
const config = await resolveAsync({
|
|
1553
1781
|
resolvers: [
|
|
1554
1782
|
[processEnv(), {}],
|
|
1555
|
-
[
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1783
|
+
[
|
|
1784
|
+
awsSecrets({ secretId: 'prod/db' }),
|
|
1785
|
+
{
|
|
1786
|
+
DATABASE_PASSWORD: string(),
|
|
1787
|
+
STRIPE_SECRET: string(),
|
|
1788
|
+
},
|
|
1789
|
+
],
|
|
1559
1790
|
],
|
|
1560
1791
|
options: {
|
|
1561
1792
|
policies: {
|
|
1562
1793
|
enforceAllowedSources: {
|
|
1563
1794
|
DATABASE_PASSWORD: ['aws-secrets'],
|
|
1564
|
-
STRIPE_SECRET: ['aws-secrets']
|
|
1565
|
-
}
|
|
1566
|
-
}
|
|
1567
|
-
}
|
|
1795
|
+
STRIPE_SECRET: ['aws-secrets'],
|
|
1796
|
+
},
|
|
1797
|
+
},
|
|
1798
|
+
},
|
|
1568
1799
|
});
|
|
1569
1800
|
|
|
1570
1801
|
// ✅ If secrets come from AWS → Success
|
|
@@ -1583,16 +1814,66 @@ interface PolicyOptions {
|
|
|
1583
1814
|
* - string[]: Allow only specific vars from .env in production
|
|
1584
1815
|
*/
|
|
1585
1816
|
allowDotenvInProduction?: boolean | string[];
|
|
1586
|
-
|
|
1817
|
+
|
|
1587
1818
|
/**
|
|
1588
1819
|
* Restrict variables to specific resolvers.
|
|
1589
|
-
*
|
|
1820
|
+
*
|
|
1590
1821
|
* Example: { DATABASE_PASSWORD: ['aws-secrets'] }
|
|
1591
1822
|
*/
|
|
1592
1823
|
enforceAllowedSources?: Record<string, string[]>;
|
|
1593
1824
|
}
|
|
1594
1825
|
```
|
|
1595
1826
|
|
|
1827
|
+
### Reference-first hardening preset
|
|
1828
|
+
|
|
1829
|
+
For incident response hardening, keep secret *values* out of Vercel env vars.
|
|
1830
|
+
Store references such as `aws-sm://prod/stripe-key` and resolve the value at
|
|
1831
|
+
runtime via reference handlers.
|
|
1832
|
+
|
|
1833
|
+
```ts
|
|
1834
|
+
import { resolveAsync, strictReferenceResolveOptions } from 'node-env-resolver';
|
|
1835
|
+
import { processEnv } from 'node-env-resolver/resolvers';
|
|
1836
|
+
import { string } from 'node-env-resolver/validators';
|
|
1837
|
+
import { createAwsSecretHandler } from 'node-env-resolver-aws';
|
|
1838
|
+
|
|
1839
|
+
const config = await resolveAsync({
|
|
1840
|
+
resolvers: [[processEnv(), { STRIPE_KEY: string() }]],
|
|
1841
|
+
references: {
|
|
1842
|
+
handlers: {
|
|
1843
|
+
'aws-sm': createAwsSecretHandler({ region: 'us-east-1' }),
|
|
1844
|
+
},
|
|
1845
|
+
},
|
|
1846
|
+
options: strictReferenceResolveOptions({
|
|
1847
|
+
sensitiveKeys: ['STRIPE_KEY'],
|
|
1848
|
+
secretSources: ['aws-secrets'],
|
|
1849
|
+
}),
|
|
1850
|
+
});
|
|
1851
|
+
```
|
|
1852
|
+
|
|
1853
|
+
What this enforces:
|
|
1854
|
+
|
|
1855
|
+
- `allowDotenvInProduction: false` (secure default)
|
|
1856
|
+
- `enforceAllowedSources` for sensitive keys (prevents accidental fallback)
|
|
1857
|
+
- `enableAudit: true` for source reconstruction via `getAuditLog()`
|
|
1858
|
+
|
|
1859
|
+
If you only want policies (not full resolve options), use:
|
|
1860
|
+
|
|
1861
|
+
```ts
|
|
1862
|
+
import { strictReferencePolicies } from 'node-env-resolver';
|
|
1863
|
+
|
|
1864
|
+
const policies = strictReferencePolicies({
|
|
1865
|
+
sensitiveKeys: ['STRIPE_KEY', 'DATABASE_URL'],
|
|
1866
|
+
secretSources: ['aws-secrets'],
|
|
1867
|
+
});
|
|
1868
|
+
```
|
|
1869
|
+
|
|
1870
|
+
Note on `process.env` mutation:
|
|
1871
|
+
|
|
1872
|
+
- `resolve()` / `resolveAsync()` keep resolved values out of `process.env` by default (`preventProcessEnvWrite: true`).
|
|
1873
|
+
- Resolved values live in the returned typed config object unless your app
|
|
1874
|
+
explicitly re-exports or assigns them.
|
|
1875
|
+
- If you explicitly set `preventProcessEnvWrite: false`, primitive resolved values are written to `process.env`.
|
|
1876
|
+
|
|
1596
1877
|
## Audit Logging
|
|
1597
1878
|
|
|
1598
1879
|
Track environment variable resolution for security and compliance monitoring.
|
|
@@ -1608,12 +1889,15 @@ import { resolve, getAuditLog, clearAuditLog } from 'node-env-resolver';
|
|
|
1608
1889
|
import { postgres, string } from 'node-env-resolver/validators';
|
|
1609
1890
|
|
|
1610
1891
|
// Option 1: Explicitly enable (works in any environment)
|
|
1611
|
-
const config = resolve(
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1892
|
+
const config = resolve(
|
|
1893
|
+
{
|
|
1894
|
+
DATABASE_URL: postgres(),
|
|
1895
|
+
API_KEY: string(),
|
|
1896
|
+
},
|
|
1897
|
+
{
|
|
1898
|
+
enableAudit: true, // ← Enable audit logging
|
|
1899
|
+
},
|
|
1900
|
+
);
|
|
1617
1901
|
|
|
1618
1902
|
console.log(getAuditLog());
|
|
1619
1903
|
// [
|
|
@@ -1649,22 +1933,28 @@ When you have multiple `resolve()` calls, you can now get audit logs **specific
|
|
|
1649
1933
|
import { resolve, getAuditLog } from 'node-env-resolver';
|
|
1650
1934
|
import { string, postgres } from 'node-env-resolver/validators';
|
|
1651
1935
|
|
|
1652
|
-
const appConfig = resolve(
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1936
|
+
const appConfig = resolve(
|
|
1937
|
+
{
|
|
1938
|
+
PORT: 3000,
|
|
1939
|
+
API_KEY: string(),
|
|
1940
|
+
},
|
|
1941
|
+
{ enableAudit: true },
|
|
1942
|
+
);
|
|
1656
1943
|
|
|
1657
|
-
const dbConfig = resolve(
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1944
|
+
const dbConfig = resolve(
|
|
1945
|
+
{
|
|
1946
|
+
DATABASE_URL: postgres(),
|
|
1947
|
+
DB_POOL_SIZE: 10,
|
|
1948
|
+
},
|
|
1949
|
+
{ enableAudit: true },
|
|
1950
|
+
);
|
|
1661
1951
|
|
|
1662
1952
|
// Get audit logs for specific config (NEW!)
|
|
1663
|
-
const appAudit = getAuditLog(appConfig);
|
|
1664
|
-
const dbAudit = getAuditLog(dbConfig);
|
|
1953
|
+
const appAudit = getAuditLog(appConfig); // Only PORT and API_KEY events
|
|
1954
|
+
const dbAudit = getAuditLog(dbConfig); // Only DATABASE_URL and DB_POOL_SIZE events
|
|
1665
1955
|
|
|
1666
1956
|
// Still works: get ALL audit events (backward compatible)
|
|
1667
|
-
const allAudit = getAuditLog();
|
|
1957
|
+
const allAudit = getAuditLog(); // All events from both configs
|
|
1668
1958
|
|
|
1669
1959
|
console.log('App config audit:', appAudit);
|
|
1670
1960
|
// [
|
|
@@ -1682,6 +1972,7 @@ console.log('DB config audit:', dbAudit);
|
|
|
1682
1972
|
```
|
|
1683
1973
|
|
|
1684
1974
|
**Use cases:**
|
|
1975
|
+
|
|
1685
1976
|
- Multi-tenant applications with separate configs per tenant
|
|
1686
1977
|
- Microservices with different config sources
|
|
1687
1978
|
- Testing/debugging specific configuration loads
|
|
@@ -1689,13 +1980,13 @@ console.log('DB config audit:', dbAudit);
|
|
|
1689
1980
|
|
|
1690
1981
|
### Audit Event Types
|
|
1691
1982
|
|
|
1692
|
-
| Event Type
|
|
1693
|
-
|
|
1694
|
-
| `env_loaded`
|
|
1695
|
-
| `validation_success` | All variables validated successfully
|
|
1696
|
-
| `validation_failure` | Variable validation failed
|
|
1697
|
-
| `policy_violation`
|
|
1698
|
-
| `resolver_error`
|
|
1983
|
+
| Event Type | When It Occurs |
|
|
1984
|
+
| -------------------- | -------------------------------------------------------- |
|
|
1985
|
+
| `env_loaded` | Environment variable successfully loaded from a resolver |
|
|
1986
|
+
| `validation_success` | All variables validated successfully |
|
|
1987
|
+
| `validation_failure` | Variable validation failed |
|
|
1988
|
+
| `policy_violation` | Security policy check failed |
|
|
1989
|
+
| `resolver_error` | Resolver failed to load data |
|
|
1699
1990
|
|
|
1700
1991
|
### Monitoring Cache Performance
|
|
1701
1992
|
|
|
@@ -1709,18 +2000,23 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1709
2000
|
|
|
1710
2001
|
const config = await resolveAsync({
|
|
1711
2002
|
resolvers: [
|
|
1712
|
-
[
|
|
1713
|
-
|
|
1714
|
-
|
|
2003
|
+
[
|
|
2004
|
+
cached(awsSecrets({ secretId: 'prod/db' }), { ttl: TTL.minutes5 }),
|
|
2005
|
+
{
|
|
2006
|
+
DATABASE_URL: postgres(),
|
|
2007
|
+
},
|
|
2008
|
+
],
|
|
1715
2009
|
],
|
|
1716
|
-
options: { enableAudit: true }
|
|
2010
|
+
options: { enableAudit: true },
|
|
1717
2011
|
});
|
|
1718
2012
|
|
|
1719
2013
|
const logs = getAuditLog();
|
|
1720
|
-
logs.forEach(log => {
|
|
2014
|
+
logs.forEach((log) => {
|
|
1721
2015
|
if (log.type === 'env_loaded') {
|
|
1722
|
-
console.log(
|
|
1723
|
-
|
|
2016
|
+
console.log(
|
|
2017
|
+
`${log.key} from ${log.source}`,
|
|
2018
|
+
log.metadata?.cached ? '[CACHED]' : '[FRESH]',
|
|
2019
|
+
);
|
|
1724
2020
|
}
|
|
1725
2021
|
});
|
|
1726
2022
|
// Output:
|
|
@@ -1742,25 +2038,28 @@ import { awsSecrets } from 'node-env-resolver-aws';
|
|
|
1742
2038
|
const config = await resolveAsync({
|
|
1743
2039
|
resolvers: [
|
|
1744
2040
|
[processEnv(), {}],
|
|
1745
|
-
[
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
2041
|
+
[
|
|
2042
|
+
awsSecrets(),
|
|
2043
|
+
{
|
|
2044
|
+
DATABASE_PASSWORD: string(),
|
|
2045
|
+
API_KEY: string(),
|
|
2046
|
+
},
|
|
2047
|
+
],
|
|
1749
2048
|
],
|
|
1750
2049
|
options: {
|
|
1751
2050
|
policies: {
|
|
1752
2051
|
enforceAllowedSources: {
|
|
1753
2052
|
DATABASE_PASSWORD: ['aws-secrets'],
|
|
1754
|
-
API_KEY: ['aws-secrets']
|
|
1755
|
-
}
|
|
1756
|
-
}
|
|
2053
|
+
API_KEY: ['aws-secrets'],
|
|
2054
|
+
},
|
|
2055
|
+
},
|
|
1757
2056
|
// enableAudit: true automatically in production
|
|
1758
|
-
}
|
|
2057
|
+
},
|
|
1759
2058
|
});
|
|
1760
2059
|
|
|
1761
2060
|
// Send audit logs to your monitoring system
|
|
1762
2061
|
const logs = getAuditLog();
|
|
1763
|
-
const policyViolations = logs.filter(l => l.type === 'policy_violation');
|
|
2062
|
+
const policyViolations = logs.filter((l) => l.type === 'policy_violation');
|
|
1764
2063
|
|
|
1765
2064
|
if (policyViolations.length > 0) {
|
|
1766
2065
|
// Alert: Secrets loaded from unauthorized source!
|
|
@@ -1775,9 +2074,10 @@ if (policyViolations.length > 0) {
|
|
|
1775
2074
|
This package uses modern [package.json `exports`](https://nodejs.org/api/packages.html#exports) for subpath exports (like `node-env-resolver/resolvers`). TypeScript requires a modern module resolution strategy to understand these exports.
|
|
1776
2075
|
|
|
1777
2076
|
**If you see this error:**
|
|
2077
|
+
|
|
1778
2078
|
```
|
|
1779
2079
|
Cannot find module 'node-env-resolver/resolvers' or its corresponding type declarations.
|
|
1780
|
-
There are types at '.../node_modules/node-env-resolver/dist/resolvers.d.ts',
|
|
2080
|
+
There are types at '.../node_modules/node-env-resolver/dist/resolvers.d.ts',
|
|
1781
2081
|
but this result could not be resolved under your current 'moduleResolution' setting.
|
|
1782
2082
|
Consider updating to 'node16', 'nodenext', or 'bundler'.
|
|
1783
2083
|
```
|
|
@@ -1785,6 +2085,7 @@ Consider updating to 'node16', 'nodenext', or 'bundler'.
|
|
|
1785
2085
|
**Solution:** Update your `tsconfig.json` to use a modern module resolution strategy.
|
|
1786
2086
|
|
|
1787
2087
|
**Example - if your config currently has:**
|
|
2088
|
+
|
|
1788
2089
|
```json
|
|
1789
2090
|
{
|
|
1790
2091
|
"compilerOptions": {
|
|
@@ -1797,36 +2098,40 @@ Consider updating to 'node16', 'nodenext', or 'bundler'.
|
|
|
1797
2098
|
**Change to one of these options:**
|
|
1798
2099
|
|
|
1799
2100
|
1. **`moduleResolution: "NodeNext"`** (recommended for most Node.js projects):
|
|
2101
|
+
|
|
1800
2102
|
```json
|
|
1801
2103
|
{
|
|
1802
2104
|
"compilerOptions": {
|
|
1803
|
-
"module": "NodeNext",
|
|
2105
|
+
"module": "NodeNext", // Changed from "CommonJS"
|
|
1804
2106
|
"moduleResolution": "NodeNext" // Changed from "node"
|
|
1805
2107
|
}
|
|
1806
2108
|
}
|
|
1807
2109
|
```
|
|
1808
2110
|
|
|
1809
2111
|
2. **`moduleResolution: "bundler"`** (for bundler-based projects like Vite, Webpack, etc.):
|
|
2112
|
+
|
|
1810
2113
|
```json
|
|
1811
2114
|
{
|
|
1812
2115
|
"compilerOptions": {
|
|
1813
|
-
"module": "CommonJS",
|
|
2116
|
+
"module": "CommonJS", // Can keep this or use "ESNext"
|
|
1814
2117
|
"moduleResolution": "bundler" // Changed from "node"
|
|
1815
2118
|
}
|
|
1816
2119
|
}
|
|
1817
2120
|
```
|
|
1818
2121
|
|
|
1819
2122
|
3. **`moduleResolution: "node16"`** (alternative to NodeNext):
|
|
2123
|
+
|
|
1820
2124
|
```json
|
|
1821
2125
|
{
|
|
1822
2126
|
"compilerOptions": {
|
|
1823
|
-
"module": "node16",
|
|
1824
|
-
"moduleResolution": "node16"
|
|
2127
|
+
"module": "node16", // Changed from "CommonJS"
|
|
2128
|
+
"moduleResolution": "node16" // Changed from "node"
|
|
1825
2129
|
}
|
|
1826
2130
|
}
|
|
1827
2131
|
```
|
|
1828
2132
|
|
|
1829
2133
|
**Why this is required:**
|
|
2134
|
+
|
|
1830
2135
|
- The legacy `moduleResolution: "node"` strategy doesn't understand package.json `exports` field
|
|
1831
2136
|
- Modern resolution strategies (`node16`, `nodenext`, `bundler`) properly support subpath exports
|
|
1832
2137
|
- This is a TypeScript configuration requirement, not a runtime issue - your code will run correctly regardless
|
|
@@ -1852,9 +2157,11 @@ const schema = {
|
|
|
1852
2157
|
};
|
|
1853
2158
|
|
|
1854
2159
|
// Accept resolvers as parameter with sensible defaults
|
|
1855
|
-
export async function getConfig(
|
|
2160
|
+
export async function getConfig(
|
|
2161
|
+
resolvers: Resolver[] = [processEnv(), awsSecrets({ secretId: 'my-app' })],
|
|
2162
|
+
) {
|
|
1856
2163
|
return resolveAsync({
|
|
1857
|
-
resolvers: resolvers.map(r => [r, schema])
|
|
2164
|
+
resolvers: resolvers.map((r) => [r, schema]),
|
|
1858
2165
|
});
|
|
1859
2166
|
}
|
|
1860
2167
|
```
|
|
@@ -1925,7 +2232,7 @@ const createMock = (env: Record<string, string>) => ({
|
|
|
1925
2232
|
|
|
1926
2233
|
// Usage
|
|
1927
2234
|
const config = await resolveAsync({
|
|
1928
|
-
resolvers: [[createMock({ API_KEY: 'test-key' }), { API_KEY: string() }]]
|
|
2235
|
+
resolvers: [[createMock({ API_KEY: 'test-key' }), { API_KEY: string() }]],
|
|
1929
2236
|
});
|
|
1930
2237
|
```
|
|
1931
2238
|
|
|
@@ -1944,6 +2251,7 @@ const config = await getConfig([mockResolver]);
|
|
|
1944
2251
|
```
|
|
1945
2252
|
|
|
1946
2253
|
Benefits of dependency injection:
|
|
2254
|
+
|
|
1947
2255
|
- Tests are simpler and more readable
|
|
1948
2256
|
- No need to understand internal module structure
|
|
1949
2257
|
- Refactoring production code doesn't break tests
|