Skip to content

Commit 13d9b53

Browse files
committed
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 <me@ycmjason.com>
1 parent f7c436e commit 13d9b53

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,42 @@ 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+
## Loading `.env` files programmatically with `process.loadEnvFile(path)`
69+
70+
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).
71+
72+
This method loads variables from a `.env` file into `process.env`, similar to how the `--env-file` flag works — but can be invoked programmatically.
73+
74+
### Example
75+
76+
```js
77+
const { loadEnvFile } = require('node:process');
78+
79+
// Loads environment variables from the default .env file
80+
loadEnvFile();
81+
82+
console.log(process.env.PORT);
83+
```
84+
85+
You can also specify a custom path:
86+
87+
```js
88+
const { loadEnvFile } = require('node:process');
89+
loadEnvFile('./config/.env');
90+
```
91+
92+
### Notes
93+
94+
- **Parameters:**
95+
`path` can be a string, `URL`, `Buffer`, or `undefined`.
96+
Default: `'./.env'`.
97+
98+
- **Version history:**
99+
- Added in: `v21.7.0`, `v20.12.0`
100+
- No longer experimental as of `v24.10.0`
101+
102+
- **Behaviour:**
103+
Values from `.env` are merged into `process.env`.
104+
Environment variables already set in the process take precedence.
105+
Variables like `NODE_OPTIONS` inside `.env` have no effect on Node.js startup behavior.

0 commit comments

Comments
 (0)