Skip to content
Search

Dotenv

lastmod 2025-12-30created 2023-07-2713 edits

Notes related to .env.

Categories

Nodejs project

INFORMATION

Note that a React App created with CRA already includes dotenv. See below

Install the package:

yarn add dotenv

Create a .env file:

DB_HOST=localhost
DB_USER=root
DB_PASS=1234

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:

dotenv.config({ path: '.env.local' });

Can be used without calling it in code via node -r dotenv/config:

DOTENV_CONFIG_PATH=.env.local node -r dotenv/config index.mjs

How to debug and override:

const result = dotenv.config({ debug: true, override: true });

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 .env file 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 .env file contains key = value pairs.
  • Do not wrap values in semicolons (;), commas (,), single quotes ('), or double quotes (").
  • After editing the .env file, you must stop and restart the server for the changes to take effect.
  • Be sure to add .env to the .gitignore file

How to apply in a bash script

The allexport method:

set -o allexport
source .env
set +o allexport

The regex method:

export "$(grep -vE "^(#.*|\s*)$" .env)"

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

author Zer0 sitemap