Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
DOTENV_ENCODING, DOTENV_PATH, DOTENV_QUIET, DOTENV_DEBUG, DOTENV_OVERRIDE, and DOTENV_FAST provide defaults for config() and dotenv run. Options/flags passed directly take precedence, followed by DOTENV_*, then the legacy DOTENV_CONFIG_* names. Empty values and false values do not fall back.
bun
bun add dotenv
yarn
yarn add dotenv
pnpm
pnpm add dotenv
deno
deno add dotenv
Monorepos
For monorepos with a structure like apps/backend/app.js, put it the .env file in the root of the folder where your app.js process runs.
Comments may be added to your file on their own line or inline:
# This is a commentSECRET_KEY=YOURSECRETKEYGOESHERE # commentSECRET_HASH="something-with-a-#-hash"
Comments begin where a # exists, so if your value contains a # please wrap it in quotes. This is a breaking change from >= v15.0.0 and on.
Parsing
The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.
Use dotenv run to run a command with environment variables from your .env file. The -- separator is optional. Put dotenv options before the command; everything after the command is passed through as its arguments.
$ dotenv run node index.js◇ injected env (2) from .env
Use -f or --file to select one or more .env files. Separate paths with commas or repeat either flag; files are loaded in the order given. The first value wins unless --override is set.
$ dotenv run --file .env.local,.env node index.js◇ injected env (2) from .env.local, .env
Use -q or --quiet to suppress the injected env message.
$ dotenv run -q node index.js
Use --override to overwrite existing environment variables, and for debug logging.
We recommend creating one .env file per environment. Use .env for local/development, .env.production for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (.env.production inherits values from .env for example). It is better to duplicate values if necessary across each .env.environment file.
In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
Additionally, we recommend using dotenvx to encrypt and manage these.
How do I use dotenv with `import`?
Import dotenv/config before modules that read environment variables.
// index.mjs (ESM)import 'dotenv/config'import express from 'express'
This loads environment variables before the rest of your application modules are initialized. You can also use the CLI to inject them before Node starts:
dotenv run -- node index.mjs
Can I customize/write plugins for dotenv?
Yes! dotenv.config() returns an object representing the parsed .env file. This gives you everything you need to continue setting values on process.env. For example:
npm i -g @dotenvx/dotenvxdotenvx precommit --install
What happens to environment variables that were already set?
By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped.
If instead, you want to override process.env use the override option.
require('dotenv').config({ override: true })
How can I prevent committing my `.env` file to a Docker build?
How come my environment variables are not showing up for React?
Your React code is run in Webpack, where the fs module or even the process global itself are not accessible out-of-the-box. process.env can only be injected through Webpack configuration.
If you are using react-scripts, which is distributed through create-react-app, it has dotenv built in but with a quirk. Preface your environment variables with REACT_APP_. See this stack overflow for more details.
If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.
Why is the `.env` file not loading my environment variables successfully?
config will read your .env file, parse the contents, assign it to
process.env,
and return an Object with a parsed key containing the loaded content or an error key if it failed.
const result = dotenv.config()if (result.error) { throw result.error}console.log(result.parsed)
You can additionally, pass options to config.
Options
path
Default: path.resolve(process.cwd(), '.env')
Specify a custom path if your file containing environment variables is located elsewhere.
const fileUrl = new URL('file:///custom/path/to/.env')require('dotenv').config({ path: fileUrl })
By default, config will look for a file called .env in the current working directory.
Pass in multiple files as an array, and they will be parsed in order and combined with process.env (or option.processEnv, if set). The first value set for a variable will win, unless the options.override flag is set, in which case the last value set will win. If a value already exists in process.env and the options.override flag is NOT set, no changes will be made to that value.
Suppress runtime logging message. dotenv/config imports and preloads default to true; set DOTENV_QUIET=false (or DOTENV_CONFIG_QUIET=false) in the shell to enable their startup message.
// index.jsrequire('dotenv').config({ quiet: false }) // change to true to suppressconsole.log(`Hello ${process.env.HELLO}`)
# .envHELLO=World
$ node index.jsHello World
encoding
Default: utf8
Specify the encoding of your file containing environment variables.
require('dotenv').config({ encoding: 'latin1' })
debug
Default: false
Turn on logging to help debug why certain keys or values are not being set as you expect.
Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in option.path the override will also be used as each file is combined with the next. Without override being set, the first value wins. With override set the last value wins.
require('dotenv').config({ override: true })
fast
Default: false
Use the faster character-scanner parser (~2x). Default remains the classic regex parser.
Specify an object to write your environment variables to. Defaults to process.env environment variables.
const myObject = {}require('dotenv').config({ processEnv: myObject })console.log(myObject) // values from .envconsole.log(process.env) // this was not changed or written to
Parse
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
Turn on logging to help debug why certain keys or values are not being set as you expect.
const dotenv = require('dotenv')const buf = Buffer.from('hello world')const opt = { debug: true }const config = dotenv.parse(buf, opt)// expect a debug message because the buffer is not in KEY=VAL form
Populate
The engine which populates the contents of your .env file to process.env is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.
Without --override, existing environment variables take precedence and the first value found across files wins. With --override, values from the files replace existing variables, and later files override earlier ones.
The CLI forwards the command's exit status. A missing default .env is allowed; a missing file explicitly selected with -f stops the command from running.
Environment defaults
Use these environment variables to set defaults. CLI flags take precedence over them.
Variable
Default
Description
DOTENV_PATH
.env
Path to the file to load.
DOTENV_ENCODING
utf8
File encoding.
DOTENV_QUIET
false
Suppress the injected environment variables message.
DOTENV_DEBUG
false
Enable debug logging.
DOTENV_OVERRIDE
false
Overwrite existing environment variables.
DOTENV_FAST
false
Use the faster parser.
The legacy DOTENV_CONFIG_* names remain fallbacks when the corresponding DOTENV_* variable is unset. For boolean settings, false, 0, no, off, and an empty value disable the setting.