Why dotenv is unnecessary!

Most articles on the web recommend to use dotenv to manage environment variables. It turns out that you can easily load them without it. More importantly, it’s straightforward even if you have different env files to load.

For local development, you can load any .env file from command line directly.

For example, if you have a local env file .env.dev, you can use the following command to load it before starting a local server.

"scripts": {

"start": "node index.js",

"dev": "env $(cat .env.dev | grep -v \"#\" | xargs) npm start"

} // use npm run dev to start a local server



If you use Docker, it’s even easier.

For example, if you have already built a docker image, run it with the following command:

docker run \

-it \

-p 3000:3000 \

--env-file .env.dev \

ulangi-dev

If you use docker-compose.yml, you can use env_file option.

services:

web:

env_file:

- .env.dev

If you insist on using dotenv, the correct way is to use preloading.

I’m not against using dotenv but I don’t recommend to put require(‘dotenv’) in your application code because it loads .env and fails silently by default.

By using preloading, you can load any env files you want without changing your application code:

"scripts": {

"dev": "node -r dotenv/config index.js dotenv_config_path=.env.dev"

}

For production, you don’t need to create an .env file.

Most cloud services like AWS or Heroku, you will manage all environment variables in their respective consoles. This is good because you don’t store any important credentials locally. More importantly, you will not accidentally start a development server which uses your production data.