node-env-resolver 1.1.0 → 2.0.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # node-env-resolver
2
2
 
3
- Type-safe environment variable handling with zero dependencies.
3
+ Type-safe environment variable resolution with zero dependencies.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/node-env-resolver)](https://www.npmjs.com/package/node-env-resolver)
6
6
 
@@ -10,53 +10,66 @@ Type-safe environment variable handling with zero dependencies.
10
10
  npm install node-env-resolver
11
11
  ```
12
12
 
13
- ## Quick start
13
+ ## Quick start (uses process.env)
14
14
 
15
15
  ```ts
16
16
  import { resolve } from 'node-env-resolver';
17
17
 
18
- const config = await resolve({
18
+ const config = resolve({
19
19
  PORT: 3000,
20
- DATABASE_URL: 'url',
20
+ DATABASE_URL: 'postgres',
21
21
  DEBUG: false,
22
22
  API_KEY: 'string?'
23
23
  });
24
24
 
25
- // All typed correctly
25
+ // config is fully typed
26
26
  config.PORT; // number
27
- config.DATABASE_URL; // URL object
27
+ config.DATABASE_URL; // verified postgres connection string
28
28
  config.DEBUG; // boolean
29
29
  config.API_KEY; // string | undefined
30
30
  ```
31
31
 
32
- ## Features
32
+ ## Quick start (async)
33
33
 
34
- - Zero runtime dependencies
35
- - Full TypeScript type inference
36
- - Custom validation functions
37
- - Standard Schema compliant
38
- - Works with any Node.js application
34
+ ```ts
35
+ import { resolve } from 'node-env-resolver';
39
36
 
40
- ## Built-in validators
37
+ const config = await resolve.with([asyncEnvProvider(),{
38
+ PORT: 3000,
39
+ DATABASE_URL: 'postgres',
40
+ DEBUG: false,
41
+ API_KEY: 'string?'
42
+ }]);
41
43
 
42
- The library includes validators for common use cases:
44
+ // config is fully typed
45
+ config.PORT; // number
46
+ config.DATABASE_URL; // verified postgres connection string
47
+ config.DEBUG; // boolean
48
+ config.API_KEY; // string | undefined
49
+ ```
43
50
 
44
- - **Basic**: `string`, `number`, `boolean`, `json`, `port`
45
- - **Network**: `url`, `http`, `https`, `email`
46
- - **Database**: `postgres`, `mysql`, `mongodb`, `redis`
51
+ ## Basic usage
47
52
 
48
- ## Usage
53
+ ### Required values
49
54
 
50
- ### Simple schema
55
+ If an environment variable is missing and has no default, validation fails:
51
56
 
52
57
  ```ts
53
- import { resolve } from 'node-env-resolver';
58
+ const config = resolve({
59
+ DATABASE_URL: 'url', // Required
60
+ API_KEY: 'string' // Required
61
+ });
62
+ ```
54
63
 
55
- const config = await resolve({
56
- PORT: 3000,
57
- NODE_ENV: ['development', 'production'] as const,
58
- DATABASE_URL: 'postgres',
59
- DEBUG: false
64
+ ### Default values
65
+
66
+ Provide a default value to use when the environment variable is not set:
67
+
68
+ ```ts
69
+ const config = resolve({
70
+ PORT: 3000, // Defaults to 3000
71
+ DEBUG: false, // Defaults to false
72
+ LOG_LEVEL: 'info' // Defaults to 'info'
60
73
  });
61
74
  ```
62
75
 
@@ -65,18 +78,60 @@ const config = await resolve({
65
78
  Add `?` to make a value optional:
66
79
 
67
80
  ```ts
68
- const config = await resolve({
69
- API_KEY: 'string?',
70
- REDIS_URL: 'url?'
81
+ const config = resolve({
82
+ API_KEY: 'string?', // string | undefined
83
+ REDIS_URL: 'url?', // string | undefined
84
+ MAX_RETRIES: 'number?' // number | undefined
85
+ });
86
+ ```
87
+
88
+ ### Enums
89
+
90
+ Use arrays for enum validation:
91
+
92
+ ```ts
93
+ const config = resolve({
94
+ NODE_ENV: ['development', 'production', 'test'] as const,
95
+ LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
71
96
  });
97
+
98
+ // TypeScript knows the exact types
99
+ config.NODE_ENV; // 'development' | 'production' | 'test'
100
+ config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
72
101
  ```
73
102
 
74
- ### Custom validators
103
+ ## Built-in validators
104
+
105
+ ### Basic types
106
+
107
+ - `'string'` - Any string value
108
+ - `'number'` - Numeric value (coerced from string)
109
+ - `'boolean'` - Boolean value (`'true'`/`'false'` coerced to boolean)
110
+ - `'json'` - JSON value (parsed automatically)
111
+ - `'port'` - Port number (1-65535)
112
+
113
+ ### Network types
114
+
115
+ - `'url'` - Valid URL
116
+ - `'http'` - HTTP URL
117
+ - `'https'` - HTTPS URL
118
+ - `'email'` - Email address
119
+
120
+ ### Database connection strings
121
+
122
+ - `'postgres'` or `'postgresql'` - PostgreSQL connection string
123
+ - `'mysql'` - MySQL connection string
124
+ - `'mongodb'` - MongoDB connection string
125
+ - `'redis'` - Redis connection string
126
+
127
+ All validators automatically handle type coercion from environment variable strings.
128
+
129
+ ## Custom validators
75
130
 
76
131
  Write your own validation functions:
77
132
 
78
133
  ```ts
79
- const portValidator = (value: string): number => {
134
+ const isValidPort = (value: string): number => {
80
135
  const port = parseInt(value, 10);
81
136
  if (isNaN(port) || port < 1 || port > 65535) {
82
137
  throw new Error('Port must be between 1 and 65535');
@@ -84,15 +139,22 @@ const portValidator = (value: string): number => {
84
139
  return port;
85
140
  };
86
141
 
87
- const config = await resolve({
88
- CUSTOM_PORT: portValidator,
89
- DATABASE_URL: 'postgres'
142
+ const isValidEmail = (value: string): string => {
143
+ if (!value.includes('@')) {
144
+ throw new Error('Invalid email address');
145
+ }
146
+ return value.toLowerCase();
147
+ };
148
+
149
+ const config = resolve({
150
+ CUSTOM_PORT: isValidPort,
151
+ ADMIN_EMAIL: isValidEmail
90
152
  });
91
153
  ```
92
154
 
93
- ### Multiple sources
155
+ ## Multiple sources
94
156
 
95
- Load from different sources with explicit mapping:
157
+ Load configuration from multiple sources. By default, later sources override earlier ones:
96
158
 
97
159
  ```ts
98
160
  import { resolve, processEnv, dotenv } from 'node-env-resolver';
@@ -103,237 +165,752 @@ const config = await resolve.with(
103
165
  NODE_ENV: ['development', 'production'] as const,
104
166
  }],
105
167
  [dotenv(), {
106
- DATABASE_URL: 'postgres',
168
+ DATABASE_URL: 'url',
107
169
  API_KEY: 'string',
108
170
  }]
109
171
  );
110
172
  ```
111
173
 
112
- Later sources override earlier ones if there are conflicts.
113
-
114
- ### Safe resolve (Zod-like pattern)
174
+ ### Controlling merge behaviour
115
175
 
116
- Like Zod's `parse()` vs `safeParse()`, choose between throwing errors or getting result objects:
176
+ Use `priority` to control how resolvers merge values:
117
177
 
118
178
  ```ts
119
- import { resolve, safeResolve } from 'node-env-resolver';
179
+ // priority: 'last' (default) - later resolvers override earlier ones
180
+ const config = await resolve.with(
181
+ [processEnv(), { DATABASE_URL: 'url' }],
182
+ [awsSecrets(), { DATABASE_URL: 'url' }]
183
+ // AWS wins
184
+ );
120
185
 
121
- // ❌ Throws on validation failure (like Zod's parse())
122
- try {
123
- const config = await resolve({
124
- PORT: 'number',
125
- DATABASE_URL: 'postgres',
126
- });
127
- console.log(config.PORT);
128
- } catch (error) {
129
- console.error(error.message);
130
- }
186
+ // priority: 'first' - earlier resolvers take precedence
187
+ const config = await resolve.with(
188
+ [dotenv(), { DATABASE_URL: 'url' }],
189
+ [awsSecrets(), { DATABASE_URL: 'url' }],
190
+ { priority: 'first' }
191
+ // dotenv wins
192
+ );
193
+ ```
194
+
195
+ This is useful for development workflows where local overrides should take precedence over cloud secrets.
131
196
 
132
- // ✅ Returns result object (like Zod's safeParse())
133
- const result = await safeResolve({
197
+ ## Safe error handling
198
+
199
+ Like Zod's `safeParse()`, use `safeResolve()` to get a result object instead of throwing:
200
+
201
+ ```ts
202
+ import { safeResolve } from 'node-env-resolver';
203
+
204
+ const result = safeResolve({
134
205
  PORT: 'number',
135
- DATABASE_URL: 'postgres',
206
+ DATABASE_URL: 'url'
136
207
  });
137
208
 
138
209
  if (result.success) {
139
- console.log('Port:', result.data.PORT);
140
- // result.data is fully typed
210
+ // Use result.data with full type safety
211
+ console.log(result.data.PORT);
141
212
  } else {
142
- console.error('Failed:', result.error);
213
+ // Handle error gracefully
214
+ console.error(result.error);
215
+ process.exit(1);
143
216
  }
144
217
  ```
145
218
 
146
- **All variants:**
219
+ All functions have safe variants:
220
+
221
+ - `resolve()` → `safeResolve()` (both synchronous)
222
+ - `resolve.with()` → `safeResolve.with()` (both async)
147
223
 
148
- | Function | Behavior | Use case |
149
- |----------|----------|----------|
150
- | `resolve()` | Throws on error | Simple apps, fail-fast |
151
- | `safeResolve()` | Returns `{ success, data?, error? }` | Graceful error handling |
152
- | `resolveSync()` | Sync, throws on error | Sync config loading |
153
- | `safeResolveSync()` | Sync, returns result object | Sync with error handling |
224
+ ## Synchronous resolution
154
225
 
155
- All functions support `.with()` for multiple sources:
226
+ `resolve()` is **synchronous by default** when reading from `process.env`:
156
227
 
157
228
  ```ts
158
- const result = await safeResolve.with(
229
+ import { resolve } from 'node-env-resolver';
230
+
231
+ // Synchronous - no await needed
232
+ const config = resolve({
233
+ PORT: 3000,
234
+ NODE_ENV: ['development', 'production'] as const
235
+ });
236
+ ```
237
+
238
+ However, `resolve.with()` is **async** when using custom resolvers (like loading from files or APIs):
239
+
240
+ ```ts
241
+ // Async - await required
242
+ const config = await resolve.with(
159
243
  [processEnv(), { PORT: 3000 }],
160
- [awsSecrets(), { API_KEY: 'string' }]
244
+ [dotenv(), { DATABASE_URL: 'url' }]
161
245
  );
246
+ ```
162
247
 
163
- if (!result.success) {
164
- console.error(result.error);
165
- process.exit(1);
166
- }
248
+ Synchronous resolution works with shorthand syntax and Zod schemas (see Zod integration below).
249
+
250
+ ## Advanced features
251
+
252
+ ### Zod integration
253
+
254
+ Use Zod schemas directly:
255
+
256
+ ```ts
257
+ import { resolveZod } from 'node-env-resolver/zod';
258
+ import { z } from 'zod';
259
+
260
+ const schema = z.object({
261
+ PORT: z.coerce.number().default(3000),
262
+ DATABASE_URL: z.string().url(),
263
+ NODE_ENV: z.enum(['development', 'production', 'test']),
264
+ DEBUG: z.coerce.boolean().optional(),
265
+ });
266
+
267
+ const config = await resolveZod(schema);
268
+ ```
269
+
270
+ Available functions:
271
+
272
+ - `resolveZod()` - Async, throws on error
273
+ - `safeResolveZod()` - Async, returns result object
274
+
275
+ ### Custom resolvers
276
+
277
+ Create resolvers to load configuration from any source:
278
+
279
+ ```ts
280
+ import { resolve, type Resolver } from 'node-env-resolver';
281
+
282
+ const databaseResolver: Resolver = {
283
+ name: 'database',
284
+ async load() {
285
+ const rows = await db.query('SELECT key, value FROM config');
286
+ return Object.fromEntries(rows.map(r => [r.key, r.value]));
287
+ }
288
+ };
289
+
290
+ const config = await resolve.with(
291
+ [processEnv(), { PORT: 3000 }],
292
+ [databaseResolver, { FEATURE_FLAGS: 'json' }]
293
+ );
167
294
  ```
168
295
 
169
- ### With caching
296
+ ### AWS Secrets Manager
297
+
298
+ Install the AWS package:
299
+
300
+ ```bash
301
+ npm install node-env-resolver-aws
302
+ ```
170
303
 
171
- Add TTL caching for remote sources:
304
+ Single source:
172
305
 
173
306
  ```ts
174
- import { resolve, cached, TTL } from 'node-env-resolver';
307
+ import { resolveSecrets } from 'node-env-resolver-aws';
308
+
309
+ const config = await resolveSecrets({
310
+ secretId: 'myapp/secrets'
311
+ }, {
312
+ DATABASE_URL: 'url',
313
+ API_KEY: 'string'
314
+ });
315
+ ```
316
+
317
+ Multiple sources:
318
+
319
+ ```ts
320
+ import { resolve } from 'node-env-resolver';
321
+ import { awsSecrets, awsSsm } from 'node-env-resolver-aws';
175
322
 
176
323
  const config = await resolve.with(
177
324
  [processEnv(), { PORT: 3000 }],
178
- [cached(customProvider, { ttl: TTL.minutes5 }), {
179
- API_KEY: 'string',
180
- }]
325
+ [awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: 'url' }],
326
+ [awsSsm({ path: '/app/config' }), { FEATURE_FLAGS: 'json' }]
181
327
  );
182
328
  ```
183
329
 
184
- ## API
330
+ See the [AWS package documentation](../node-env-resolver-aws/README.md) for details on credentials, caching, and best practices.
331
+
332
+ ### TTL caching
333
+
334
+ Cache expensive operations like AWS API calls:
335
+
336
+ ```ts
337
+ import { resolve, cached, TTL } from 'node-env-resolver';
338
+ import { awsSecrets } from 'node-env-resolver-aws';
339
+
340
+ export const getConfig = async () => {
341
+ return await resolve.with(
342
+ [cached(
343
+ awsSecrets({ secretId: 'app/secrets' }),
344
+ { ttl: TTL.minutes5 }
345
+ ), {
346
+ DATABASE_URL: 'url',
347
+ API_KEY: 'string',
348
+ }]
349
+ );
350
+ };
351
+
352
+ // Call getConfig() in your handlers
353
+ app.get('/api/data', async (req, res) => {
354
+ const config = await getConfig(); // Fast after first call
355
+ });
356
+ ```
357
+
358
+ Performance:
359
+
360
+ - First call: ~200ms (loads from AWS)
361
+ - Subsequent calls (< 5min): <1ms (cached)
362
+ - After 5min: ~200ms (refresh from AWS)
363
+
364
+ **Important:** Call `resolve()` every time. The `cached()` wrapper handles the caching.
365
+
366
+ ## API Reference
367
+
368
+ ### Function variants
369
+
370
+ | Function | Behaviour | Use case |
371
+ |----------|-----------|----------|
372
+ | `resolve()` | Sync, throws on error | Most applications (reading from process.env) |
373
+ | `safeResolve()` | Sync, returns result object | Graceful error handling |
374
+ | `resolve.with()` | Async, throws on error | Multiple sources (dotenv, AWS, etc.) |
375
+ | `safeResolve.with()` | Async, returns result object | Multiple sources with error handling |
185
376
 
186
377
  ### Shorthand syntax
187
378
 
379
+ | Syntax | Type | Description |
380
+ |--------|------|-------------|
381
+ | `'string'` | `string` | Required string |
382
+ | `'string?'` | `string \| undefined` | Optional string |
383
+ | `'number'` | `number` | Required number |
384
+ | `'number?'` | `number \| undefined` | Optional number |
385
+ | `'boolean'` | `boolean` | Required boolean |
386
+ | `'boolean?'` | `boolean \| undefined` | Optional boolean |
387
+ | `'url'` | `string` | Valid URL |
388
+ | `'email'` | `string` | Email address |
389
+ | `'port'` | `number` | Port (1-65535) |
390
+ | `'json'` | `unknown` | Parsed JSON |
391
+ | `'postgres'` | `string` | PostgreSQL connection string |
392
+ | `3000` | `number` | Number with default |
393
+ | `false` | `boolean` | Boolean with default |
394
+ | `['a', 'b']` | `'a' \| 'b'` | Enum (requires `as const`) |
395
+
396
+ ## Configuration Options
397
+
398
+ All `resolve()` functions accept an optional `options` parameter to control behaviour:
399
+
188
400
  ```ts
189
- 'string' // Required string
190
- 'string?' // Optional string
191
- 'url' // URL (returns URL object)
192
- 'email' // Email address
193
- 'port' // Port number (1-65535)
194
- 'json' // JSON value
195
- 'postgres' // PostgreSQL connection string
196
- 'mysql' // MySQL connection string
197
- 'mongodb' // MongoDB connection string
198
- 'redis' // Redis connection string
401
+ // Single source (process.env) - options as second parameter
402
+ const config = resolve(schema, {
403
+ interpolate: false,
404
+ strict: true,
405
+ policies: {...},
406
+ enableAudit: true
407
+ });
199
408
 
200
- // Defaults
201
- 3000 // number with default
202
- false // boolean with default
203
- ['dev', 'prod'] as const // enum (requires 'as const')
409
+ // Multiple sources - options as last parameter to resolve.with()
410
+ const config = await resolve.with(
411
+ [resolver1, schema],
412
+ [resolver2, schema],
413
+ {
414
+ interpolate: false,
415
+ strict: true,
416
+ policies: {...},
417
+ enableAudit: true,
418
+ priority: 'last'
419
+ }
420
+ );
204
421
  ```
205
422
 
206
- ### Object syntax
423
+ **Note:** The `resolvers` option has been removed. For single source resolution, use `resolve()` directly (defaults to `process.env`). For multiple sources, use `resolve.with()` syntax.
424
+
425
+ ### `interpolate`
426
+
427
+ **What:** Enables variable interpolation using `${VAR_NAME}` syntax.
428
+
429
+ **When:** Use when environment variables reference other variables.
430
+
431
+ **Why:** Keeps configuration DRY and maintainable.
207
432
 
208
- For advanced validation:
433
+ **Default:** `true` in `resolve.with()`, `false` in `resolve()`
209
434
 
210
435
  ```ts
211
- {
212
- type: 'string',
213
- pattern: '^sk_[a-zA-Z0-9]+$',
214
- min: 32,
215
- max: 64,
216
- optional: true,
217
- description: 'API key'
218
- }
436
+ // With interpolation
437
+ process.env.BASE_URL = 'https://api.example.com';
438
+ process.env.API_ENDPOINT = '${BASE_URL}/v1';
439
+
440
+ const config = resolve({
441
+ BASE_URL: 'url',
442
+ API_ENDPOINT: 'url'
443
+ }, {
444
+ interpolate: true
445
+ });
446
+
447
+ // config.API_ENDPOINT === 'https://api.example.com/v1'
219
448
  ```
220
449
 
221
- ### Options
450
+ ### `strict`
451
+
452
+ **What:** Controls whether resolver failures stop the entire resolution process.
453
+
454
+ **When:**
455
+
456
+ - `strict: true` (default) - Production environments where you want fail-fast behaviour
457
+ - `strict: false` - Graceful degradation when some sources might be unavailable
458
+
459
+ **Why:**
460
+
461
+ - `true`: Ensures all resolvers work correctly (reliability)
462
+ - `false`: Allows partial success when some resolvers fail (availability)
463
+
464
+ **Default:** `true`
222
465
 
223
466
  ```ts
224
- await resolve(schema, {
225
- resolvers: [customResolver], // Custom resolvers
226
- extend: [awsSecrets()], // Extend default resolvers
227
- strict: true, // Strict mode
228
- enableAudit: true, // Audit logging
229
- policies: { // Security policies
230
- enforceAllowedSources: {
231
- DATABASE_URL: ['aws-secrets']
232
- }
467
+ const flakyResolver = {
468
+ name: 'external-api',
469
+ async load() {
470
+ throw new Error('Service unavailable');
233
471
  }
234
- });
472
+ };
473
+
474
+ // ❌ Throws immediately
475
+ await resolve.with(
476
+ [flakyResolver, schema],
477
+ [processEnv(), schema],
478
+ { strict: true } // default
479
+ );
480
+
481
+ // ✅ Continues with processEnv()
482
+ await resolve.with(
483
+ [flakyResolver, schema],
484
+ [processEnv(), schema],
485
+ { strict: false } // graceful degradation
486
+ );
235
487
  ```
236
488
 
237
- ### Built-in resolvers
489
+ **Note:** In sync mode with `strict: true`, resolvers without `loadSync()` method will throw errors.
490
+
491
+ ### `priority`
492
+
493
+ **What:** Controls merge strategy when multiple resolvers provide the same variable.
494
+
495
+ **When:**
496
+
497
+ - `priority: 'last'` (default) - Production: cloud secrets override local env
498
+ - `priority: 'first'` - Development: local overrides override cloud secrets
499
+
500
+ **Why:** Different environments need different precedence rules.
501
+
502
+ **Default:** `'last'`
238
503
 
239
504
  ```ts
240
- import { dotenv, processEnv } from 'node-env-resolver';
505
+ // Production: AWS secrets override process.env
506
+ await resolve.with(
507
+ [processEnv(), { DATABASE_URL: 'url' }],
508
+ [awsSecrets(), { DATABASE_URL: 'url' }]
509
+ // priority: 'last' (default) - AWS wins
510
+ );
511
+
512
+ // Development: Local .env overrides cloud
513
+ await resolve.with(
514
+ [dotenv(), { DATABASE_URL: 'url' }],
515
+ [awsSecrets(), { DATABASE_URL: 'url' }],
516
+ { priority: 'first' } // dotenv wins
517
+ );
518
+ ```
519
+
520
+ **See:** "Controlling merge behaviour" section above for details.
241
521
 
242
- // Load from .env files
243
- dotenv({ path: '.env', expand: true })
522
+ ### `policies`
244
523
 
245
- // Load from process.env
246
- processEnv()
524
+ **What:** Security policies to enforce where variables can be loaded from.
525
+
526
+ **When:** Use in production to enforce security requirements.
527
+
528
+ **Why:** Prevent accidental use of `.env` files or ensure secrets come from secure sources.
529
+
530
+ **Default:** `undefined` (no policies enforced)
531
+
532
+ ```ts
533
+ await resolve.with(
534
+ [processEnv(), schema],
535
+ [awsSecrets(), schema],
536
+ {
537
+ policies: {
538
+ // Block .env in production (default behaviour)
539
+ allowDotenvInProduction: false,
540
+
541
+ // Force secrets to come from AWS
542
+ enforceAllowedSources: {
543
+ DATABASE_PASSWORD: ['aws-secrets'],
544
+ API_KEY: ['aws-secrets']
545
+ }
546
+ }
547
+ }
548
+ );
247
549
  ```
248
550
 
249
- ### Utility resolvers
551
+ **See:** "Security Policies" section below for complete documentation.
552
+
553
+ ### `enableAudit`
554
+
555
+ **What:** Enables audit logging to track where each variable was loaded from.
556
+
557
+ **When:**
558
+
559
+ - Production monitoring and compliance
560
+ - Debugging configuration issues
561
+ - Security audits
562
+
563
+ **Why:** Track configuration sources for compliance and troubleshooting.
564
+
565
+ **Default:** `false` (disabled in development), automatically `true` in production (`NODE_ENV === 'production'`)
250
566
 
251
567
  ```ts
252
- import { cached, retry, TTL } from 'node-env-resolver';
568
+ await resolve.with(
569
+ [processEnv(), schema],
570
+ [awsSecrets(), schema],
571
+ { enableAudit: true } // Explicitly enable in development
572
+ );
253
573
 
254
- // Cache with TTL
255
- cached(resolver, { ttl: 300 })
574
+ const logs = getAuditLog();
575
+ // [
576
+ // { type: 'env_loaded', key: 'DATABASE_URL', source: 'aws-secrets', ... },
577
+ // { type: 'validation_success', ... }
578
+ // ]
579
+ ```
580
+
581
+ **See:** "Audit Logging" section below for complete documentation.
582
+
583
+ ### Complete Interface
256
584
 
257
- // Retry on failure
258
- retry(resolver, { attempts: 3 })
585
+ ```ts
586
+ interface ResolveOptions {
587
+ interpolate?: boolean; // Variable interpolation (default: true in .with())
588
+ strict?: boolean; // Fail-fast behaviour (default: true)
589
+ priority?: 'first' | 'last'; // Merge strategy (default: 'last')
590
+ policies?: PolicyOptions; // Security policies (default: undefined)
591
+ enableAudit?: boolean; // Audit logging (default: auto in production)
592
+ }
259
593
 
260
- // TTL constants
261
- TTL.minute // 60
262
- TTL.minutes5 // 300
263
- TTL.hour // 3600
264
- TTL.day // 86400
594
+ interface PolicyOptions {
595
+ allowDotenvInProduction?: boolean | string[]; // .env in production control
596
+ enforceAllowedSources?: Record<string, string[]>; // Source restrictions
597
+ }
265
598
  ```
266
599
 
267
- ## Examples
600
+ ## Framework examples
268
601
 
269
- ### Express app
602
+ ### Express
270
603
 
271
604
  ```ts
605
+ import express from 'express';
272
606
  import { resolve } from 'node-env-resolver';
273
607
 
274
- const config = await resolve({
608
+ const config = resolve({
275
609
  PORT: 3000,
276
- NODE_ENV: ['development', 'production', 'test'] as const,
277
610
  DATABASE_URL: 'postgres',
278
- REDIS_URL: 'redis?',
279
- JWT_SECRET: 'string',
280
- JWT_EXPIRES_IN: '7d',
281
- ENABLE_ANALYTICS: false
611
+ SESSION_SECRET: 'string'
282
612
  });
283
613
 
284
- app.listen(config.PORT, () => {
285
- console.log(`Server running on port ${config.PORT}`);
614
+ const app = express();
615
+ app.listen(config.PORT);
616
+ ```
617
+
618
+ ### Next.js
619
+
620
+ ```ts
621
+ // env.mjs
622
+ import { resolve } from 'node-env-resolver/nextjs';
623
+
624
+ export const env = resolve({
625
+ server: {
626
+ DATABASE_URL: 'url',
627
+ API_SECRET: 'string',
628
+ },
629
+ client: {
630
+ NEXT_PUBLIC_APP_URL: 'url',
631
+ }
286
632
  });
287
633
  ```
288
634
 
289
635
  ### AWS Lambda
290
636
 
291
637
  ```ts
292
- import { resolve } from 'node-env-resolver';
638
+ import { resolve, cached, TTL } from 'node-env-resolver';
293
639
  import { awsSecrets } from 'node-env-resolver-aws';
294
640
 
295
- const config = await resolve({
296
- API_ENDPOINT: 'url',
297
- TIMEOUT: 30,
298
- LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
299
- }, {
300
- extend: [awsSecrets({ secretId: 'lambda/secrets' })]
301
- });
641
+ const getConfig = async () => {
642
+ return await resolve.with(
643
+ [cached(
644
+ awsSecrets({ secretId: 'lambda/config' }),
645
+ { ttl: TTL.minutes5 }
646
+ ), {
647
+ DATABASE_URL: 'url',
648
+ }]
649
+ );
650
+ };
302
651
 
303
652
  export const handler = async (event) => {
304
- // Use config values
653
+ const config = await getConfig();
654
+ // Use config
305
655
  };
306
656
  ```
307
657
 
308
- ## Error messages
658
+ ## Security Policies
309
659
 
310
- The library provides clear, actionable error messages:
660
+ Control where environment variables can be loaded from to enforce security requirements.
311
661
 
662
+ ### Policy: `allowDotenvInProduction`
663
+
664
+ By default, `.env` files are **completely blocked in production** for security. Production platforms (Vercel, AWS, Docker) inject environment variables via `process.env`, NOT `.env` files.
665
+
666
+ **Default behavior (secure):**
667
+
668
+ ```ts
669
+ // In production (NODE_ENV=production)
670
+ const config = await resolve.with(
671
+ [dotenv(), {
672
+ DATABASE_URL: 'url',
673
+ }]
674
+ );
675
+ // ❌ Throws: "DATABASE_URL cannot be sourced from .env files in production"
312
676
  ```
313
- ❌ Environment validation failed:
314
- - Missing required environment variable: DATABASE_URL
315
- - PORT: Invalid port number (1-65535)
316
- - NODE_ENV: must be one of: development, production (got: "staging")
677
+
678
+ **Allow all .env variables (NOT recommended):**
679
+
680
+ ```ts
681
+ const config = await resolve.with(
682
+ [dotenv(), {
683
+ DATABASE_URL: 'url',
684
+ }],
685
+ {
686
+ policies: {
687
+ allowDotenvInProduction: true // Allow all (risky!)
688
+ }
689
+ }
690
+ );
317
691
  ```
318
692
 
319
- ## TypeScript support
693
+ **Allow specific variables only (recommended if needed):**
320
694
 
321
- Full type inference works automatically:
695
+ ```ts
696
+ const config = await resolve.with(
697
+ [dotenv(), {
698
+ PORT: 3000,
699
+ DATABASE_URL: 'url',
700
+ }],
701
+ {
702
+ policies: {
703
+ allowDotenvInProduction: ['PORT'] // Only PORT allowed from .env
704
+ // DATABASE_URL must come from process.env or cloud resolvers
705
+ }
706
+ }
707
+ );
708
+ ```
709
+
710
+ ### Policy: `enforceAllowedSources`
711
+
712
+ Restrict sensitive variables to specific resolvers (e.g., force secrets to come from AWS):
322
713
 
323
714
  ```ts
324
- const config = await resolve({
325
- PORT: 3000,
715
+ import { resolve, processEnv } from 'node-env-resolver';
716
+ import { awsSecrets } from 'node-env-resolver-aws';
717
+
718
+ const config = await resolve.with(
719
+ [processEnv(), {
720
+ PORT: 3000,
721
+ }],
722
+ [awsSecrets({ secretId: 'prod/secrets' }), {
723
+ DATABASE_PASSWORD: 'string',
724
+ API_KEY: 'string',
725
+ }],
726
+ {
727
+ policies: {
728
+ enforceAllowedSources: {
729
+ DATABASE_PASSWORD: ['aws-secrets'], // Must come from AWS
730
+ API_KEY: ['aws-secrets'] // Must come from AWS
731
+ // PORT not restricted - can come from any resolver
732
+ }
733
+ }
734
+ }
735
+ );
736
+ ```
737
+
738
+ **Use case:** Ensure production secrets only come from AWS Secrets Manager, never from `.env` or `process.env`:
739
+
740
+ ```ts
741
+ import { resolve, processEnv, cached, TTL } from 'node-env-resolver';
742
+ import { awsSecrets } from 'node-env-resolver-aws';
743
+
744
+ const config = await resolve.with(
745
+ [processEnv(), {}],
746
+ [cached(awsSecrets({ secretId: 'prod/db' }), { ttl: TTL.minutes5 }), {
747
+ DATABASE_PASSWORD: 'string',
748
+ STRIPE_SECRET: 'string',
749
+ }],
750
+ {
751
+ policies: {
752
+ enforceAllowedSources: {
753
+ DATABASE_PASSWORD: ['cached(aws-secrets)'],
754
+ STRIPE_SECRET: ['cached(aws-secrets)']
755
+ }
756
+ }
757
+ }
758
+ );
759
+
760
+ // ✅ If secrets come from AWS → Success
761
+ // ❌ If secrets come from process.env → Throws policy violation error
762
+ ```
763
+
764
+ ### PolicyOptions Interface
765
+
766
+ ```ts
767
+ interface PolicyOptions {
768
+ /**
769
+ * Control loading from .env files in production.
770
+ *
771
+ * - undefined (default): .env files completely ignored in production
772
+ * - true: Allow all vars from .env in production (NOT recommended)
773
+ * - string[]: Allow only specific vars from .env in production
774
+ */
775
+ allowDotenvInProduction?: boolean | string[];
776
+
777
+ /**
778
+ * Restrict variables to specific resolvers.
779
+ *
780
+ * Example: { DATABASE_PASSWORD: ['aws-secrets'] }
781
+ */
782
+ enforceAllowedSources?: Record<string, string[]>;
783
+ }
784
+ ```
785
+
786
+ ## Audit Logging
787
+
788
+ Track environment variable resolution for security and compliance monitoring.
789
+
790
+ ### Important: Audit is Disabled by Default in Development
791
+
792
+ **Audit logging is only enabled automatically in production** (`NODE_ENV === 'production'`) for performance reasons. In development, you must explicitly enable it.
793
+
794
+ ### Enable Audit Logging
795
+
796
+ ```ts
797
+ import { resolve, getAuditLog, clearAuditLog } from 'node-env-resolver';
798
+
799
+ // Option 1: Explicitly enable (works in any environment)
800
+ const config = resolve({
801
+ DATABASE_URL: 'url',
802
+ API_KEY: 'string',
803
+ }, {
804
+ enableAudit: true // ← Enable audit logging
805
+ });
806
+
807
+ console.log(getAuditLog());
808
+ // [
809
+ // { type: 'env_loaded', key: 'DATABASE_URL', source: 'process.env', timestamp: ... },
810
+ // { type: 'env_loaded', key: 'API_KEY', source: 'aws-secrets', timestamp: ... },
811
+ // { type: 'validation_success', metadata: { variableCount: 2 }, timestamp: ... }
812
+ // ]
813
+
814
+ // Clear the log
815
+ clearAuditLog();
816
+ ```
817
+
818
+ ```ts
819
+ // Option 2: Automatic in production
820
+ process.env.NODE_ENV = 'production';
821
+
822
+ const config = resolve({
326
823
  DATABASE_URL: 'url',
327
- NODE_ENV: ['dev', 'prod'] as const,
328
- DEBUG: false
329
824
  });
330
825
 
331
- config.PORT.toFixed(2); // ✓ number
332
- config.DATABASE_URL.protocol; // ✓ URL object
333
- config.NODE_ENV === 'dev'; // ✓ 'dev' | 'prod'
334
- config.DEBUG ? 'yes' : 'no'; // ✓ boolean
826
+ // Audit automatically enabled in production
827
+ console.log(getAuditLog());
828
+ ```
829
+
830
+ ### Audit Event Types
831
+
832
+ | Event Type | When It Occurs |
833
+ |------------|----------------|
834
+ | `env_loaded` | Environment variable successfully loaded from a resolver |
835
+ | `validation_success` | All variables validated successfully |
836
+ | `validation_failure` | Variable validation failed |
837
+ | `policy_violation` | Security policy check failed |
838
+ | `resolver_error` | Resolver failed to load data |
839
+
840
+ ### Monitoring Cache Performance
841
+
842
+ Audit logs include cache metadata to help monitor performance:
843
+
844
+ ```ts
845
+ import { resolve, cached, getAuditLog } from 'node-env-resolver';
846
+ import { awsSecrets } from 'node-env-resolver-aws';
847
+
848
+ const config = await resolve.with(
849
+ [cached(awsSecrets({ secretId: 'prod/db' }), { ttl: 300000 }), {
850
+ DATABASE_URL: 'url',
851
+ }],
852
+ { enableAudit: true }
853
+ );
854
+
855
+ const logs = getAuditLog();
856
+ logs.forEach(log => {
857
+ if (log.type === 'env_loaded') {
858
+ console.log(`${log.key} from ${log.source}`,
859
+ log.metadata?.cached ? '[CACHED]' : '[FRESH]');
860
+ }
861
+ });
862
+ // Output:
863
+ // DATABASE_URL from cached(aws-secrets) [FRESH]
864
+ // (subsequent calls show [CACHED])
865
+ ```
866
+
867
+ ### Production Security Monitoring
868
+
869
+ Use audit logs for compliance and security monitoring:
870
+
871
+ ```ts
872
+ import { resolve, processEnv, getAuditLog } from 'node-env-resolver';
873
+ import { awsSecrets } from 'node-env-resolver-aws';
874
+
875
+ // In production
876
+ const config = await resolve.with(
877
+ [processEnv(), {}],
878
+ [awsSecrets(), {
879
+ DATABASE_PASSWORD: 'string',
880
+ API_KEY: 'string',
881
+ }],
882
+ {
883
+ policies: {
884
+ enforceAllowedSources: {
885
+ DATABASE_PASSWORD: ['aws-secrets'],
886
+ API_KEY: ['aws-secrets']
887
+ }
888
+ }
889
+ // enableAudit: true automatically in production
890
+ }
891
+ );
892
+
893
+ // Send audit logs to your monitoring system
894
+ const logs = getAuditLog();
895
+ const policyViolations = logs.filter(l => l.type === 'policy_violation');
896
+
897
+ if (policyViolations.length > 0) {
898
+ // Alert: Secrets loaded from unauthorized source!
899
+ console.error('Security violation:', policyViolations);
900
+ }
901
+ ```
902
+
903
+ ## Error messages
904
+
905
+ The library provides clear, actionable error messages:
906
+
907
+ ```text
908
+ Environment validation failed:
909
+ - Missing required environment variable: DATABASE_URL
910
+ - PORT: Invalid port number (1-65535)
911
+ - NODE_ENV: must be one of: development, production (got: "staging")
335
912
  ```
336
913
 
337
- ## License
914
+ ## Licence
338
915
 
339
- MIT © [Jagvinder Singh Reehal](https://jagreehal.com)
916
+ MIT