node-env-resolver 1.0.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
71
85
  });
72
86
  ```
73
87
 
74
- ### Custom validators
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
96
+ });
97
+
98
+ // TypeScript knows the exact types
99
+ config.NODE_ENV; // 'development' | 'production' | 'test'
100
+ config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
101
+ ```
102
+
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,182 +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.
174
+ ### Controlling merge behaviour
175
+
176
+ Use `priority` to control how resolvers merge values:
177
+
178
+ ```ts
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
+ );
185
+
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.
113
196
 
114
- ### With caching
197
+ ## Safe error handling
115
198
 
116
- Add TTL caching for remote sources:
199
+ Like Zod's `safeParse()`, use `safeResolve()` to get a result object instead of throwing:
117
200
 
118
201
  ```ts
119
- import { resolve, cached, TTL } from 'node-env-resolver';
202
+ import { safeResolve } from 'node-env-resolver';
203
+
204
+ const result = safeResolve({
205
+ PORT: 'number',
206
+ DATABASE_URL: 'url'
207
+ });
208
+
209
+ if (result.success) {
210
+ // Use result.data with full type safety
211
+ console.log(result.data.PORT);
212
+ } else {
213
+ // Handle error gracefully
214
+ console.error(result.error);
215
+ process.exit(1);
216
+ }
217
+ ```
218
+
219
+ All functions have safe variants:
220
+
221
+ - `resolve()` → `safeResolve()` (both synchronous)
222
+ - `resolve.with()` → `safeResolve.with()` (both async)
223
+
224
+ ## Synchronous resolution
120
225
 
226
+ `resolve()` is **synchronous by default** when reading from `process.env`:
227
+
228
+ ```ts
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
121
242
  const config = await resolve.with(
122
243
  [processEnv(), { PORT: 3000 }],
123
- [cached(customProvider, { ttl: TTL.minutes5 }), {
124
- API_KEY: 'string',
125
- }]
244
+ [dotenv(), { DATABASE_URL: 'url' }]
126
245
  );
127
246
  ```
128
247
 
129
- ## API
248
+ Synchronous resolution works with shorthand syntax and Zod schemas (see Zod integration below).
130
249
 
131
- ### Shorthand syntax
250
+ ## Advanced features
251
+
252
+ ### Zod integration
253
+
254
+ Use Zod schemas directly:
132
255
 
133
256
  ```ts
134
- 'string' // Required string
135
- 'string?' // Optional string
136
- 'url' // URL (returns URL object)
137
- 'email' // Email address
138
- 'port' // Port number (1-65535)
139
- 'json' // JSON value
140
- 'postgres' // PostgreSQL connection string
141
- 'mysql' // MySQL connection string
142
- 'mongodb' // MongoDB connection string
143
- 'redis' // Redis connection string
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
+ });
144
266
 
145
- // Defaults
146
- 3000 // number with default
147
- false // boolean with default
148
- ['dev', 'prod'] as const // enum (requires 'as const')
267
+ const config = await resolveZod(schema);
149
268
  ```
150
269
 
151
- ### Object syntax
270
+ Available functions:
271
+
272
+ - `resolveZod()` - Async, throws on error
273
+ - `safeResolveZod()` - Async, returns result object
274
+
275
+ ### Custom resolvers
152
276
 
153
- For advanced validation:
277
+ Create resolvers to load configuration from any source:
154
278
 
155
279
  ```ts
156
- {
157
- type: 'string',
158
- pattern: '^sk_[a-zA-Z0-9]+$',
159
- min: 32,
160
- max: 64,
161
- optional: true,
162
- description: 'API key'
163
- }
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
+ );
294
+ ```
295
+
296
+ ### AWS Secrets Manager
297
+
298
+ Install the AWS package:
299
+
300
+ ```bash
301
+ npm install node-env-resolver-aws
164
302
  ```
165
303
 
166
- ### Options
304
+ Single source:
167
305
 
168
306
  ```ts
169
- await resolve(schema, {
170
- resolvers: [customResolver], // Custom resolvers
171
- extend: [awsSecrets()], // Extend default resolvers
172
- strict: true, // Strict mode
173
- enableAudit: true, // Audit logging
174
- policies: { // Security policies
175
- enforceAllowedSources: {
176
- DATABASE_URL: ['aws-secrets']
177
- }
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';
322
+
323
+ const config = await resolve.with(
324
+ [processEnv(), { PORT: 3000 }],
325
+ [awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: 'url' }],
326
+ [awsSsm({ path: '/app/config' }), { FEATURE_FLAGS: 'json' }]
327
+ );
328
+ ```
329
+
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 |
376
+
377
+ ### Shorthand syntax
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
+
400
+ ```ts
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
+ });
408
+
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'
178
419
  }
420
+ );
421
+ ```
422
+
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.
432
+
433
+ **Default:** `true` in `resolve.with()`, `false` in `resolve()`
434
+
435
+ ```ts
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
179
445
  });
446
+
447
+ // config.API_ENDPOINT === 'https://api.example.com/v1'
180
448
  ```
181
449
 
182
- ### Built-in resolvers
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`
183
465
 
