Regarding this:
https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
We strongly recommend against having a "main"
.envfile and an "environment".envfile like.env.test...you should not be sharing values between environments.
These statements seem to be contradictory. I may want to have .env.development and .env.staging (separate API keys), but the above sentence says it's strongly discouraged, but then says we shouldn't be sharing values between environments.. which is why someone would want separate .env files for dev/staging/prod.
I had the same question. You can see the discussion on it here: https://github.com/motdotla/dotenv/issues/150. The short answer is that as long as each .env.X file has a full set of the settings, then it's okay.
Your dev, staging, and prod "environments" can be thought of as "deploys" where each deploy expects a .env file for configuration. How you get each .env file to each deploy is your business but only rely on _one_ file.
What the README is advising to avoid is cascading variables or grouping or defaults because it's harder to manage and more error prone as you have more environments. For example, your application expects a database host and a database name. In development, your want the database name to be myapp_dev. When you run integration tests locally (same "environment" as development), you want the database name to be myapp_test.
How you should not structure your app:
.env:
DB_HOST=localhost
.env.dev:
DB_NAME=myapp_dev
.env.test:
DB_NAME=myapp_test
index.js:
require('dotenv').config({ path: './env' });
require('dotenv').config({ path: './env.' + process.env.NODE_ENV });
const db = require('./db');
db.connect(process.env.DB_HOST, process.env.DB_NAME);
// ... more app logic using database connection
To run in "dev" environment: NODE_ENV=dev node index.js
To run in "test" environment: NODE_ENV=test node index.js
A "better" way to structure your app:
.env.dev:
DB_HOST=localhost
DB_NAME=myapp_dev
.env.test:
DB_HOST=localhost
DB_NAME=myapp_test
index.js:
require('dotenv').config({ path: './env.' + process.env.NODE_ENV });
const db = require('./db');
db.connect(process.env.DB_HOST, process.env.DB_NAME);
// ... more app logic using database connection
To run in "dev" environment: NODE_ENV=dev node index.js
To run in "test" environment: NODE_ENV=test node index.js
dotenv as a module is very flexible and can be used in many ways so do whatever makes your life easier. We try to provide some guidance in the docs to save people headaches we've already gone through.
Thanks for clarifying!
would be great to have link to this clarification in readme.
Most helpful comment
would be great to have link to this clarification in readme.