Loads environment variables from .env for nodejs projects.
Loads environment variables from .env for nodejs projects.
If you like dotenv, you will probably love dotenvx – for encrypting
.envfiles. Thank you for using dotenv. 🙏
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.
Install it.
npm install dotenv --saveCreate a .env file in the root of your project:
# .env
HELLO="Dotenv"
OPENAI_API_KEY="your-api-key-goes-here"As early as possible in your application, import and configure dotenv:
// index.js
require('dotenv').config()
// or import 'dotenv/config' // for esm
console.log(`Hello ${process.env.HELLO}`)$ node index.js
◇ injected env (2) from .env
Hello DotenvThat's it. process.env now has the keys and values you defined in your .env file.
Import with ES6:
import 'dotenv/config'DOTENV_CONFIG_ENCODING, DOTENV_CONFIG_PATH, DOTENV_CONFIG_QUIET, DOTENV_CONFIG_DEBUG, DOTENV_CONFIG_OVERRIDE, DOTENV_CONFIG_SECURE, and DOTENV_CONFIG_FAST provide defaults for config() and dotenv run. Options/flags passed directly take precedence.
bun add dotenvyarn add dotenvpnpm add dotenvdeno add dotenvFor 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.
# app/backend/.env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"If you need multiline variables, for example private keys, those are now supported (>= v15.0.0) with line breaks:
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"Alternatively, you can double quote strings and use the \n character:
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"Comments may be added to your file on their own line or inline:
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_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.
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.
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }Use dotenv run -- to run a command with environment variables from your .env file.
$ dotenv run -- node index.js
◇ injected env (2) from .envUse -f to select one or more .env files.
$ dotenv run -f .env.local -f .env -- node index.js
◇ injected env (2) from .env.local, .envUse --quiet to suppress the injected env message.
$ dotenv run --quiet -- node index.jsUse --override to overwrite existing environment variables, and --debug for debug logging.
$ dotenv run --override --debug -- node index.jsUse --secure or config({ secure: true }) to decrypt via dotenvx.
$ npm i @dotenvx/dotenvx
$ dotenv run --secure -- node index.jsrequire('dotenv').config({ secure: true })Or with an environment variable:
$ DOTENV_CONFIG_SECURE=true dotenv run -- node index.js
$ DOTENV_CONFIG_SECURE=true node -e "require('dotenv').config()"dotenv run --secure resolves local @dotenvx/dotenvx then dotenvx on your PATH. config({ secure: true }) requires a local @dotenvx/dotenvx install.
If your .env contains encrypted: values and you run without --secure / secure: true, dotenv warns and leaves them encrypted.
The same DOTENV_CONFIG_* environment variables formerly used by preload still work with the CLI. CLI flags take precedence.
$ DOTENV_CONFIG_PATH=./.env.local DOTENV_CONFIG_QUIET=true dotenv run -- node index.jsUse --fast (or config({ fast: true })) for the faster character-scanner parser (~2x). Default remains the classic regex parser.
$ dotenv run --fast -- node index.jsrequire('dotenv').config({ fast: true })Supported: DOTENV_CONFIG_PATH, DOTENV_CONFIG_ENCODING, DOTENV_CONFIG_QUIET, DOTENV_CONFIG_DEBUG, DOTENV_CONFIG_OVERRIDE, DOTENV_CONFIG_SECURE, DOTENV_CONFIG_FAST.
Use dotenvx for variable expansion.
Reference and expand variables already on your machine for use in your .env file.
# .env
USERNAME="username"
DATABASE_URL="postgres://${USERNAME}@localhost/my_database"// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)$ dotenvx run --debug -- node index.js
⟐ injected env (2) from .env · [email protected]
DATABASE_URL postgres://username@localhost/my_databaseUse dotenvx for command substitution.
Add the output of a command to one of your variables in your .env file.
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)$ dotenvx run --debug -- node index.js
⟐ injected env (1) from .env · [email protected]
DATABASE_URL postgres://yourusername@localhost/my_databaseUse dotenvx for encryption.
Add encryption to your .env files with a single command.
$ dotenvx set HELLO Production -f .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
⟐ injected env (2) from .env.production · [email protected]
Hello ProductionUse dotenvx to manage multiple environments.
Run any environment locally. Create a .env.ENVIRONMENT file and use -f to load it. It's straightforward, yet flexible.
$ echo "HELLO=production" > .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run -f=.env.production -- node index.js
Hello production
> ^^or with multiple .env files
$ echo "HELLO=local" > .env.local
$ echo "HELLO=World" > .env
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run -f=.env.local -f=.env -- node index.js
Hello localUse dotenvx for production deploys.
Create a .env.production file.
$ echo "HELLO=production" > .env.productionEncrypt it.
$ dotenvx encrypt -f .env.productionSet DOTENV_PRIVATE_KEY_PRODUCTION (found in .env.keys) on your server.
$ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION=valueCommit your .env.production file to code and deploy.
$ git add .env.production
$ git commit -m "encrypted .env.production"
$ git push heroku mainDotenvx will decrypt and inject the secrets at runtime using dotenvx run -- node index.js.
Use dotenvx to sync your .env files.
Encrypt them with dotenvx encrypt -f .env and safely include them in source control. Your secrets are securely synced with your git.
This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
More ExamplesSee examples of using dotenv with various frameworks, languages, and configurations.
No.
Unless you encrypt it with dotenvx. Then we recommend you do.
What about variable expansion?Use dotenvx.
Should I have multiple `.env` files?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 m