Skip to content

Commit c0a1f84

Browse files
authored
Document process.loadEnvFile for loading .env files
Added information about loading .env files programmatically in Node.js using process.loadEnvFile. Signed-off-by: YCM Jason <[email protected]>
1 parent f7c436e commit c0a1f84

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

apps/site/pages/en/learn/command-line/how-to-read-environment-variables-from-nodejs.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,45 @@ throwing an error if the file is missing using the `--env-file-if-exists` flag.
6464
```bash
6565
node --env-file-if-exists=.env app.js
6666
```
67+
68+
69+
## Loading `.env` files programmatically with `process.loadEnvFile(path)`
70+
71+
As of **Node.js v21.7.0** (and **v20.12.0** for Node 20 LTS), Node.js provides a built-in API to load `.env` files directly from your code: [`process.loadEnvFile(path)`](https://nodejs.org/api/process.html#processloadenvfilepath).
72+
73+
This method loads variables from a `.env` file into `process.env`, similar to how the `--env-file` flag works — but can be invoked programmatically.
74+
75+
### Example
76+
77+
```js
78+
const { loadEnvFile } = require('node:process');
79+
80+
// Loads environment variables from the default .env file
81+
loadEnvFile();
82+
83+
console.log(process.env.PORT);
84+
```
85+
86+
You can also specify a custom path:
87+
88+
```js
89+
const { loadEnvFile } = require('node:process');
90+
loadEnvFile('./config/.env');
91+
```
92+
93+
### Notes
94+
95+
* **Parameters:**
96+
`path` can be a string, `URL`, `Buffer`, or `undefined`.
97+
Default: `'./.env'`.
98+
99+
* **Version history:**
100+
101+
* Added in: `v21.7.0`, `v20.12.0`
102+
* No longer experimental as of `v24.10.0`
103+
104+
* **Behaviour:**
105+
Values from `.env` are merged into `process.env`.
106+
Environment variables already set in the process take precedence.
107+
Variables like `NODE_OPTIONS` inside `.env` have no effect on Node.js startup behaviour.
108+

0 commit comments

Comments
 (0)