@@ -5,18 +5,51 @@ import { ApplicationConfig, Config } from './config.interface';
55import config from './config' ;
66
77export function loadConfig ( ) {
8- const filePath = `.env` ; //${process.env.NODE_ENV || 'local'}
8+ // Determine which env file to load. Precedence:
9+ // 1. Explicit ENV_FILE var
10+ // 2. NODE_ENV=local|development -> .env.local (if exists)
11+ // 3. Fallback to .env
12+ const explicit = process . env . ENV_FILE ;
13+ const nodeEnv = ( process . env . NODE_ENV || '' ) . toLowerCase ( ) ;
14+ const candidates : string [ ] = [ ] ;
15+ if ( explicit ) {
16+ candidates . push ( explicit ) ;
17+ } else if ( [ 'local' , 'development' , 'dev' ] . includes ( nodeEnv ) ) {
18+ candidates . push ( '.env.local' ) ;
19+ }
20+ candidates . push ( '.env' ) ;
21+
22+ let pickedPath = '.env' ;
23+ for ( const c of candidates ) {
24+ if ( fs . existsSync ( c ) ) {
25+ pickedPath = c ;
26+ break ;
27+ }
28+ }
929
10- // Try to read and parse the file
1130 let file = Buffer . from ( '' ) ;
1231 try {
13- file = fs . readFileSync ( filePath ) ;
32+ file = fs . readFileSync ( pickedPath ) ;
1433 } catch {
15- /* empty */
34+ // If nothing found we proceed with empty buffer relying on process.env
1635 }
1736
1837 const dotenvConfig = dotenv . parse ( file ) ;
1938
39+ // Inject parsed values into process.env if not already present so the rest of the
40+ // application (e.g. main.ts reading process.env.PORT) sees them.
41+ for ( const [ k , v ] of Object . entries ( dotenvConfig ) ) {
42+ if ( process . env [ k ] === undefined ) {
43+ process . env [ k ] = v ;
44+ }
45+ }
46+
47+ if ( ! process . env . ENV_FILE_LOGGED ) {
48+ // Single log guard to avoid spamming on hot-reload
49+ console . log ( `[config] Loaded environment file: ${ pickedPath } ` ) ;
50+ process . env . ENV_FILE_LOGGED = 'true' ;
51+ }
52+
2053 // Parse nested JSON in file and merge with process.env
2154 const parsedConfig = parseNestedJson ( {
2255 ...dotenvConfig ,
0 commit comments