Loads environment variables from .env.[development|test|production][.local] files for Node.jsĀ® projects.
Installations
npm install dotenv-flow
Developer
kerimdzhanov
Developer Guide
Module System
CommonJS, ESM
Min. Node Version
>= 12.0.0
Typescript Support
Yes
Node Version
NPM Version
Statistics
864 Stars
134 Commits
35 Forks
12 Watching
7 Branches
10 Contributors
Updated on 27 Nov 2024
Languages
JavaScript (96.56%)
TypeScript (3.44%)
Total Downloads
Cumulative downloads
Total Downloads
43,911,884
Last day
27.3%
168,579
Compared to previous day
Last week
9.2%
784,572
Compared to previous week
Last month
5.7%
3,061,754
Compared to previous month
Last year
75.8%
18,360,823
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
dotenv-flow
dotenv is a zero-dependency npm module that loads environment variables from a
.env
file intoprocess.env
.
dotenv-flow extends dotenv, adding support of NODE_ENV
-specific .env*
files like .env.development
, .env.test
, .env.stage
, and .env.production
, and the appropriate .env*.local
overrides.
It allows your app to have multiple environments (like "development", "test", "stage", and "production" respectively) with selectively-adjusted environment variable setups and load them dynamically depending on the current NODE_ENV
.
In addition to that, .env*.local
overrides add the ability to overwrite variables locally for development, testing, and debugging purposes
(note that the appropriate .env*.local
entry should be added to your .gitignore
).
š± Inspired by Ruby's dotenv (a.k.a. dotenv-rails
) gem, CreateReactApp's storing configs in .env*
files approach,
the Twelve-Factor App methodology in general, and its store config in the environment section in particular.
Installation
Using NPM:
1$ npm install dotenv-flow --save
Using Yarn:
1$ yarn add dotenv-flow
Using PNPM:
1$ pnpm add dotenv-flow
Usage
As early as possible in your Node.js app, initialize dotenv-flow:
1require('dotenv-flow').config();
It will allow you to configure and use dotenv-flow from your code programmatically.
If you're using TypeScript or ES Modules:
1import dotenvFlow from 'dotenv-flow'; 2dotenvFlow.config();
Alternatively, you can use the default config entry point that allows you to configure dotenv-flow using command switch flags or predefined environment variables:
1require('dotenv-flow/config');
Or even make dotenv-flow load environment variables for your app without adding it to the code using preload technique:
1$ node -r "dotenv-flow/config" your_app.js
It works with ts-node
as well:
1$ ts-node -r "dotenv-flow/config" your_app.ts
How it works
Once dotenv-flow is initialized (using .config
or any other method above), environment variables defined in your .env*
files are loaded and become accessible in your Node.js app via process.env.*
.
For example, let's suppose that you have the following .env*
files in your project:
1# .env 2 3DATABASE_HOST=127.0.0.1 4DATABASE_PORT=27017 5DATABASE_USER=default 6DATABASE_PASS= 7DATABASE_NAME=my_app
1# .env.local 2 3DATABASE_USER=local-user 4DATABASE_PASS=super-secret
1# .env.development 2 3DATABASE_NAME=my_app_dev
1# .env.test 2 3DATABASE_NAME=my_app_test
1# .env.production 2 3DATABASE_NAME=my_app_prod
1# .env.production.local 2 3DATABASE_HOST=10.0.0.32 4DATABASE_PORT=27017 5DATABASE_USER=devops 6DATABASE_PASS=1qa2ws3ed4rf5tg6yh 7DATABASE_NAME=application_storage
1// your_script.js 2 3require('dotenv-flow').config(); 4 5console.log('database host:', process.env.DATABASE_HOST); 6console.log('database port:', process.env.DATABASE_PORT); 7console.log('database user:', process.env.DATABASE_USER); 8console.log('database pass:', process.env.DATABASE_PASS); 9console.log('database name:', process.env.DATABASE_NAME);
And if you run your_script.js
in the development environment, like:
1$ NODE_ENV=development node your_script.js
you'll get the following output:
1database host: 127.0.0.1 2database port: 27017 3database user: local-user 4database pass: super-secret 5database name: my_app_dev
Or if you run the same script in the production environment:
1$ NODE_ENV=production node your_script.js
you'll get the following:
1database host: 10.0.0.32 2database port: 27017 3database user: devops 4database pass: 1qa2ws3ed4rf5tg6yh 5database name: application_storage
Note that the .env*.local
files should be ignored by your version control system (refer the Files under version control section below to learn more), and you should have the .env.production.local
file only on your production deployment machine.
NODE_ENV
-specific env files
Actually, dotenv-flow doesn't have any predefined environment names, so you may use whatever names you want.
However, it's a good practice to use the world's universally recognized environment names like development
, test
, production
, as well as frequently used qa
or stage
.
The naming convention for NODE_ENV
-specific files is simply as .env.${NODE_ENV}[.local]
(i.e. .env.development
, .env.test
, .env.production
, .env.development.local
, .env.production.local
, etc.).
To activate specific environment run your application with predefined NODE_ENV
environment variable, like:
1$ export NODE_ENV=production 2$ node your_script.js
or:
1$ NODE_ENV=production node your_script.js
If you are on Windows:
1> SET NODE_ENV=production 2> node your_script.js
Or even better, use cross-env to make it work independent of platform:
1$ cross-env NODE_ENV=production node your_script.js
The --node-env
switch is also supported:
1$ node your_script.js --node-env=production
Preload
Alternatively, you can preload dotenv-flow using node's -r
(--require
) command line option.
1$ NODE_ENV=production node -r dotenv-flow/config your_script.js
or:
1$ node -r dotenv-flow/config your_script.js --node-env=production
You can also use environment variables to set configuration options when preloading the dotenv-flow/config
:
1$ DOTENV_FLOW_PATH=/path/to/env-files-dir node -r dotenv-flow/config your_script.js
Refer to the dotenv-flow/config
options section below to see all available options.
Files under version control
The main point here is not to commit production database passwords, API keys and other sensitive things to your source code repository, but it's still nice to have default database connections, ports, hosts, etc., for development and testing purposes to keep your code clean and simple.
Understanding the above, we have the following approach:
You can keep all the fallback values in the default .env
file, that (if exists) will always be loaded by default.
Also, it is a good place to have all the application used environment variables there, thus having a reference of environment variables that are used by your application on the whole.
So it is a good reason to share the .env
file with other developers in your team, but keep all the sensitive data on your own (or production) machine locally in the .env*.local
files.
It is not necessary, but also a good practice to use NODE_ENV
to control the environment to run your application in.
And if you follow this practice you can keep the NODE_ENV
-specific defaults in your .env.development
, .env.test
, .env.production
files sharing them with your team as well.
Any NODE_ENV
-specific .env.*
file's values can also be overwritten in the appropriate .env.*.local
file (i.e. .env.development.local
, .env.test.local
, .env.production.local
).
Summarizing the above, you can have the following .env*
files in your project:
.env
ā for default (fallback) values, tracked by VCS.env.development
ā for development environment, tracked by VCS.env.test
ā for test environment, tracked by VCS.env.production
ā for production environment, tracked by VCS.env.local
ā for individual default values, ignored by VCS.env.development.local
ā for individual development environment values, ignored by VCS.env.test.local
ā for individual test environment values, ignored by VCS.env.production.local
ā for production environment values (DB passwords, API keys, etc.), ignored by VCS
Note that .env.*
file names may vary in your project depending on your own needs/preferences, just keep in mind that .env*.local
files should be untracked (ignored) by your version control system.
Here is an example of the .gitignore
(or .hgignore
) file entry to keep it clear:
1# local .env* files 2.env.local 3.env.*.local
Variables overwriting/priority
Since multiple .env*
files are loaded simultaneously, all the variables defined in these files are merged in the following order:
- The
.env
file has the lowest priority. Keep the most default (fallback) values there; - The
.env.local
file has a priority over the.env
(except whenNODE_ENV=test
, in which case this file is not loaded). Create it if you want to overwrite the default values for your own environment-specific needs; NODE_ENV
-specific env files (like.env.development
,.env.test
, etc.) have a priority over the default.env
and.env.local
files. KeepNODE_ENV
-specific environment variables there;NODE_ENV
-specific local env files (.env.development.local
,.env.production.local
, etc.) have the highest priority over all the env files. As with.env.local
, create them only if you need to overwriteNODE_ENV
-specific values for your own environment-specific needs;- Environment variables that are already set will not be overwritten, that means that the command line variables have a higher priority over all those defined in env files;
Alternative defaults: .env.defaults
In addition to .env
, you may also use .env.defaults
to store default (fallback) values.
This may come handy e.g. when migrating from dotenv (where it is strongly advised against committing .env
file to VCS)
and you already have .env
file used to store your local values.
In such case, you may prefer to keep using your existing .env
(ignored by VCS) as your local config
and create additional .env.defaults
(tracked by VCS) file which will be loaded before .env
.
Then at every place .env
is mentioned in the docs, read it as: ".env.defaults
first, then .env
".
dotenv-flow/config
options
The following configuration options can be used when:
- a) preloading dotenv-flow using Node's
-r
([ts-]node --require
) switch, orā¦ - b)
require
ing thedotenv-flow/config
entry point (usingrequire('dotenv-flow/config');
).
Environment variables
NODE_ENV
=>options.node_env
;DEFAULT_NODE_ENV
=>options.default_node_env
;DOTENV_FLOW_PATH
=>options.path
;DOTENV_FLOW_PATTERN
=>options.pattern
;DOTENV_FLOW_ENCODING
=>options.encoding
;DOTENV_FLOW_PURGE_DOTENV
=>options.purge_dotenv
;DOTENV_FLOW_DEBUG
=>options.debug
;DOTENV_FLOW_SILENT
=>options.silent
;
for example:
1$ NODE_ENV=production DOTENV_FLOW_PATH=/path/to/env-files-dir node -r dotenv-flow/config your_script.js
Command line switches
--node-env
=>options.node_env
;--default-node-env
=>options.default_node_env
;--dotenv-flow-path
=>options.path
;--dotenv-flow-pattern
=>options.pattern
;--dotenv-flow-encoding
=>options.encoding
;--dotenv-flow-purge-dotenv
=>options.purge_dotenv
;--dotenv-flow-debug
=>options.debug
;--dotenv-flow-silent
=>options.silent
;
Make sure that dotenv-flow/config-specific CLI switches are separated from Node's by
--
(double dash) since they are not recognized by Node.js.
for example:
1$ node --require dotenv-flow/config your_script.js -- --dotenv-flow-path=/path/to/project --dotenv-flow-encoding=base64
API reference
.config([options]) => object
"dotenv-flow" initialization function (API entry point).
Allows configuring dotenv-flow programmatically.
Also, like the original module (dotenv),
it returns an object
with .parsed
property containing the resulting
varname => values
pairs or .error
property if the initialization is failed.
options.node_env
Type: string
Default: process.env.NODE_ENV
With the node_env
option you can force the module to use your custom environment value independent of process.env.NODE_ENV
:
1require('dotenv-flow').config({ 2 node_env: process.argv[2] || 'development' 3});
options.default_node_env
Type: string
Default: undefined
If the NODE_ENV
environment variable is not set, the module doesn't load/parse any NODE_ENV
-specific files at all.
Therefore, you may want to use "development"
as a default environment, like:
1require('dotenv-flow').config({ 2 default_node_env: 'development' 3});
To be clear, just make a note that all the following initialization examples are also equivalent:
1process.env.NODE_ENV = process.env.NODE_ENV || 'development'; 2 3require('dotenv-flow').config();
1require('dotenv-flow').config({ 2 node_env: process.env.NODE_ENV || 'development' 3});
1require('dotenv-flow').config({ 2 node_env: process.env.NODE_ENV, 3 default_node_env: 'development' 4});
All the examples above, considers the value of process.env.NODE_ENV
at first, and if it is not set, uses "development"
as the value by default.
You can just choose one that looks prettier for you.
options.path
Type: string
Default: process.cwd()
(current working directory)
With the path
initialization option you can specify a path to .env*
files directory:
1require('dotenv-flow').config({ 2 path: '/path/to/env-files-dir' 3});
If the option is not provided, the current working directory is used.
options.pattern
Type: string
Default: ".env[.node_env][.local]"
Allows you to change the default .env*
files' naming convention
if you want to have a specific file naming structure for maintaining
your environment variables' files.
Default Value
The default value ".env[.node_env][.local]"
makes dotenv-flow look up
and load the following files in order:
.env
.env.local
.env.${NODE_ENV}
.env.${NODE_ENV}.local
For example, when the proess.env.NODE_ENV
(or options.node_env
) is set to "development"
,
dotenv-flow will be looking for and parsing (if found) the following files:
.env
.env.local
.env.development
.env.development.local
Custom Pattern
Here is a couple of examples of customizing the .env*
files naming convention:
For example, if you set the pattern to ".env/[local/]env[.node_env]"
,
dotenv-flow will look for these files instead:
.env/env
.env/local/env
.env/env.development
.env/local/env.development
ā¦ or if you set the pattern to ".env/[.node_env/].env[.node_env][.local]"
,
dotenv-flow will try to find and parse:
.env/.env
.env/.env.local
.env/development/.env.development
.env/development/.env.development.local
āŗ Please refer to .listFiles([options])
to dive deeper.
options.files
Type: string[]
Allows explicitly specifying a list (and the order) of .env*
files to load.
Note that options like node_env
, default_node_env
, and pattern
are ignored in this case.
1require('dotenv-flow').config({ 2 files: [ 3 '.env', 4 '.env.local', 5 `.env.${process.env.NODE_ENV}`, // '.env.development' 6 `.env.${process.env.NODE_ENV}.local` // '.env.development.local' 7 ] 8});
options.encoding
Type: string
Default: "utf8"
You can specify the encoding for reading your files containing environment variables.
1require('dotenv-flow').config({ 2 encoding: 'base64' 3});
options.purge_dotenv
Type: boolean
Default: false
In some cases the original "dotenv" library can be used by one of the dependent
npm modules. It causes calling the original dotenv.config()
that loads
the .env
file from your project before you can call dotenv-flow.config()
.
Such cases breaks .env*
files priority because the previously loaded
environment variables are treated as shell-defined thus having a higher priority.
Setting the purge_dotenv
option to true
can gracefully fix this issue.
1require('dotenv-flow').config({ 2 purge_dotenv: true 3});
options.debug
Type: boolean
Default: false
Enables detailed logging to debug why certain variables are not being set as you expect.
options.silent
Type: boolean
Default: false
Suppresses all kinds of warnings including ".env*" files' loading errors.
1require('dotenv-flow').config({ 2 silent: true 3});
The following API is considered as internal, although it's exposed for programmatic use of dotenv-flow for your own project-specific needs.
.listFiles([options]) => string[]
Returns a list of existing .env*
filenames depending on the given options
.
The resulting list is ordered by the env files' variables overwriting priority from lowest to highest.
This can also be referenced as "env files' environment cascade" or "order of ascending priority."
ā ļø Note that the .env.local
file is not listed for "test" environment,
since normally you expect tests to produce the same results for everyone.
Parameters:
options.node_env
Type: string
Default: undefined
The node environment (a.k.a. process.env.NODE_ENV
).
The conventionally used values are "development"
, "test"
(or "staging"
) and "production"
, also commonly used are "qa"
, "uat"
, "ci"
.
options.pattern
Type: string
Default: ".env[.node_env][.local]"
.env*
files' naming convention pattern.
The default one, (".env[.node_env][.local]"
) without options.node_env
given,
produces the following list of filenames:
.env
.env.local
When options.node_env
is set, for example to "development"
,
it appends "node_env-specific" filenames, that will make .listFiles
to return:
.env
.env.local
.env.development
.env.development.local
Another example might be the pattern ".env/[local/]env[.node_env]"
,
that without options.node_env
will produce:
.env/env
.env/local/env
ā¦ and if options.node_env
is set to (for example) "development"
,
will append "node_env-specific" files producing the following:
.env/env
.env/local/env
.env/env.development
.env/local/development
Also, note that if [node_env]
placeholders is missing in the pattern,
none of the "node_env-specific" files fill be listed.
For example, a pattern like ".env[.local]"
,
independently of whether the options.node_env
is set, will always produce:
.env
.env.local
ā¦ except the case when options.node_env
is set to "test"
,
which (as mentioned above) will exclude .env.local
producing just a single:
.env
ā¦ since normally we expect tests to produce the same results for everyone.
options.debug
Type: boolean
Default: false
Enables debug messages.
Returns:
Type: string[]
A list of .env*
filenames.
Example:
1const dotenvFlow = require('dotenv-flow'); 2 3const filenames = dotenvFlow.listFiles({ node_env: 'development' }); 4 5console.log(filenames); // will output the following: 6// > [ '/path/to/project/.env.defaults', 7// > '/path/to/project/.env', 8// > '/path/to/project/.env.local', 9// > '/path/to/project/.env.development', 10// > '/path/to/project/.env.development.local' ]
.parse(filenames, [options]) => object
Parses the content of a given file(s) to use the result programmatically. Accepts a filename or a list of filenames and returns a map of the parsed key/values as an object.
When several filenames are given, the parsed variables are merged into a single object using the "overwrite" strategy.
Parameters:
filenames
Type: string|string[]
A filename or a list of filenames to parse.
options.encoding
Type: string
Default: "utf8"
An optional encoding for reading files.
options.debug
Type: boolean
Default: false
Enables debug messages.
Returns:
Type: object
The resulting map of { env_var: value }
as an object.
Example:
1# .env 2 3FOO=bar 4BAZ=bar
1# .env.local 2 3BAZ=qux
1const dotenvFlow = require('dotenv-flow'); 2 3const variables = dotenvFlow.parse([ 4 '/path/to/project/.env', 5 '/path/to/project/.env.local' 6]); 7 8console.log(typeof variables, variables); // > object { FOO: 'bar', BAZ: 'qux' }
.load(filenames, [options]) => object
Loads variables defined in a given file(s) into process.env
.
When several filenames are given, parsed environment variables are merged using the "overwrite" strategy since it utilizes .parse()
for doing this.
But eventually, assigning the parsed environment variables to process.env
is done using the "append" strategy, thus giving a higher priority to the environment variables predefined by the shell.
Parameters:
filenames
Type: string|string[]
A filename or a list of filenames to load.
options.encoding
Type: string
Default: "utf8"
An optional encoding for reading files.
options.debug
Type: boolean
Default: false
Optionally, turn on debug messages.
options.silent
Type: boolean
Default: false
If enabled, suppresses all kinds of warnings including ".env*" files' loading errors.
Returns:
Type: object
The same as .config()
, the returning object contains
.parsed
property with a parsed content of the given file(s),
or if parsing is failed the .error
property with a reference
to the reasoning error.
Example:
1# .env 2 3FOO=bar 4BAZ=bar
1# .env.local 2 3BAZ=qux
1const dotenvFlow = require('dotenv-flow'); 2 3process.env.BAZ = 'Yay!'; 4 5const result = dotenvFlow.load([ 6 '/path/to/project/.env', 7 '/path/to/project/.env.local' 8]); 9 10console.log(typeof result, result); // > object { parsed: { FOO: 'bar', BAZ: 'qux' } } 11 12console.log(process.env.FOO); // > 'bar' 13console.log(process.env.BAZ); // > 'Yay!'
.unload(filenames, [options]) => void
Unloads variables defined in a given file(s) from process.env
.
The environment variables that are predefined (i.e. by the shell) will not be unloaded.
Parameters:
filenames
Type: string|string[]
A filename or a list of filenames to unload.
options.encoding
Type: string
Default: "utf8"
An optional encoding for reading files.
Example:
1# .env 2 3FOO=bar 4BAZ=bar
1# .env.local 2 3BAZ=qux
1const dotenvFlow = require('dotenv-flow'); 2 3process.env.BAZ = 'Yay!'; 4 5dotenvFlow.load([ '/path/to/project/.env', '/path/to/project/.env.local']); 6 7console.log(process.env.FOO); // > 'bar' 8console.log(process.env.BAZ); // > 'Yay!' 9 10dotenvFlow.unload([ '/path/to/project/.env', '/path/to/project/.env.local']); 11 12console.log(process.env.FOO); // > undefined 13console.log(process.env.BAZ); // > 'Yay!'
Related packages
@types/dotenv-flow
ā type definitions for usingdotenv-flow
with TypeScriptdotenv-flow-webpack
ā a webpack plugin for usingdotenv-flow
in web applicationsdotenv-flow-cli
ā CLI executable that preloads environment variables usingdotenv-flow
dotenv-expand
ā environment variables expansion (originally designed fordotenv
, but also compatible withdotenv-flow
)
Contributing
Feel free to dive in! Open an issue or submit PRs.
Running tests
Using NPM:
1$ npm test
Using Yarn:
1$ yarn test
License
Licensed under MIT Ā© 2018-2023 Dan Kerimdzhanov
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
2 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
Reason
Found 1/29 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Warn: no topLevel permission defined: .github/workflows/yarn-npm-publish.yml:1
- Info: no jobLevel write permissions found
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:34: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/yarn-npm-publish.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/yarn-npm-publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/yarn-npm-publish.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/yarn-npm-publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/yarn-npm-publish.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/yarn-npm-publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/yarn-npm-publish.yml:33: update your workflow using https://app.stepsecurity.io/secureworkflow/kerimdzhanov/dotenv-flow/yarn-npm-publish.yml/master?enable=pin
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 10 are checked with a SAST tool
Score
3.6
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to dotenv-flow
@types/dotenv-flow
TypeScript definitions for dotenv-flow
dotenv-flow-cli
A cli executable to run commands with the ENV variables loaded by dotenv-flow
cypress-dotenv-flow
Cypress plugin that enables compatability with dotenv-flow
dotenv-flow-webpack
A webpack plugin that allows you to securely use environment variables within your javascript web application, loading them using dotenv-flow's `.env*` files loading strategy.