184
466
  ```ts
185
- import { dotenv, processEnv } from 'node-env-resolver';
467
+ const flakyResolver = {
468
+ name: 'external-api',
469
+ async load() {
470
+ throw new Error('Service unavailable');
471
+ }
472
+ };
186
473
 
187
- // Load from .env files
188
- dotenv({ path: '.env', expand: true })
474
+ // ❌ Throws immediately
475
+ await resolve.with(
476
+ [flakyResolver, schema],
477
+ [processEnv(), schema],
478
+ { strict: true } // default
479
+ );
189
480
 
190
- // Load from process.env
191
- processEnv()
481
+ // ✅ Continues with processEnv()
482
+ await resolve.with(
483
+ [flakyResolver, schema],
484
+ [processEnv(), schema],
485
+ { strict: false } // graceful degradation
486
+ );
192
487
  ```
193
488
 
194
- ### Utility 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'`
195
503
 
196
504
  ```ts
197
- import { cached, retry, TTL } 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
+ );
198
511
 
199
- // Cache with TTL
200
- cached(resolver, { ttl: 300 })
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.
521
+
522
+ ### `policies`
523
+
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
+ );
549
+ ```
550
+
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.
201
564
 
202
- // Retry on failure
203
- retry(resolver, { attempts: 3 })
565
+ **Default:** `false` (disabled in development), automatically `true` in production (`NODE_ENV === 'production'`)
204
566
 
205
- // TTL constants
206
- TTL.minute // 60
207
- TTL.minutes5 // 300
208
- TTL.hour // 3600
209
- TTL.day // 86400
567
+ ```ts
568
+ await resolve.with(
569
+ [processEnv(), schema],
570
+ [awsSecrets(), schema],
571
+ { enableAudit: true } // Explicitly enable in development
572
+ );
573
+
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
584
+
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
+ }
593
+
594
+ interface PolicyOptions {
595
+ allowDotenvInProduction?: boolean | string[]; // .env in production control
596
+ enforceAllowedSources?: Record<string, string[]>; // Source restrictions
597
+ }
210
598
  ```
211
599
 
212
- ## Examples
600
+ ## Framework examples
213
601
 
214
- ### Express app
602
+ ### Express
215
603
 
216
604
  ```ts
605
+ import express from 'express';
217
606
  import { resolve } from 'node-env-resolver';
218
607
 
219
- const config = await resolve({
608
+ const config = resolve({
220
609
  PORT: 3000,
221
- NODE_ENV: ['development', 'production', 'test'] as const,
222
610
  DATABASE_URL: 'postgres',
223
- REDIS_URL: 'redis?',
224
- JWT_SECRET: 'string',
225
- JWT_EXPIRES_IN: '7d',
226
- ENABLE_ANALYTICS: false
611
+ SESSION_SECRET: 'string'
227
612
  });
228
613
 
229
- app.listen(config.PORT, () => {
230
- 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
+ }
231
632
  });
232
633
  ```
233
634
 
234
635
  ### AWS Lambda
235
636
 
236
637
  ```ts
237
- import { resolve } from 'node-env-resolver';
238
- import { awsSecrets } from '@node-env-resolver/aws';
239
-
240
- const config = await resolve({
241
- API_ENDPOINT: 'url',
242
- TIMEOUT: 30,
243
- LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
244
- }, {
245
- extend: [awsSecrets({ secretId: 'lambda/secrets' })]
246
- });
638
+ import { resolve, cached, TTL } from 'node-env-resolver';
639
+ import { awsSecrets } from 'node-env-resolver-aws';
640
+
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
+ };
247
651
 
248
652
  export const handler = async (event) => {
249
- // Use config values
653
+ const config = await getConfig();
654
+ // Use config
250
655
  };
251
656
  ```
252
657
 
253
- ## Error messages
658
+ ## Security Policies
254
659
 
255
- The library provides clear, actionable error messages:
660
+ Control where environment variables can be loaded from to enforce security requirements.
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.
256
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"
257
676
  ```
258
- ❌ Environment validation failed:
259
- - Missing required environment variable: DATABASE_URL
260
- - PORT: Invalid port number (1-65535)
261
- - 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
+ );
691
+ ```
692
+
693
+ **Allow specific variables only (recommended if needed):**
694
+
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
+ );
262
708
  ```
263
709
 
264
- ## TypeScript support
710
+ ### Policy: `enforceAllowedSources`
265
711
 
266
- Full type inference works automatically:
712
+ Restrict sensitive variables to specific resolvers (e.g., force secrets to come from AWS):
267
713
 
268
714
  ```ts
269
- const config = await resolve({
270
- 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({
271
823
  DATABASE_URL: 'url',
272
- NODE_ENV: ['dev', 'prod'] as const,
273
- DEBUG: false
274
824
  });
275
825
 
276
- config.PORT.toFixed(2); // ✓ number
277
- config.DATABASE_URL.protocol; // ✓ URL object
278
- config.NODE_ENV === 'dev'; // ✓ 'dev' | 'prod'
279
- 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")
280
912
  ```
281
913
 
282
- ## License
914
+ ## Licence
283
915
 
284
- MIT © [Jagvinder Singh Reehal](https://jagreehal.com)
916
+ MIT