Dotenv
lastmod 2025-12-30created 2023-07-2713 edits
Notes related to .env.
Categories
- Environment Variables
- Python-dotenv (Python)
- varlock - Next-generation .env management tool
Nodejs project
- dotenv - npm
- Managing environment variables in a .env file with dotenv | Engineering Blog by Dale Seo
| INFORMATION |
| Note that a React App created with CRA already includes dotenv. See below |
Install the package:
Create a .env file:
Then call require("dotenv").config(); and use process.env.
CommonJS version:
// process.env 를 먼저 쓰면 안된다.
require("dotenv").config();
console.log("DB_HOST:", process.env.DB_HOST);
console.log("DB_USER:", process.env.DB_USER);
console.log("DB_PASS:", process.env.DB_PASS);
ECMAScript version:
import dotenv from "dotenv";
dotenv.config();
console.log("DB_HOST", process.env.DB_HOST);
console.log("DB_USER:", process.env.DB_USER);
console.log("DB_PASS:", process.env.DB_PASS);
If you need to read a file at a different path:
Can be used without calling it in code via node -r dotenv/config:
How to debug and override:
React projects created with CRA
- Two errors I ran into when applying dotenv in a React project
- When creating a React project with CRA, you do not need to install dotenv. (It is already built in..)
- The
.envfile must be in the root path, the same path as the package.json file. - When using dotenv with react, you must prefix variable names with
REACT_APP_. - Check that the
.envfile containskey = valuepairs. - Do not wrap values in semicolons (;), commas (,), single quotes ('), or double quotes (").
- After editing the
.envfile, you must stop and restart the server for the changes to take effect. - Be sure to add
.envto the .gitignore file
How to apply in a bash script
The allexport method:
The regex method:
Troubleshooting
When declare -x ... is suddenly printed
The .env file must not contain blank lines. Otherwise eval "export " (an empty string) is executed, and bash then prints the currently exported variables in declare -x form.
See also
Pages that link here