Skip to content

Commit 8672bcb

Browse files
config: add .env.local precedence and adjust default port to 4000
1 parent 17ac9ab commit 8672bcb

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

src/common/configs/config.helper.ts

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,51 @@ import { ApplicationConfig, Config } from './config.interface';
55
import config from './config';
66

77
export 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,

src/common/configs/config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { Config } from './config.interface';
22

33
const config: Config = {
44
nest: {
5-
port: 3000,
5+
port: 4000,
66
},
77
cors: {
88
enabled: true,

0 commit comments

Comments
 (0)