Repository: motdotla/dotenv
Branch: master
Commit: 4e5f0e9a08ab
Files: 30
Total size: 131.9 KB
Directory structure:
gitextract_wl236uti/
├── .editorconfig
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── .npmignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README-es.md
├── README.md
├── SECURITY.md
├── config.d.ts
├── config.js
├── lib/
│ ├── cli-options.js
│ ├── env-options.js
│ ├── main.d.ts
│ └── main.js
├── package.json
└── tests/
├── .env-multiline
├── test-cli-options.js
├── test-config-cli.js
├── test-config-vault.js
├── test-config.js
├── test-decrypt.js
├── test-env-options.js
├── test-parse-multiline.js
├── test-parse.js
├── test-populate.js
└── types/
├── test.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .github/FUNDING.yml
================================================
github: motdotla
custom: https://www.dotenvx.com
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x, 18.x, 20.x, 22.x, 24.x]
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
- run: npm run test:coverage
- name: codecov
uses: codecov/codecov-action@v3
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
================================================
FILE: .gitignore
================================================
.DS_Store
.nyc_output
.tap
coverage/
node_modules/
.idea/
.vscode
================================================
FILE: .npmignore
================================================
.github/
.nyc_output/
coverage/
examples/
flow-typed/
tests/
types/
.editorconfig
.flowconfig
.npmignore
.travis.yml
appveyor.yml
CONTRIBUTING.md
dotenv.png
dotenv.svg
tea.yaml
.tap/
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [Unreleased](https://github.com/motdotla/dotenv/compare/v17.3.1...master)
## [17.3.1](https://github.com/motdotla/dotenv/compare/v17.3.0...v17.3.1) (2026-02-12)
### Changed
* Fix as2 example command in README and update spanish README
## [17.3.0](https://github.com/motdotla/dotenv/compare/v17.2.4...v17.3.0) (2026-02-12)
### Added
* Add a new README section on dotenv’s approach to the agentic future.
### Changed
* Rewrite README to get humans started more quickly with less noise while simultaneously making more accessible for llms and agents to go deeper into details.
## [17.2.4](https://github.com/motdotla/dotenv/compare/v17.2.3...v17.2.4) (2026-02-05)
### Changed
* Make `DotenvPopulateInput` accept `NodeJS.ProcessEnv` type ([#915](https://github.com/motdotla/dotenv/pull/915))
- Give back to dotenv by checking out my newest project [vestauth](https://github.com/vestauth/vestauth). It is auth for agents. Thank you for using my software.
## [17.2.3](https://github.com/motdotla/dotenv/compare/v17.2.2...v17.2.3) (2025-09-29)
### Changed
* Fixed typescript error definition ([#912](https://github.com/motdotla/dotenv/pull/912))
## [17.2.2](https://github.com/motdotla/dotenv/compare/v17.2.1...v17.2.2) (2025-09-02)
### Added
- 🙏 A big thank you to new sponsor [Tuple.app](https://tuple.app/dotenv) - *the premier screen sharing app for developers on macOS and Windows.* Go check them out. It's wonderful and generous of them to give back to open source by sponsoring dotenv. Give them some love back.
## [17.2.1](https://github.com/motdotla/dotenv/compare/v17.2.0...v17.2.1) (2025-07-24)
### Changed
* Fix clickable tip links by removing parentheses ([#897](https://github.com/motdotla/dotenv/pull/897))
## [17.2.0](https://github.com/motdotla/dotenv/compare/v17.1.0...v17.2.0) (2025-07-09)
### Added
* Optionally specify `DOTENV_CONFIG_QUIET=true` in your environment or `.env` file to quiet the runtime log ([#889](https://github.com/motdotla/dotenv/pull/889))
* Just like dotenv any `DOTENV_CONFIG_` environment variables take precedence over any code set options like `({quiet: false})`
```ini
# .env
DOTENV_CONFIG_QUIET=true
HELLO="World"
```
```js
// index.js
require('dotenv').config()
console.log(`Hello ${process.env.HELLO}`)
```
```sh
$ node index.js
Hello World
or
$ DOTENV_CONFIG_QUIET=true node index.js
```
## [17.1.0](https://github.com/motdotla/dotenv/compare/v17.0.1...v17.1.0) (2025-07-07)
### Added
* Add additional security and configuration tips to the runtime log ([#884](https://github.com/motdotla/dotenv/pull/884))
* Dim the tips text from the main injection information text
```js
const TIPS = [
'🔐 encrypt with dotenvx: https://dotenvx.com',
'🔐 prevent committing .env to code: https://dotenvx.com/precommit',
'🔐 prevent building .env in docker: https://dotenvx.com/prebuild',
'🛠️ run anywhere with `dotenvx run -- yourcommand`',
'⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }',
'⚙️ enable debug logging with { debug: true }',
'⚙️ override existing env vars with { override: true }',
'⚙️ suppress all logs with { quiet: true }',
'⚙️ write to custom object with { processEnv: myObject }',
'⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }'
]
```
## [17.0.1](https://github.com/motdotla/dotenv/compare/v17.0.0...v17.0.1) (2025-07-01)
### Changed
* Patched injected log to count only populated/set keys to process.env ([#879](https://github.com/motdotla/dotenv/pull/879))
## [17.0.0](https://github.com/motdotla/dotenv/compare/v16.6.1...v17.0.0) (2025-06-27)
### Changed
- Default `quiet` to false - informational (file and keys count) runtime log message shows by default ([#875](https://github.com/motdotla/dotenv/pull/875))
## [16.6.1](https://github.com/motdotla/dotenv/compare/v16.6.0...v16.6.1) (2025-06-27)
### Changed
- Default `quiet` to true – hiding the runtime log message ([#874](https://github.com/motdotla/dotenv/pull/874))
- NOTICE: 17.0.0 will be released with quiet defaulting to false. Use `config({ quiet: true })` to suppress.
- And check out the new [dotenvx](https://github.com/dotenvx/dotenvx). As coding workflows evolve and agents increasingly handle secrets, encrypted .env files offer a much safer way to deploy both agents and code together with secure secrets. Simply switch `require('dotenv').config()` for `require('@dotenvx/dotenvx').config()`.
## [16.6.0](https://github.com/motdotla/dotenv/compare/v16.5.0...v16.6.0) (2025-06-26)
### Added
- Default log helpful message `[dotenv@16.6.0] injecting env (1) from .env` ([#870](https://github.com/motdotla/dotenv/pull/870))
- Use `{ quiet: true }` to suppress
- Aligns dotenv more closely with [dotenvx](https://github.com/dotenvx/dotenvx).
## [16.5.0](https://github.com/motdotla/dotenv/compare/v16.4.7...v16.5.0) (2025-04-07)
### Added
- 🎉 Added new sponsor [Graphite](https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv) - *the AI developer productivity platform helping teams on GitHub ship higher quality software, faster*.
> [!TIP]
> **[Become a sponsor](https://github.com/sponsors/motdotla)**
>
> The dotenvx README is viewed thousands of times DAILY on GitHub and NPM.
> Sponsoring dotenv is a great way to get in front of developers and give back to the developer community at the same time.
### Changed
- Remove `_log` method. Use `_debug` [#862](https://github.com/motdotla/dotenv/pull/862)
## [16.4.7](https://github.com/motdotla/dotenv/compare/v16.4.6...v16.4.7) (2024-12-03)
### Changed
- Ignore `.tap` folder when publishing. (oops, sorry about that everyone. - @motdotla) [#848](https://github.com/motdotla/dotenv/pull/848)
## [16.4.6](https://github.com/motdotla/dotenv/compare/v16.4.5...v16.4.6) (2024-12-02)
### Changed
- Clean up stale dev dependencies [#847](https://github.com/motdotla/dotenv/pull/847)
- Various README updates clarifying usage and alternative solutions using [dotenvx](https://github.com/dotenvx/dotenvx)
## [16.4.5](https://github.com/motdotla/dotenv/compare/v16.4.4...v16.4.5) (2024-02-19)
### Changed
- 🐞 Fix recent regression when using `path` option. return to historical behavior: do not attempt to auto find `.env` if `path` set. (regression was introduced in `16.4.3`) [#814](https://github.com/motdotla/dotenv/pull/814)
## [16.4.4](https://github.com/motdotla/dotenv/compare/v16.4.3...v16.4.4) (2024-02-13)
### Changed
- 🐞 Replaced chaining operator `?.` with old school `&&` (fixing node 12 failures) [#812](https://github.com/motdotla/dotenv/pull/812)
## [16.4.3](https://github.com/motdotla/dotenv/compare/v16.4.2...v16.4.3) (2024-02-12)
### Changed
- Fixed processing of multiple files in `options.path` [#805](https://github.com/motdotla/dotenv/pull/805)
## [16.4.2](https://github.com/motdotla/dotenv/compare/v16.4.1...v16.4.2) (2024-02-10)
### Changed
- Changed funding link in package.json to [`dotenvx.com`](https://dotenvx.com)
## [16.4.1](https://github.com/motdotla/dotenv/compare/v16.4.0...v16.4.1) (2024-01-24)
- Patch support for array as `path` option [#797](https://github.com/motdotla/dotenv/pull/797)
## [16.4.0](https://github.com/motdotla/dotenv/compare/v16.3.2...v16.4.0) (2024-01-23)
- Add `error.code` to error messages around `.env.vault` decryption handling [#795](https://github.com/motdotla/dotenv/pull/795)
- Add ability to find `.env.vault` file when filename(s) passed as an array [#784](https://github.com/motdotla/dotenv/pull/784)
## [16.3.2](https://github.com/motdotla/dotenv/compare/v16.3.1...v16.3.2) (2024-01-18)
### Added
- Add debug message when no encoding set [#735](https://github.com/motdotla/dotenv/pull/735)
### Changed
- Fix output typing for `populate` [#792](https://github.com/motdotla/dotenv/pull/792)
- Use subarray instead of slice [#793](https://github.com/motdotla/dotenv/pull/793)
## [16.3.1](https://github.com/motdotla/dotenv/compare/v16.3.0...v16.3.1) (2023-06-17)
### Added
- Add missing type definitions for `processEnv` and `DOTENV_KEY` options. [#756](https://github.com/motdotla/dotenv/pull/756)
## [16.3.0](https://github.com/motdotla/dotenv/compare/v16.2.0...v16.3.0) (2023-06-16)
### Added
- Optionally pass `DOTENV_KEY` to options rather than relying on `process.env.DOTENV_KEY`. Defaults to `process.env.DOTENV_KEY` [#754](https://github.com/motdotla/dotenv/pull/754)
## [16.2.0](https://github.com/motdotla/dotenv/compare/v16.1.4...v16.2.0) (2023-06-15)
### Added
- Optionally write to your own target object rather than `process.env`. Defaults to `process.env`. [#753](https://github.com/motdotla/dotenv/pull/753)
- Add import type URL to types file [#751](https://github.com/motdotla/dotenv/pull/751)
## [16.1.4](https://github.com/motdotla/dotenv/compare/v16.1.3...v16.1.4) (2023-06-04)
### Added
- Added `.github/` to `.npmignore` [#747](https://github.com/motdotla/dotenv/pull/747)
## [16.1.3](https://github.com/motdotla/dotenv/compare/v16.1.2...v16.1.3) (2023-05-31)
### Removed
- Removed `browser` keys for `path`, `os`, and `crypto` in package.json. These were set to false incorrectly as of 16.1. Instead, if using dotenv on the front-end make sure to include polyfills for `path`, `os`, and `crypto`. [node-polyfill-webpack-plugin](https://github.com/Richienb/node-polyfill-webpack-plugin) provides these.
## [16.1.2](https://github.com/motdotla/dotenv/compare/v16.1.1...v16.1.2) (2023-05-31)
### Changed
- Exposed private function `_configDotenv` as `configDotenv`. [#744](https://github.com/motdotla/dotenv/pull/744)
## [16.1.1](https://github.com/motdotla/dotenv/compare/v16.1.0...v16.1.1) (2023-05-30)
### Added
- Added type definition for `decrypt` function
### Changed
- Fixed `{crypto: false}` in `packageJson.browser`
## [16.1.0](https://github.com/motdotla/dotenv/compare/v16.0.3...v16.1.0) (2023-05-30)
### Added
- Add `populate` convenience method [#733](https://github.com/motdotla/dotenv/pull/733)
- Accept URL as path option [#720](https://github.com/motdotla/dotenv/pull/720)
- Add dotenv to `npm fund` command
- Spanish language README [#698](https://github.com/motdotla/dotenv/pull/698)
- Add `.env.vault` support. 🎉 ([#730](https://github.com/motdotla/dotenv/pull/730))
ℹ️ `.env.vault` extends the `.env` file format standard with a localized encrypted vault file. Package it securely with your production code deploys. It's cloud agnostic so that you can deploy your secrets anywhere – without [risky third-party integrations](https://techcrunch.com/2023/01/05/circleci-breach/). [read more](https://github.com/motdotla/dotenv#-deploying)
### Changed
- Fixed "cannot resolve 'fs'" error on tools like Replit [#693](https://github.com/motdotla/dotenv/pull/693)
## [16.0.3](https://github.com/motdotla/dotenv/compare/v16.0.2...v16.0.3) (2022-09-29)
### Changed
- Added library version to debug logs ([#682](https://github.com/motdotla/dotenv/pull/682))
## [16.0.2](https://github.com/motdotla/dotenv/compare/v16.0.1...v16.0.2) (2022-08-30)
### Added
- Export `env-options.js` and `cli-options.js` in package.json for use with downstream [dotenv-expand](https://github.com/motdotla/dotenv-expand) module
## [16.0.1](https://github.com/motdotla/dotenv/compare/v16.0.0...v16.0.1) (2022-05-10)
### Changed
- Minor README clarifications
- Development ONLY: updated devDependencies as recommended for development only security risks ([#658](https://github.com/motdotla/dotenv/pull/658))
## [16.0.0](https://github.com/motdotla/dotenv/compare/v15.0.1...v16.0.0) (2022-02-02)
### Added
- _Breaking:_ Backtick support 🎉 ([#615](https://github.com/motdotla/dotenv/pull/615))
If you had values containing the backtick character, please quote those values with either single or double quotes.
## [15.0.1](https://github.com/motdotla/dotenv/compare/v15.0.0...v15.0.1) (2022-02-02)
### Changed
- Properly parse empty single or double quoted values 🐞 ([#614](https://github.com/motdotla/dotenv/pull/614))
## [15.0.0](https://github.com/motdotla/dotenv/compare/v14.3.2...v15.0.0) (2022-01-31)
`v15.0.0` is a major new release with some important breaking changes.
### Added
- _Breaking:_ Multiline parsing support (just works. no need for the flag.)
### Changed
- _Breaking:_ `#` marks the beginning of a comment (UNLESS the value is wrapped in quotes. Please update your `.env` files to wrap in quotes any values containing `#`. For example: `SECRET_HASH="something-with-a-#-hash"`).
..Understandably, (as some teams have noted) this is tedious to do across the entire team. To make it less tedious, we recommend using [dotenv cli](https://github.com/dotenv-org/cli) going forward. It's an optional plugin that will keep your `.env` files in sync between machines, environments, or team members.
### Removed
- _Breaking:_ Remove multiline option (just works out of the box now. no need for the flag.)
## [14.3.2](https://github.com/motdotla/dotenv/compare/v14.3.1...v14.3.2) (2022-01-25)
### Changed
- Preserve backwards compatibility on values containing `#` 🐞 ([#603](https://github.com/motdotla/dotenv/pull/603))
## [14.3.1](https://github.com/motdotla/dotenv/compare/v14.3.0...v14.3.1) (2022-01-25)
### Changed
- Preserve backwards compatibility on exports by re-introducing the prior in-place exports 🐞 ([#606](https://github.com/motdotla/dotenv/pull/606))
## [14.3.0](https://github.com/motdotla/dotenv/compare/v14.2.0...v14.3.0) (2022-01-24)
### Added
- Add `multiline` option 🎉 ([#486](https://github.com/motdotla/dotenv/pull/486))
## [14.2.0](https://github.com/motdotla/dotenv/compare/v14.1.1...v14.2.0) (2022-01-17)
### Added
- Add `dotenv_config_override` cli option
- Add `DOTENV_CONFIG_OVERRIDE` command line env option
## [14.1.1](https://github.com/motdotla/dotenv/compare/v14.1.0...v14.1.1) (2022-01-17)
### Added
- Add React gotcha to FAQ on README
## [14.1.0](https://github.com/motdotla/dotenv/compare/v14.0.1...v14.1.0) (2022-01-17)
### Added
- Add `override` option 🎉 ([#595](https://github.com/motdotla/dotenv/pull/595))
## [14.0.1](https://github.com/motdotla/dotenv/compare/v14.0.0...v14.0.1) (2022-01-16)
### Added
- Log error on failure to load `.env` file ([#594](https://github.com/motdotla/dotenv/pull/594))
## [14.0.0](https://github.com/motdotla/dotenv/compare/v13.0.1...v14.0.0) (2022-01-16)
### Added
- _Breaking:_ Support inline comments for the parser 🎉 ([#568](https://github.com/motdotla/dotenv/pull/568))
## [13.0.1](https://github.com/motdotla/dotenv/compare/v13.0.0...v13.0.1) (2022-01-16)
### Changed
* Hide comments and newlines from debug output ([#404](https://github.com/motdotla/dotenv/pull/404))
## [13.0.0](https://github.com/motdotla/dotenv/compare/v12.0.4...v13.0.0) (2022-01-16)
### Added
* _Breaking:_ Add type file for `config.js` ([#539](https://github.com/motdotla/dotenv/pull/539))
## [12.0.4](https://github.com/motdotla/dotenv/compare/v12.0.3...v12.0.4) (2022-01-16)
### Changed
* README updates
* Minor order adjustment to package json format
## [12.0.3](https://github.com/motdotla/dotenv/compare/v12.0.2...v12.0.3) (2022-01-15)
### Changed
* Simplified jsdoc for consistency across editors
## [12.0.2](https://github.com/motdotla/dotenv/compare/v12.0.1...v12.0.2) (2022-01-15)
### Changed
* Improve embedded jsdoc type documentation
## [12.0.1](https://github.com/motdotla/dotenv/compare/v12.0.0...v12.0.1) (2022-01-15)
### Changed
* README updates and clarifications
## [12.0.0](https://github.com/motdotla/dotenv/compare/v11.0.0...v12.0.0) (2022-01-15)
### Removed
- _Breaking:_ drop support for Flow static type checker ([#584](https://github.com/motdotla/dotenv/pull/584))
### Changed
- Move types/index.d.ts to lib/main.d.ts ([#585](https://github.com/motdotla/dotenv/pull/585))
- Typescript cleanup ([#587](https://github.com/motdotla/dotenv/pull/587))
- Explicit typescript inclusion in package.json ([#566](https://github.com/motdotla/dotenv/pull/566))
## [11.0.0](https://github.com/motdotla/dotenv/compare/v10.0.0...v11.0.0) (2022-01-11)
### Changed
- _Breaking:_ drop support for Node v10 ([#558](https://github.com/motdotla/dotenv/pull/558))
- Patch debug option ([#550](https://github.com/motdotla/dotenv/pull/550))
## [10.0.0](https://github.com/motdotla/dotenv/compare/v9.0.2...v10.0.0) (2021-05-20)
### Added
- Add generic support to parse function
- Allow for import "dotenv/config.js"
- Add support to resolve home directory in path via ~
## [9.0.2](https://github.com/motdotla/dotenv/compare/v9.0.1...v9.0.2) (2021-05-10)
### Changed
- Support windows newlines with debug mode
## [9.0.1](https://github.com/motdotla/dotenv/compare/v9.0.0...v9.0.1) (2021-05-08)
### Changed
- Updates to README
## [9.0.0](https://github.com/motdotla/dotenv/compare/v8.6.0...v9.0.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8
## [8.6.0](https://github.com/motdotla/dotenv/compare/v8.5.1...v8.6.0) (2021-05-05)
### Added
- define package.json in exports
## [8.5.1](https://github.com/motdotla/dotenv/compare/v8.5.0...v8.5.1) (2021-05-05)
### Changed
- updated dev dependencies via npm audit
## [8.5.0](https://github.com/motdotla/dotenv/compare/v8.4.0...v8.5.0) (2021-05-05)
### Added
- allow for `import "dotenv/config"`
## [8.4.0](https://github.com/motdotla/dotenv/compare/v8.3.0...v8.4.0) (2021-05-05)
### Changed
- point to exact types file to work with VS Code
## [8.3.0](https://github.com/motdotla/dotenv/compare/v8.2.0...v8.3.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8 (mistake to be released as minor bump. later bumped to 9.0.0. see above.)
## [8.2.0](https://github.com/motdotla/dotenv/compare/v8.1.0...v8.2.0) (2019-10-16)
### Added
- TypeScript types
## [8.1.0](https://github.com/motdotla/dotenv/compare/v8.0.0...v8.1.0) (2019-08-18)
### Changed
- _Breaking:_ drop support for Node v6 ([#392](https://github.com/motdotla/dotenv/issues/392))
# [8.0.0](https://github.com/motdotla/dotenv/compare/v7.0.0...v8.0.0) (2019-05-02)
### Changed
- _Breaking:_ drop support for Node v6 ([#302](https://github.com/motdotla/dotenv/issues/392))
## [7.0.0] - 2019-03-12
### Fixed
- Fix removing unbalanced quotes ([#376](https://github.com/motdotla/dotenv/pull/376))
### Removed
- Removed `load` alias for `config` for consistency throughout code and documentation.
## [6.2.0] - 2018-12-03
### Added
- Support preload configuration via environment variables ([#351](https://github.com/motdotla/dotenv/issues/351))
## [6.1.0] - 2018-10-08
### Added
- `debug` option for `config` and `parse` methods will turn on logging
## [6.0.0] - 2018-06-02
### Changed
- _Breaking:_ drop support for Node v4 ([#304](https://github.com/motdotla/dotenv/pull/304))
## [5.0.0] - 2018-01-29
### Added
- Testing against Node v8 and v9
- Documentation on trim behavior of values
- Documentation on how to use with `import`
### Changed
- _Breaking_: default `path` is now `path.resolve(process.cwd(), '.env')`
- _Breaking_: does not write over keys already in `process.env` if the key has a falsy value
- using `const` and `let` instead of `var`
### Removed
- Testing against Node v7
## [4.0.0] - 2016-12-23
### Changed
- Return Object with parsed content or error instead of false ([#165](https://github.com/motdotla/dotenv/pull/165)).
### Removed
- `verbose` option removed in favor of returning result.
## [3.0.0] - 2016-12-20
### Added
- `verbose` option will log any error messages. Off by default.
- parses email addresses correctly
- allow importing config method directly in ES6
### Changed
- Suppress error messages by default ([#154](https://github.com/motdotla/dotenv/pull/154))
- Ignoring more files for NPM to make package download smaller
### Fixed
- False positive test due to case-sensitive variable ([#124](https://github.com/motdotla/dotenv/pull/124))
### Removed
- `silent` option removed in favor of `verbose`
## [2.0.0] - 2016-01-20
### Added
- CHANGELOG to ["make it easier for users and contributors to see precisely what notable changes have been made between each release"](http://keepachangelog.com/). Linked to from README
- LICENSE to be more explicit about what was defined in `package.json`. Linked to from README
- Testing nodejs v4 on travis-ci
- added examples of how to use dotenv in different ways
- return parsed object on success rather than boolean true
### Changed
- README has shorter description not referencing ruby gem since we don't have or want feature parity
### Removed
- Variable expansion and escaping so environment variables are encouraged to be fully orthogonal
## [1.2.0] - 2015-06-20
### Added
- Preload hook to require dotenv without including it in your code
### Changed
- clarified license to be "BSD-2-Clause" in `package.json`
### Fixed
- retain spaces in string vars
## [1.1.0] - 2015-03-31
### Added
- Silent option to silence `console.log` when `.env` missing
## [1.0.0] - 2015-03-13
### Removed
- support for multiple `.env` files. should always use one `.env` file for the current environment
[7.0.0]: https://github.com/motdotla/dotenv/compare/v6.2.0...v7.0.0
[6.2.0]: https://github.com/motdotla/dotenv/compare/v6.1.0...v6.2.0
[6.1.0]: https://github.com/motdotla/dotenv/compare/v6.0.0...v6.1.0
[6.0.0]: https://github.com/motdotla/dotenv/compare/v5.0.0...v6.0.0
[5.0.0]: https://github.com/motdotla/dotenv/compare/v4.0.0...v5.0.0
[4.0.0]: https://github.com/motdotla/dotenv/compare/v3.0.0...v4.0.0
[3.0.0]: https://github.com/motdotla/dotenv/compare/v2.0.0...v3.0.0
[2.0.0]: https://github.com/motdotla/dotenv/compare/v1.2.0...v2.0.0
[1.2.0]: https://github.com/motdotla/dotenv/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/motdotla/dotenv/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/motdotla/dotenv/compare/v0.4.0...v1.0.0
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
1. [Fork it](https://help.github.com/articles/fork-a-repo/)
2. Install dependencies (`npm install`)
3. Create your feature branch (`git checkout -b my-new-feature`)
4. Commit your changes (`git commit -am 'Added some feature'`)
5. Test your changes (`npm test`)
6. Push to the branch (`git push origin my-new-feature`)
7. [Create new Pull Request](https://help.github.com/articles/creating-a-pull-request/)
## Testing
We use [TAP](https://github.com/tapjs/node-tap) to write tests. Run our test suite with this command:
```
npm test
```
## Code Style
We use [standard](https://www.npmjs.com/package/standard) and [editorconfig](http://editorconfig.org) to maintain code style and best practices. Please make sure your PR adheres to the guides by running:
```
npm run lint
```
================================================
FILE: LICENSE
================================================
Copyright (c) 2015, Scott Motte
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README-es.md
================================================
# dotenv [](https://www.npmjs.com/package/dotenv) [](https://www.npmjs.com/package/dotenv)
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
[Watch the tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g)
## Usage
Install it.
```sh
npm install dotenv --save
```
Create a `.env` file in the root of your project:
```ini
# .env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
And as early as possible in your application, import and configure dotenv:
```javascript
require('dotenv').config() // or import 'dotenv/config' if you're using ES6
...
console.log(process.env) // remove this after you've confirmed it is working
```
That's it. `process.env` now has the keys and values you defined in your `.env` file:
## Advanced
ES6
Import with [ES6](#how-do-i-use-dotenv-with-import):
```javascript
import 'dotenv/config'
```
ES6 import if you need to set config options:
```javascript
import dotenv from 'dotenv'
dotenv.config({ path: '/custom/path/to/.env' })
```
bun
```sh
bun add dotenv
```
yarn
```sh
yarn add dotenv
```
pnpm
```sh
pnpm 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.
```ini
# app/backend/.env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
Multiline Values
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternatively, you can double quote strings and use the `\n` character:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
Comments
Comments may be added to your file on their own line or inline:
```ini
# 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.
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.
```javascript
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' }
```
Preload
> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
>
> It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. – [motdotla](https://mot.la)
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_Variable Expansion
Use [dotenvx](https://github.com/dotenvx/dotenvx) for variable expansion.
Reference and expand variables already on your machine for use in your .env file.
```ini
# .env
USERNAME="username"
DATABASE_URL="postgres://${USERNAME}@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (2) from .env
DATABASE_URL postgres://username@localhost/my_database
```
Command Substitution
Use [dotenvx](https://github.com/dotenvx/dotenvx) for command substitution.
Add the output of a command to one of your variables in your .env file.
```ini
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (1) from .env
DATABASE_URL postgres://yourusername@localhost/my_database
```
Encryption
Use [dotenvx](https://github.com/dotenvx/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
[dotenvx] injecting env (2) from .env.production
Hello Production
```
[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
Multiple Environments
Use [dotenvx](https://github.com/dotenvx/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.
```bash
$ 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
```bash
$ 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 local
```
[more environment examples](https://dotenvx.com/docs/quickstart/environments)
Production
Use [dotenvx](https://github.com/dotenvx/dotenvx) for production deploys.
Create a `.env.production` file.
```sh
$ echo "HELLO=production" > .env.production
```
Encrypt it.
```sh
$ dotenvx encrypt -f .env.production
```
Set `DOTENV_PRIVATE_KEY_PRODUCTION` (found in `.env.keys`) on your server.
```
$ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION=value
```
Commit your `.env.production` file to code and deploy.
```
$ git add .env.production
$ git commit -m "encrypted .env.production"
$ git push heroku main
```
Dotenvx will decrypt and inject the secrets at runtime using `dotenvx run -- node index.js`.
Syncing
Use [dotenvx](https://github.com/dotenvx/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 Examples
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
## Agentes
> El software está cambiando, y dotenv debe cambiar con él—por eso construí [agentic secret storage (AS2)](https://dotenvx.com/as2). Los agentes ejecutan código sin humanos en la terminal, por lo que los archivos `.env` en texto plano son el primitivo equivocado.
>
> AS2 está diseñado para software autónomo: cifrado por defecto, cero acceso a consola y entrega priorizando la criptografía que mantiene a los operadores fuera del circuito.
>
> Está respaldado por [Vestauth](https://github.com/vestauth/vestauth), la capa de autenticación pionera y de confianza para agentes—que otorga a cada agente una identidad criptográfica para firmar solicitudes con claves privadas y verificarlas con claves públicas. Sin secretos compartidos que se filtren.
>
> Es lo que uso ahora. - [motdotla](https://mot.la)
### Inicio rápido
Instala vestauth e inicializa tu agente.
```bash
npm i -g vestauth
vestauth agent init
```
Tu agente puede `set` secretos con un endpoint `curl` simple:
```bash
vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}'
```
Y tu agente puede `get` secretos con un endpoint `curl` simple:
```bash
vestauth agent curl "https://as2.dotenvx.com/get?key=KEY"
```
¡Eso es todo! Este nuevo primitivo habilita el acceso a secretos para agentes sin intervención humana, flujos de OAuth ni claves API. Es el futuro para los agentes.
## FAQ
Should I commit my `.env` file?
No.
Unless you encrypt it with [dotenvx](https://github.com/dotenvx/dotenvx). Then we recommend you do.
What about variable expansion?
Use [dotenvx](https://github.com/dotenvx/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 form `.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.
>
> – [The Twelve-Factor App](http://12factor.net/config)
Additionally, we recommend using [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt and manage these.
How do I use dotenv with `import`?
Simply..
```javascript
// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
```
A little background..
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
What does this mean in plain language? It means you would think the following would work but it won't.
`errorReporter.mjs`:
```js
class Client {
constructor (apiKey) {
console.log('apiKey', apiKey)
this.apiKey = apiKey
}
}
export default new Client(process.env.API_KEY)
```
`index.mjs`:
```js
// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
```
`process.env.API_KEY` will be blank.
Instead, `index.mjs` should be written as..
```js
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
```
Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
There are two alternatives to this approach:
1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
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:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
What rules does the parsing engine follow?
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
What about syncing and securing .env files?
Use [dotenvx](https://github.com/dotenvx/dotenvx) to unlock syncing encrypted .env files over git.
What if I accidentally commit my `.env` file to code?
Remove it, [remove git history](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) and then install the [git pre-commit hook](https://github.com/dotenvx/dotenvx#pre-commit) to prevent this from ever happening again.
```
npm i -g @dotenvx/dotenvx
dotenvx 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.
```javascript
require('dotenv').config({ override: true })
```
How can I prevent committing my `.env` file to a Docker build?
Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).
```bash
# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]
```
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`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) 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?
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Turn on debug mode and try again..
```js
require('dotenv').config({ debug: true })
```
You will receive a helpful error outputted to your console.
Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
```bash
npm install node-polyfill-webpack-plugin
```
Configure your `webpack.config.js` to something like the following.
```js
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};
```
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
## Docs
Dotenv exposes four functions:
* `config`
* `parse`
* `populate`
### Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
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.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
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.
```js
require('dotenv').config({ path: ['.env.local', '.env'] })
```
##### quiet
Default: `false`
Suppress runtime logging message.
```js
// index.js
require('dotenv').config({ quiet: false }) // change to true to suppress
console.log(`Hello ${process.env.HELLO}`)
```
```ini
# .env
HELLO=World
```
```sh
$ node index.js
[dotenv@17.0.0] injecting env (1) from .env
Hello World
```
##### encoding
Default: `utf8`
Specify the encoding of your file containing environment variables.
```js
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.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### override
Default: `false`
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.
```js
require('dotenv').config({ override: true })
```
##### processEnv
Default: `process.env`
Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
```js
const myObject = {}
require('dotenv').config({ processEnv: myObject })
console.log(myObject) // values from .env
console.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.
```js
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' }
```
#### Options
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
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.
For example, customizing the source:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)
console.log(process.env.HELLO) // world
```
For example, customizing the source AND target:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object
dotenv.populate(target, parsed, { override: true, debug: true })
console.log(target) // { HELLO: 'universe' }
```
#### options
##### Debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being populated as you expect.
##### override
Default: `false`
Override any environment variables that have already been set.
## CHANGELOG
See [CHANGELOG.md](CHANGELOG.md)
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
================================================
FILE: README.md
================================================
# dotenv [](https://www.npmjs.com/package/dotenv) [](https://www.npmjs.com/package/dotenv)
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
[Watch the tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g)
## Usage
Install it.
```sh
npm install dotenv --save
```
Create a `.env` file in the root of your project:
```ini
# .env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
And as early as possible in your application, import and configure dotenv:
```javascript
require('dotenv').config() // or import 'dotenv/config' if you're using ES6
...
console.log(process.env) // remove this after you've confirmed it is working
```
That's it. `process.env` now has the keys and values you defined in your `.env` file:
## Advanced
ES6
Import with [ES6](#how-do-i-use-dotenv-with-import):
```javascript
import 'dotenv/config'
```
ES6 import if you need to set config options:
```javascript
import dotenv from 'dotenv'
dotenv.config({ path: '/custom/path/to/.env' })
```
bun
```sh
bun add dotenv
```
yarn
```sh
yarn add dotenv
```
pnpm
```sh
pnpm 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.
```ini
# app/backend/.env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
Multiline Values
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternatively, you can double quote strings and use the `\n` character:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
Comments
Comments may be added to your file on their own line or inline:
```ini
# 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.
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.
```javascript
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' }
```
Preload
> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
>
> It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. – [motdotla](https://mot.la)
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_Variable Expansion
Use [dotenvx](https://github.com/dotenvx/dotenvx) for variable expansion.
Reference and expand variables already on your machine for use in your .env file.
```ini
# .env
USERNAME="username"
DATABASE_URL="postgres://${USERNAME}@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (2) from .env
DATABASE_URL postgres://username@localhost/my_database
```
Command Substitution
Use [dotenvx](https://github.com/dotenvx/dotenvx) for command substitution.
Add the output of a command to one of your variables in your .env file.
```ini
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (1) from .env
DATABASE_URL postgres://yourusername@localhost/my_database
```
Encryption
Use [dotenvx](https://github.com/dotenvx/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
[dotenvx] injecting env (2) from .env.production
Hello Production
```
[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
Multiple Environments
Use [dotenvx](https://github.com/dotenvx/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.
```bash
$ 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
```bash
$ 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 local
```
[more environment examples](https://dotenvx.com/docs/quickstart/environments)
Production
Use [dotenvx](https://github.com/dotenvx/dotenvx) for production deploys.
Create a `.env.production` file.
```sh
$ echo "HELLO=production" > .env.production
```
Encrypt it.
```sh
$ dotenvx encrypt -f .env.production
```
Set `DOTENV_PRIVATE_KEY_PRODUCTION` (found in `.env.keys`) on your server.
```
$ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION=value
```
Commit your `.env.production` file to code and deploy.
```
$ git add .env.production
$ git commit -m "encrypted .env.production"
$ git push heroku main
```
Dotenvx will decrypt and inject the secrets at runtime using `dotenvx run -- node index.js`.
Syncing
Use [dotenvx](https://github.com/dotenvx/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 Examples
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
## Agents
> Software is changing, and dotenv must change with it—that is why I built [agentic secret storage (AS2)](https://dotenvx.com/as2). Agents run code without humans at terminals, so plaintext `.env` files are the wrong primitive.
>
> AS2 is built for autonomous software: encrypted by default, zero console access, and cryptography‑first delivery that keeps operators out of the loop.
>
> It is backed by [Vestauth](https://github.com/vestauth/vestauth), the trusted, pioneering auth layer for agents—giving each agent a cryptographic identity so requests are signed with private keys and verified with public keys. No shared secrets to leak.
>
> It's what I'm using now. - [motdotla](https://mot.la)
### Quickstart
Install vestauth and initialize your agent.
```bash
npm i -g vestauth
vestauth agent init
```
Your agent `set`s secrets with a simple `curl` endpoint:
```bash
vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}'
```
And your agent `get`s secrets with a simple `curl` endpoint:
```bash
vestauth agent curl "https://as2.dotenvx.com/get?key=KEY"
```
That's it! This new primitive unlocks secrets access for agents without human-in-the-loop, oauth flows, or API keys. It's the future for agents.
## FAQ
Should I commit my `.env` file?
No.
Unless you encrypt it with [dotenvx](https://github.com/dotenvx/dotenvx). Then we recommend you do.
What about variable expansion?
Use [dotenvx](https://github.com/dotenvx/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.
>
> – [The Twelve-Factor App](http://12factor.net/config)
Additionally, we recommend using [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt and manage these.
How do I use dotenv with `import`?
Simply..
```javascript
// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
```
A little background..
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
What does this mean in plain language? It means you would think the following would work but it won't.
`errorReporter.mjs`:
```js
class Client {
constructor (apiKey) {
console.log('apiKey', apiKey)
this.apiKey = apiKey
}
}
export default new Client(process.env.API_KEY)
```
`index.mjs`:
```js
// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
```
`process.env.API_KEY` will be blank.
Instead, `index.mjs` should be written as..
```js
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
```
Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
There are two alternatives to this approach:
1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
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:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
What rules does the parsing engine follow?
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
What about syncing and securing .env files?
Use [dotenvx](https://github.com/dotenvx/dotenvx) to unlock syncing encrypted .env files over git.
What if I accidentally commit my `.env` file to code?
Remove it, [remove git history](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) and then install the [git pre-commit hook](https://github.com/dotenvx/dotenvx#pre-commit) to prevent this from ever happening again.
```
npm i -g @dotenvx/dotenvx
dotenvx 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.
```javascript
require('dotenv').config({ override: true })
```
How can I prevent committing my `.env` file to a Docker build?
Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).
```bash
# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]
```
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`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) 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?
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Turn on debug mode and try again..
```js
require('dotenv').config({ debug: true })
```
You will receive a helpful error outputted to your console.
Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
```bash
npm install node-polyfill-webpack-plugin
```
Configure your `webpack.config.js` to something like the following.
```js
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};
```
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
## Docs
Dotenv exposes four functions:
* `config`
* `parse`
* `populate`
### Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
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.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
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.
```js
require('dotenv').config({ path: ['.env.local', '.env'] })
```
##### quiet
Default: `false`
Suppress runtime logging message.
```js
// index.js
require('dotenv').config({ quiet: false }) // change to true to suppress
console.log(`Hello ${process.env.HELLO}`)
```
```ini
# .env
HELLO=World
```
```sh
$ node index.js
[dotenv@17.0.0] injecting env (1) from .env
Hello World
```
##### encoding
Default: `utf8`
Specify the encoding of your file containing environment variables.
```js
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.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### override
Default: `false`
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.
```js
require('dotenv').config({ override: true })
```
##### processEnv
Default: `process.env`
Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
```js
const myObject = {}
require('dotenv').config({ processEnv: myObject })
console.log(myObject) // values from .env
console.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.
```js
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' }
```
#### Options
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
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.
For example, customizing the source:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)
console.log(process.env.HELLO) // world
```
For example, customizing the source AND target:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object
dotenv.populate(target, parsed, { override: true, debug: true })
console.log(target) // { HELLO: 'universe' }
```
#### options
##### Debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being populated as you expect.
##### override
Default: `false`
Override any environment variables that have already been set.
## CHANGELOG
See [CHANGELOG.md](CHANGELOG.md)
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
================================================
FILE: SECURITY.md
================================================
Please report any security vulnerabilities to security@dotenvx.com.
================================================
FILE: config.d.ts
================================================
export {};
================================================
FILE: config.js
================================================
(function () {
require('./lib/main').config(
Object.assign(
{},
require('./lib/env-options'),
require('./lib/cli-options')(process.argv)
)
)
})()
================================================
FILE: lib/cli-options.js
================================================
const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/
module.exports = function optionMatcher (args) {
const options = args.reduce(function (acc, cur) {
const matches = cur.match(re)
if (matches) {
acc[matches[1]] = matches[2]
}
return acc
}, {})
if (!('quiet' in options)) {
options.quiet = 'true'
}
return options
}
================================================
FILE: lib/env-options.js
================================================
// ../config.js accepts options via environment variables
const options = {}
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH
}
if (process.env.DOTENV_CONFIG_QUIET != null) {
options.quiet = process.env.DOTENV_CONFIG_QUIET
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG
}
if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
options.override = process.env.DOTENV_CONFIG_OVERRIDE
}
if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY
}
module.exports = options
================================================
FILE: lib/main.d.ts
================================================
// TypeScript Version: 3.0
///
import type { URL } from 'url';
export interface DotenvParseOutput {
[name: string]: string;
}
export interface DotenvPopulateOutput {
[name: string]: string;
}
/**
* Parses a string or buffer in the .env file format into an object.
*
* See https://dotenvx.com/docs
*
* @param src - contents to be parsed. example: `'DB_HOST=localhost'`
* @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
*/
export function parse(
src: string | Buffer
): T;
export interface DotenvConfigOptions {
/**
* Default: `path.resolve(process.cwd(), '.env')`
*
* Specify a custom path if your file containing environment variables is located elsewhere.
* Can also be an array of strings, specifying multiple paths.
*
* example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
* example: `require('dotenv').config({ path: ['/path/to/first.env', '/path/to/second.env'] })`
*/
path?: string | string[] | URL;
/**
* Default: `utf8`
*
* Specify the encoding of your file containing environment variables.
*
* example: `require('dotenv').config({ encoding: 'latin1' })`
*/
encoding?: string;
/**
* Default: `false`
*
* Suppress all output (except errors).
*
* example: `require('dotenv').config({ quiet: true })`
*/
quiet?: boolean;
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
/**
* Default: `process.env`
*
* Specify an object to write your secrets to. Defaults to process.env environment variables.
*
* example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
*/
processEnv?: DotenvPopulateInput;
/**
* Default: `undefined`
*
* Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
*
* example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenvx.com/vault/.env.vault?environment=production' })`
*/
DOTENV_KEY?: string;
}
export interface DotenvConfigOutput {
error?: DotenvError;
parsed?: DotenvParseOutput;
}
type DotenvError = Error & {
code:
| 'MISSING_DATA'
| 'INVALID_DOTENV_KEY'
| 'NOT_FOUND_DOTENV_ENVIRONMENT'
| 'DECRYPTION_FAILED'
| 'OBJECT_REQUIRED';
}
export interface DotenvPopulateOptions {
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
}
export interface DotenvPopulateInput {
[name: string]: string | undefined;
}
/**
* Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `.env` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `source` json contents into `target` like process.env.
*
* See https://dotenvx.com/docs
*
* @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
* @param parsed - the source JSON object
* @param options - additional options. example: `{ quiet: false, debug: true, override: false }`
* @returns an object with the keys and values that were actually set
*
*/
export function populate(
processEnv: DotenvPopulateInput,
parsed: DotenvPopulateInput,
options?: DotenvConfigOptions
): DotenvPopulateOutput;
/**
* Decrypt ciphertext
*
* See https://dotenvx.com/docs
*
* @param encrypted - the encrypted ciphertext string
* @param keyStr - the decryption key string
* @returns {string}
*
*/
export function decrypt(encrypted: string, keyStr: string): string;
================================================
FILE: lib/main.js
================================================
const fs = require('fs')
const path = require('path')
const os = require('os')
const crypto = require('crypto')
const packageJson = require('../package.json')
const version = packageJson.version
// Array of tips to display randomly
const TIPS = [
'🔐 encrypt with Dotenvx: https://dotenvx.com',
'🔐 prevent committing .env to code: https://dotenvx.com/precommit',
'🔐 prevent building .env in docker: https://dotenvx.com/prebuild',
'🤖 agentic secret storage: https://dotenvx.com/as2',
'⚡️ secrets for agents: https://dotenvx.com/as2',
'🛡️ auth for agents: https://vestauth.com',
'🛠️ run anywhere with `dotenvx run -- yourcommand`',
'⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }',
'⚙️ enable debug logging with { debug: true }',
'⚙️ override existing env vars with { override: true }',
'⚙️ suppress all logs with { quiet: true }',
'⚙️ write to custom object with { processEnv: myObject }',
'⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }'
]
// Get a random tip from the tips array
function _getRandomTip () {
return TIPS[Math.floor(Math.random() * TIPS.length)]
}
function parseBoolean (value) {
if (typeof value === 'string') {
return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase())
}
return Boolean(value)
}
function supportsAnsi () {
return process.stdout.isTTY // && process.env.TERM !== 'dumb'
}
function dim (text) {
return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text
}
const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
// Parse src into an Object
function parse (src) {
const obj = {}
// Convert buffer to string
let lines = src.toString()
// Convert line breaks to same format
lines = lines.replace(/\r\n?/mg, '\n')
let match
while ((match = LINE.exec(lines)) != null) {
const key = match[1]
// Default undefined or null to empty string
let value = (match[2] || '')
// Remove whitespace
value = value.trim()
// Check if double quoted
const maybeQuote = value[0]
// Remove surrounding quotes
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')
// Expand newlines if double quoted
if (maybeQuote === '"') {
value = value.replace(/\\n/g, '\n')
value = value.replace(/\\r/g, '\r')
}
// Add to object
obj[key] = value
}
return obj
}
function _parseVault (options) {
options = options || {}
const vaultPath = _vaultPath(options)
options.path = vaultPath // parse .env.vault
const result = DotenvModule.configDotenv(options)
if (!result.parsed) {
const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
err.code = 'MISSING_DATA'
throw err
}
// handle scenario for comma separated keys - for use with key rotation
// example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
const keys = _dotenvKey(options).split(',')
const length = keys.length
let decrypted
for (let i = 0; i < length; i++) {
try {
// Get full key
const key = keys[i].trim()
// Get instructions for decrypt
const attrs = _instructions(result, key)
// Decrypt
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)
break
} catch (error) {
// last key
if (i + 1 >= length) {
throw error
}
// try next key
}
}
// Parse decrypted .env string
return DotenvModule.parse(decrypted)
}
function _warn (message) {
console.error(`[dotenv@${version}][WARN] ${message}`)
}
function _debug (message) {
console.log(`[dotenv@${version}][DEBUG] ${message}`)
}
function _log (message) {
console.log(`[dotenv@${version}] ${message}`)
}
function _dotenvKey (options) {
// prioritize developer directly setting options.DOTENV_KEY
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY
}
// secondary infra already contains a DOTENV_KEY environment variable
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY
}
// fallback to empty string
return ''
}
function _instructions (result, dotenvKey) {
// Parse DOTENV_KEY. Format is a URI
let uri
try {
uri = new URL(dotenvKey)
} catch (error) {
if (error.code === 'ERR_INVALID_URL') {
const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
throw error
}
// Get decrypt key
const key = uri.password
if (!key) {
const err = new Error('INVALID_DOTENV_KEY: Missing key part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get environment
const environment = uri.searchParams.get('environment')
if (!environment) {
const err = new Error('INVALID_DOTENV_KEY: Missing environment part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get ciphertext payload
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`
const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION
if (!ciphertext) {
const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'
throw err
}
return { ciphertext, key }
}
function _vaultPath (options) {
let possibleVaultPath = null
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`
}
}
} else {
possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`
}
} else {
possibleVaultPath = path.resolve(process.cwd(), '.env.vault')
}
if (fs.existsSync(possibleVaultPath)) {
return possibleVaultPath
}
return null
}
function _resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}
function _configVault (options) {
const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug))
const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet))
if (debug || !quiet) {
_log('Loading env from encrypted .env.vault')
}
const parsed = DotenvModule._parseVault(options)
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
DotenvModule.populate(processEnv, parsed, options)
return { parsed }
}
function configDotenv (options) {
const dotenvPath = path.resolve(process.cwd(), '.env')
let encoding = 'utf8'
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug))
let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet))
if (options && options.encoding) {
encoding = options.encoding
} else {
if (debug) {
_debug('No encoding is specified. UTF-8 is used by default')
}
}
let optionPaths = [dotenvPath] // default, look for .env
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)]
} else {
optionPaths = [] // reset default
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath))
}
}
}
// Build the parsed data in a temporary object (because we need to return it). Once we have the final
// parsed data, we will combine it with process.env (or options.processEnv if provided).
let lastError
const parsedAll = {}
for (const path of optionPaths) {
try {
// Specifying an encoding returns a string instead of a buffer
const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))
DotenvModule.populate(parsedAll, parsed, options)
} catch (e) {
if (debug) {
_debug(`Failed to load ${path} ${e.message}`)
}
lastError = e
}
}
const populated = DotenvModule.populate(processEnv, parsedAll, options)
// handle user settings DOTENV_CONFIG_ options inside .env file(s)
debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug)
quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet)
if (debug || !quiet) {
const keysCount = Object.keys(populated).length
const shortPaths = []
for (const filePath of optionPaths) {
try {
const relative = path.relative(process.cwd(), filePath)
shortPaths.push(relative)
} catch (e) {
if (debug) {
_debug(`Failed to load ${filePath} ${e.message}`)
}
lastError = e
}
}
_log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`)
}
if (lastError) {
return { parsed: parsedAll, error: lastError }
} else {
return { parsed: parsedAll }
}
}
// Populates process.env from .env file
function config (options) {
// fallback to original dotenv if DOTENV_KEY is not set
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options)
}
const vaultPath = _vaultPath(options)
// dotenvKey exists but .env.vault file does not exist
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)
return DotenvModule.configDotenv(options)
}
return DotenvModule._configVault(options)
}
function decrypt (encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), 'hex')
let ciphertext = Buffer.from(encrypted, 'base64')
const nonce = ciphertext.subarray(0, 12)
const authTag = ciphertext.subarray(-16)
ciphertext = ciphertext.subarray(12, -16)
try {
const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)
aesgcm.setAuthTag(authTag)
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
} catch (error) {
const isRange = error instanceof RangeError
const invalidKeyLength = error.message === 'Invalid key length'
const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'
if (isRange || invalidKeyLength) {
const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')
err.code = 'INVALID_DOTENV_KEY'
throw err
} else if (decryptionFailed) {
const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')
err.code = 'DECRYPTION_FAILED'
throw err
} else {
throw error
}
}
}
// Populate process.env with parsed values
function populate (processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug)
const override = Boolean(options && options.override)
const populated = {}
if (typeof parsed !== 'object') {
const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
err.code = 'OBJECT_REQUIRED'
throw err
}
// Set process.env
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key]
populated[key] = parsed[key]
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`)
} else {
_debug(`"${key}" is already defined and was NOT overwritten`)
}
}
} else {
processEnv[key] = parsed[key]
populated[key] = parsed[key]
}
}
return populated
}
const DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse,
populate
}
module.exports.configDotenv = DotenvModule.configDotenv
module.exports._configVault = DotenvModule._configVault
module.exports._parseVault = DotenvModule._parseVault
module.exports.config = DotenvModule.config
module.exports.decrypt = DotenvModule.decrypt
module.exports.parse = DotenvModule.parse
module.exports.populate = DotenvModule.populate
module.exports = DotenvModule
================================================
FILE: package.json
================================================
{
"name": "dotenv",
"version": "17.3.1",
"description": "Loads environment variables from .env file",
"main": "lib/main.js",
"types": "lib/main.d.ts",
"exports": {
".": {
"types": "./lib/main.d.ts",
"require": "./lib/main.js",
"default": "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
"scripts": {
"dts-check": "tsc --project tests/types/tsconfig.json",
"lint": "standard",
"pretest": "npm run lint && npm run dts-check",
"test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
"test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
"prerelease": "npm test",
"release": "standard-version"
},
"repository": {
"type": "git",
"url": "git://github.com/motdotla/dotenv.git"
},
"homepage": "https://github.com/motdotla/dotenv#readme",
"funding": "https://dotenvx.com",
"keywords": [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
"readmeFilename": "README.md",
"license": "BSD-2-Clause",
"devDependencies": {
"@types/node": "^18.11.3",
"decache": "^4.6.2",
"sinon": "^14.0.1",
"standard": "^17.0.0",
"standard-version": "^9.5.0",
"tap": "^19.2.0",
"typescript": "^4.8.4"
},
"engines": {
"node": ">=12"
},
"browser": {
"fs": false
}
}
================================================
FILE: tests/.env-multiline
================================================
BASIC=basic
# previous line intentionally left blank
AFTER_LINE=after_line
EMPTY=
SINGLE_QUOTES='single_quotes'
SINGLE_QUOTES_SPACED=' single quotes '
DOUBLE_QUOTES="double_quotes"
DOUBLE_QUOTES_SPACED=" double quotes "
EXPAND_NEWLINES="expand\nnew\nlines"
DONT_EXPAND_UNQUOTED=dontexpand\nnewlines
DONT_EXPAND_SQUOTED='dontexpand\nnewlines'
# COMMENTS=work
EQUAL_SIGNS=equals==
RETAIN_INNER_QUOTES={"foo": "bar"}
RETAIN_INNER_QUOTES_AS_STRING='{"foo": "bar"}'
TRIM_SPACE_FROM_UNQUOTED= some spaced out string
USERNAME=therealnerdybeast@example.tld
SPACED_KEY = parsed
MULTI_DOUBLE_QUOTED="THIS
IS
A
MULTILINE
STRING"
MULTI_SINGLE_QUOTED='THIS
IS
A
MULTILINE
STRING'
MULTI_BACKTICKED=`THIS
IS
A
"MULTILINE'S"
STRING`
MULTI_PEM_DOUBLE_QUOTED="-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnNl1tL3QjKp3DZWM0T3u
LgGJQwu9WqyzHKZ6WIA5T+7zPjO1L8l3S8k8YzBrfH4mqWOD1GBI8Yjq2L1ac3Y/
bTdfHN8CmQr2iDJC0C6zY8YV93oZB3x0zC/LPbRYpF8f6OqX1lZj5vo2zJZy4fI/
kKcI5jHYc8VJq+KCuRZrvn+3V+KuL9tF9v8ZgjF2PZbU+LsCy5Yqg1M8f5Jp5f6V
u4QuUoobAgMBAAE=
-----END PUBLIC KEY-----"
================================================
FILE: tests/test-cli-options.js
================================================
const t = require('tap')
const options = require('../lib/cli-options')
// matches encoding option
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_encoding=utf8']), {
encoding: 'utf8',
quiet: 'true'
})
// matches path option
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_path=/custom/path/to/your/env/vars']), {
path: '/custom/path/to/your/env/vars',
quiet: 'true'
})
// matches debug option
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_debug=true']), {
debug: 'true',
quiet: 'true'
})
// matches override option
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_override=true']), {
override: 'true',
quiet: 'true'
})
// ignores empty values
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_path=']), { quiet: 'true' })
// ignores unsupported options
t.same(options(['node', '-e', "'console.log(testing)'", 'dotenv_config_foo=bar']), { quiet: 'true' })
================================================
FILE: tests/test-config-cli.js
================================================
const cp = require('child_process')
const path = require('path')
const t = require('tap')
function spawn (cmd, options = {}) {
const { stdout } = cp.spawnSync(
process.argv[0], // node binary
cmd,
Object.assign(
{},
{
cwd: path.resolve(__dirname, '..'),
timeout: 5000,
encoding: 'utf8'
},
options
)
)
return stdout
}
t.plan(3)
// dotenv/config enables preloading
t.equal(
spawn(
[
'-r',
'./config',
'-e',
'console.log(process.env.BASIC)',
'dotenv_config_encoding=utf8',
'dotenv_config_path=./tests/.env'
]
),
'basic\n'
)
// dotenv/config supports configuration via environment variables
t.equal(
spawn(
[
'-r',
'./config',
'-e',
'console.log(process.env.BASIC)'
],
{
env: {
DOTENV_CONFIG_PATH: './tests/.env'
}
}
),
'basic\n'
)
// dotenv/config takes CLI configuration over environment variables
t.equal(
spawn(
[
'-r',
'./config',
'-e',
'console.log(process.env.BASIC)',
'dotenv_config_path=./tests/.env'
],
{
env: {
DOTENV_CONFIG_PATH: '/tmp/dne/path/.env.should.break'
}
}
),
'basic\n'
)
================================================
FILE: tests/test-config-vault.js
================================================
const fs = require('fs')
const crypto = require('crypto')
const sinon = require('sinon')
const t = require('tap')
const dotenv = require('../lib/main')
const testPath = 'tests/.env'
const dotenvKey = 'dotenv://:key_ddcaa26504cd70a6fef9801901c3981538563a1767c297cb8416e8a38c62fe00@dotenvx.com/vault/.env.vault?environment=development'
let envStub
let logStub
t.beforeEach(() => {
process.env.DOTENV_KEY = ''
envStub = sinon.stub(process.env, 'DOTENV_KEY').value(dotenvKey)
})
t.afterEach(() => {
envStub.restore()
if (logStub) {
logStub.restore()
}
})
t.test('does log when testPath calls to .env.vault directly (interpret what the user meant)', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config({ path: `${testPath}.vault` })
ct.ok(logStub.called)
})
t.test('warns if DOTENV_KEY exists but .env.vault does not exist', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
const existsSync = sinon.stub(fs, 'existsSync').returns(false) // make .env.vault not exist
dotenv.config({ path: testPath })
ct.ok(logStub.called)
existsSync.restore()
ct.end()
})
t.test('warns if DOTENV_KEY exists but .env.vault does not exist (set as array)', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
const existsSync = sinon.stub(fs, 'existsSync').returns(false) // make .env.vault not exist
dotenv.config({ path: [testPath] })
ct.ok(logStub.called)
existsSync.restore()
ct.end()
})
t.test('logs when testPath calls to .env.vault directly (interpret what the user meant) and debug true', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config({ path: `${testPath}.vault`, debug: true })
ct.ok(logStub.called)
})
t.test('returns parsed object', ct => {
ct.plan(1)
const env = dotenv.config({ path: testPath })
ct.same(env.parsed, { ALPHA: 'zeta' })
ct.end()
})
t.test('returns parsed object (set path as array)', ct => {
ct.plan(1)
const env = dotenv.config({ path: [testPath] })
ct.same(env.parsed, { ALPHA: 'zeta' })
ct.end()
})
t.test('returns parsed object (set path as mulit-array)', ct => {
ct.plan(1)
const env = dotenv.config({ path: ['tests/.env.local', 'tests/.env'] })
ct.same(env.parsed, { ALPHA: 'zeta' })
ct.end()
})
t.test('returns parsed object (set path as array with .vault extension)', ct => {
ct.plan(1)
const env = dotenv.config({ path: [`${testPath}.vault`] })
ct.same(env.parsed, { ALPHA: 'zeta' })
ct.end()
})
t.test('throws not found if .env.vault is empty', ct => {
ct.plan(2)
const readFileSync = sinon.stub(fs, 'readFileSync').returns('') // empty file
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment DOTENV_VAULT_DEVELOPMENT in your .env.vault file.')
ct.equal(e.code, 'NOT_FOUND_DOTENV_ENVIRONMENT')
}
readFileSync.restore()
ct.end()
})
t.test('throws missing data when somehow parsed badly', ct => {
ct.plan(2)
const configDotenvStub = sinon.stub(dotenv, 'configDotenv').returns({ parsed: undefined })
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'MISSING_DATA: Cannot parse tests/.env.vault for an unknown reason')
ct.equal(e.code, 'MISSING_DATA')
}
configDotenvStub.restore()
ct.end()
})
t.test('throws error when invalid formed DOTENV_KEY', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('invalid-format-non-uri-format')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')
ct.equal(e.code, 'INVALID_DOTENV_KEY')
}
ct.end()
})
t.test('throws error when invalid formed DOTENV_KEY that otherwise is not caught', ct => {
ct.plan(1)
const urlStub = sinon.stub(global, 'URL')
urlStub.callsFake(() => {
throw new Error('uncaught error')
})
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'uncaught error')
}
urlStub.restore()
ct.end()
})
t.test('throws error when DOTENV_KEY missing password', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('dotenv://username@dotenvx.com/vault/.env.vault?environment=development')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'INVALID_DOTENV_KEY: Missing key part')
ct.equal(e.code, 'INVALID_DOTENV_KEY')
}
ct.end()
})
t.test('throws error when DOTENV_KEY missing environment', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('dotenv://:key_ddcaa26504cd70a6fef9801901c3981538563a1767c297cb8416e8a38c62fe00@dotenvx.com/vault/.env.vault')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'INVALID_DOTENV_KEY: Missing environment part')
ct.equal(e.code, 'INVALID_DOTENV_KEY')
}
ct.end()
})
t.test('when DOTENV_KEY is empty string falls back to .env file', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('')
ct.plan(1)
const result = dotenv.config({ path: testPath })
ct.equal(result.parsed.BASIC, 'basic')
ct.end()
})
t.test('does not write over keys already in process.env by default', ct => {
ct.plan(2)
const existing = 'bar'
process.env.ALPHA = existing
const result = dotenv.config({ path: testPath })
ct.equal(result.parsed.ALPHA, 'zeta')
ct.equal(process.env.ALPHA, 'bar')
})
t.test('does write over keys already in process.env if override turned on', ct => {
ct.plan(2)
const existing = 'bar'
process.env.ALPHA = existing
const result = dotenv.config({ path: testPath, override: true })
ct.equal(result.parsed.ALPHA, 'zeta')
ct.equal(process.env.ALPHA, 'zeta')
})
t.test('when DOTENV_KEY is passed as an option it successfully decrypts and injects', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('')
ct.plan(2)
const result = dotenv.config({ path: testPath, DOTENV_KEY: dotenvKey })
ct.equal(result.parsed.ALPHA, 'zeta')
ct.equal(process.env.ALPHA, 'zeta')
ct.end()
})
t.test('can write to a different object rather than process.env', ct => {
ct.plan(3)
process.env.ALPHA = 'other' // reset process.env
logStub = sinon.stub(console, 'log')
const myObject = {}
const result = dotenv.config({ path: testPath, processEnv: myObject })
ct.equal(result.parsed.ALPHA, 'zeta')
ct.equal(process.env.ALPHA, 'other')
ct.equal(myObject.ALPHA, 'zeta')
})
t.test('logs when debug and override are turned on', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, override: true, debug: true })
ct.ok(logStub.called)
})
t.test('logs when debug is on and override is false', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, override: false, debug: true })
ct.ok(logStub.called)
})
t.test('raises an INVALID_DOTENV_KEY if key RangeError', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('dotenv://:key_ddcaa26504cd70a@dotenvx.com/vault/.env.vault?environment=development')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'INVALID_DOTENV_KEY: It must be 64 characters long (or more)')
ct.equal(e.code, 'INVALID_DOTENV_KEY')
}
ct.end()
})
t.test('raises an DECRYPTION_FAILED if key fails to decrypt payload', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('dotenv://:key_2c4d267b8c3865f921311612e69273666cc76c008acb577d3e22bc3046fba386@dotenvx.com/vault/.env.vault?environment=development')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'DECRYPTION_FAILED: Please check your DOTENV_KEY')
ct.equal(e.code, 'DECRYPTION_FAILED')
}
ct.end()
})
t.test('raises an DECRYPTION_FAILED if both (comma separated) keys fail to decrypt', ct => {
envStub.restore()
envStub = sinon.stub(process.env, 'DOTENV_KEY').value('dotenv://:key_2c4d267b8c3865f921311612e69273666cc76c008acb577d3e22bc3046fba386@dotenvx.com/vault/.env.vault?environment=development,dotenv://:key_c04959b64473e43dd60c56a536ef8481388528b16759736d89515c25eec69247@dotenvx.com/vault/.env.vault?environment=development')
ct.plan(2)
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'DECRYPTION_FAILED: Please check your DOTENV_KEY')
ct.equal(e.code, 'DECRYPTION_FAILED')
}
ct.end()
})
t.test('raises error if some other uncaught decryption error', ct => {
ct.plan(1)
const decipherStub = sinon.stub(crypto, 'createDecipheriv')
decipherStub.callsFake(() => {
throw new Error('uncaught error')
})
try {
dotenv.config({ path: testPath })
} catch (e) {
ct.equal(e.message, 'uncaught error')
}
decipherStub.restore()
ct.end()
})
t.test('_parseVault when empty args', ct => {
ct.plan(1)
try {
dotenv._parseVault()
} catch (e) {
ct.equal(e.message, 'NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment DOTENV_VAULT_DEVELOPMENT in your .env.vault file.')
}
})
================================================
FILE: tests/test-config.js
================================================
const fs = require('fs')
const os = require('os')
const path = require('path')
const sinon = require('sinon')
const t = require('tap')
const dotenv = require('../lib/main')
let logStub
t.beforeEach(() => {
logStub = null
delete process.env.BASIC // reset
})
t.afterEach(() => {
if (logStub) logStub.restore()
})
t.test('takes string for path option', ct => {
const testPath = 'tests/.env'
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, 'basic')
ct.end()
})
t.test('takes array for path option', ct => {
const testPath = ['tests/.env']
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, 'basic')
ct.end()
})
t.test('takes two or more files in the array for path option', ct => {
const testPath = ['tests/.env.local', 'tests/.env']
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, 'local_basic')
ct.equal(process.env.BASIC, 'local_basic')
ct.end()
})
t.test('sets values from both .env.local and .env. first file key wins.', ct => {
delete process.env.SINGLE_QUOTES
const testPath = ['tests/.env.local', 'tests/.env']
const env = dotenv.config({ path: testPath })
// in both files - first file wins (.env.local)
ct.equal(env.parsed.BASIC, 'local_basic')
ct.equal(process.env.BASIC, 'local_basic')
// in .env.local only
ct.equal(env.parsed.LOCAL, 'local')
ct.equal(process.env.LOCAL, 'local')
// in .env only
ct.equal(env.parsed.SINGLE_QUOTES, 'single_quotes')
ct.equal(process.env.SINGLE_QUOTES, 'single_quotes')
ct.end()
})
t.test('sets values from both .env.local and .env. but none is used as value existed in process.env.', ct => {
const testPath = ['tests/.env.local', 'tests/.env']
process.env.BASIC = 'existing'
const env = dotenv.config({ path: testPath })
// does not override process.env
ct.equal(env.parsed.BASIC, 'local_basic')
ct.equal(process.env.BASIC, 'existing')
ct.end()
})
t.test('takes URL for path option', ct => {
const envPath = path.resolve(__dirname, '.env')
const fileUrl = new URL(`file://${envPath}`)
const env = dotenv.config({ path: fileUrl })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, 'basic')
ct.end()
})
t.test('takes option for path along with home directory char ~', ct => {
const readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
const mockedHomedir = '/Users/dummy'
const homedirStub = sinon.stub(os, 'homedir').returns(mockedHomedir)
const testPath = '~/.env'
dotenv.config({ path: testPath })
ct.equal(readFileSyncStub.args[0][0], path.join(mockedHomedir, '.env'))
ct.ok(homedirStub.called)
homedirStub.restore()
readFileSyncStub.restore()
ct.end()
})
t.test('takes option for encoding', ct => {
const readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
const testEncoding = 'latin1'
dotenv.config({ encoding: testEncoding })
ct.equal(readFileSyncStub.args[0][1].encoding, testEncoding)
readFileSyncStub.restore()
ct.end()
})
t.test('takes option for debug', ct => {
logStub = sinon.stub(console, 'log')
dotenv.config({ debug: 'true' })
ct.ok(logStub.called)
ct.end()
})
t.test('reads path with encoding, parsing output to process.env', ct => {
const readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('BASIC=basic')
const parseStub = sinon.stub(dotenv, 'parse').returns({ BASIC: 'basic' })
const res = dotenv.config()
ct.same(res.parsed, { BASIC: 'basic' })
ct.equal(readFileSyncStub.callCount, 1)
readFileSyncStub.restore()
parseStub.restore()
ct.end()
})
t.test('does not write over keys already in process.env', ct => {
const testPath = 'tests/.env'
const existing = 'bar'
process.env.BASIC = existing
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, existing)
ct.end()
})
t.test('does write over keys already in process.env if override turned on', ct => {
const testPath = 'tests/.env'
const existing = 'bar'
process.env.BASIC = existing
const env = dotenv.config({ path: testPath, override: true })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, 'basic')
ct.end()
})
t.test('does not write over keys already in process.env if the key has a falsy value', ct => {
const testPath = 'tests/.env'
const existing = ''
process.env.BASIC = existing
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, '')
ct.end()
})
t.test('does write over keys already in process.env if the key has a falsy value but override is set to true', ct => {
const testPath = 'tests/.env'
const existing = ''
process.env.BASIC = existing
const env = dotenv.config({ path: testPath, override: true })
ct.equal(env.parsed.BASIC, 'basic')
ct.equal(process.env.BASIC, 'basic')
ct.end()
})
t.test('can write to a different object rather than process.env', ct => {
const testPath = 'tests/.env'
process.env.BASIC = 'other' // reset process.env
const myObject = {}
const env = dotenv.config({ path: testPath, processEnv: myObject })
ct.equal(env.parsed.BASIC, 'basic')
console.log('logging', process.env.BASIC)
ct.equal(process.env.BASIC, 'other')
ct.equal(myObject.BASIC, 'basic')
ct.end()
})
t.test('returns parsed object', ct => {
const testPath = 'tests/.env'
const env = dotenv.config({ path: testPath })
ct.notOk(env.error)
ct.equal(env.parsed.BASIC, 'basic')
ct.end()
})
t.test('returns any errors thrown from reading file or parsing', ct => {
const readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
readFileSyncStub.throws()
const env = dotenv.config()
ct.type(env.error, Error)
readFileSyncStub.restore()
ct.end()
})
t.test('logs any errors thrown from reading file or parsing when in debug mode', ct => {
ct.plan(2)
logStub = sinon.stub(console, 'log')
const readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
readFileSyncStub.throws()
const env = dotenv.config({ debug: true })
ct.ok(logStub.called)
ct.type(env.error, Error)
readFileSyncStub.restore()
})
t.test('logs any errors parsing when in debug and override mode', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config({ debug: true, override: true })
ct.ok(logStub.called)
})
t.test('deals with file:// path', ct => {
logStub = sinon.stub(console, 'log')
const testPath = 'file:///tests/.env'
const env = dotenv.config({ path: testPath })
ct.equal(env.parsed.BASIC, undefined)
ct.equal(process.env.BASIC, undefined)
ct.equal(env.error.message, "ENOENT: no such file or directory, open 'file:///tests/.env'")
ct.ok(logStub.called)
ct.end()
})
t.test('deals with file:// path and debug true', ct => {
logStub = sinon.stub(console, 'log')
const testPath = 'file:///tests/.env'
const env = dotenv.config({ path: testPath, debug: true })
ct.equal(env.parsed.BASIC, undefined)
ct.equal(process.env.BASIC, undefined)
ct.equal(env.error.message, "ENOENT: no such file or directory, open 'file:///tests/.env'")
ct.ok(logStub.called)
ct.end()
})
t.test('path.relative fails somehow', ct => {
logStub = sinon.stub(console, 'log')
const pathRelativeStub = sinon.stub(path, 'relative').throws(new Error('fail'))
const testPath = 'file:///tests/.env'
const env = dotenv.config({ path: testPath, debug: true })
ct.equal(env.parsed.BASIC, undefined)
ct.equal(process.env.BASIC, undefined)
ct.equal(env.error.message, 'fail')
ct.ok(logStub.called)
pathRelativeStub.restore()
ct.end()
})
t.test('displays random tips from the tips array', ct => {
ct.plan(2)
const originalTTY = process.stdout.isTTY
process.stdout.isTTY = true
logStub = sinon.stub(console, 'log')
const testPath = 'tests/.env'
// Test that tips are displayed (run config multiple times to see variation)
dotenv.config({ path: testPath })
dotenv.config({ path: testPath })
dotenv.config({ path: testPath })
// Should have at least one call that contains a tip
let foundTip = false
for (const call of logStub.getCalls()) {
if (call.args[0] && call.args[0].includes('tip:')) {
foundTip = true
break
}
}
ct.ok(foundTip, 'Should display a tip')
// Test that the tip contains one of our expected tip messages
let foundExpectedTip = false
const expectedTips = [
'🔐 encrypt with Dotenvx: https://dotenvx.com',
'🔐 prevent committing .env to code: https://dotenvx.com/precommit',
'🔐 prevent building .env in docker: https://dotenvx.com/prebuild',
'🤖 agentic secret storage: https://dotenvx.com/as2',
'⚡️ secrets for agents: https://dotenvx.com/as2',
'🛡️ auth for agents: https://vestauth.com',
'🛠️ run anywhere with `dotenvx run -- yourcommand`',
'⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }',
'⚙️ enable debug logging with { debug: true }',
'⚙️ override existing env vars with { override: true }',
'⚙️ suppress all logs with { quiet: true }',
'⚙️ write to custom object with { processEnv: myObject }',
'⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }'
]
for (const call of logStub.getCalls()) {
if (call.args[0] && call.args[0].includes('tip:')) {
for (const expectedTip of expectedTips) {
if (call.args[0].includes(expectedTip)) {
foundExpectedTip = true
break
}
}
}
}
ct.ok(foundExpectedTip, 'Should display one of the expected tips')
// Restore
process.stdout.isTTY = originalTTY
ct.end()
})
t.test('displays random tips from the tips array with fallback for isTTY false', ct => {
ct.plan(2)
const originalTTY = process.stdout.isTTY
process.stdout.isTTY = undefined
logStub = sinon.stub(console, 'log')
const testPath = 'tests/.env'
// Test that tips are displayed (run config multiple times to see variation)
dotenv.config({ path: testPath })
dotenv.config({ path: testPath })
dotenv.config({ path: testPath })
// Should have at least one call that contains a tip
let foundTip = false
for (const call of logStub.getCalls()) {
if (call.args[0] && call.args[0].includes('tip:')) {
foundTip = true
break
}
}
ct.ok(foundTip, 'Should display a tip')
// Test that the tip contains one of our expected tip messages
let foundExpectedTip = false
const expectedTips = [
'🔐 encrypt with Dotenvx: https://dotenvx.com',
'🔐 prevent committing .env to code: https://dotenvx.com/precommit',
'🔐 prevent building .env in docker: https://dotenvx.com/prebuild',
'🤖 agentic secret storage: https://dotenvx.com/as2',
'⚡️ secrets for agents: https://dotenvx.com/as2',
'🛡️ auth for agents: https://vestauth.com',
'🛠️ run anywhere with `dotenvx run -- yourcommand`',
'⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }',
'⚙️ enable debug logging with { debug: true }',
'⚙️ override existing env vars with { override: true }',
'⚙️ suppress all logs with { quiet: true }',
'⚙️ write to custom object with { processEnv: myObject }',
'⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }'
]
for (const call of logStub.getCalls()) {
if (call.args[0] && call.args[0].includes('tip:')) {
for (const expectedTip of expectedTips) {
if (call.args[0].includes(expectedTip)) {
foundExpectedTip = true
break
}
}
}
}
ct.ok(foundExpectedTip, 'Should display one of the expected tips')
// Restore
process.stdout.isTTY = originalTTY
ct.end()
})
t.test('logs when no path is set', ct => {
ct.plan(1)
logStub = sinon.stub(console, 'log')
dotenv.config()
ct.ok(logStub.called)
})
t.test('does log by default', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath })
ct.ok(logStub.called)
})
t.test('does not log if quiet flag passed true', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, quiet: true })
ct.ok(logStub.notCalled)
})
t.test('does not log if process.env.DOTENV_CONFIG_QUIET is true', ct => {
ct.plan(1)
process.env.DOTENV_CONFIG_QUIET = 'true'
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath })
ct.ok(logStub.notCalled)
delete process.env.DOTENV_CONFIG_QUIET
})
t.test('does log if quiet flag false', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, quiet: false })
ct.ok(logStub.called)
})
t.test('does log if process.env.DOTENV_CONFIG_QUIET is false', ct => {
ct.plan(1)
process.env.DOTENV_CONFIG_QUIET = 'false'
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath })
ct.ok(logStub.called)
delete process.env.DOTENV_CONFIG_QUIET
})
t.test('does log if quiet flag present and undefined/null', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, quiet: undefined })
ct.ok(logStub.called)
})
t.test('logs if debug set', ct => {
ct.plan(1)
const testPath = 'tests/.env'
logStub = sinon.stub(console, 'log')
dotenv.config({ path: testPath, debug: true })
ct.ok(logStub.called)
})
================================================
FILE: tests/test-decrypt.js
================================================
const t = require('tap')
const dotenv = require('../lib/main')
t.test('can decrypt', ct => {
ct.plan(1)
const encrypted = 's7NYXa809k/bVSPwIAmJhPJmEGTtU0hG58hOZy7I0ix6y5HP8LsHBsZCYC/gw5DDFy5DgOcyd18R'
const keyStr = 'ddcaa26504cd70a6fef9801901c3981538563a1767c297cb8416e8a38c62fe00'
const result = dotenv.decrypt(encrypted, keyStr)
ct.equal(result, '# development@v6\nALPHA="zeta"')
})
================================================
FILE: tests/test-env-options.js
================================================
const t = require('tap')
const decache = require('decache')
// warm cache
require('../lib/env-options')
// preserve existing env
const e = process.env.DOTENV_CONFIG_ENCODING
const p = process.env.DOTENV_CONFIG_PATH
const q = process.env.DOTENV_CONFIG_QUIET
const d = process.env.DOTENV_CONFIG_DEBUG
const o = process.env.DOTENV_CONFIG_OVERRIDE
const dk = process.env.DOTENV_CONFIG_DOTENV_KEY
// get fresh object for each test
function options () {
decache('../lib/env-options.js')
return require('../lib/env-options')
}
function testOption (envVar, tmpVal, expect) {
delete process.env[envVar]
process.env[envVar] = tmpVal
t.same(options(), expect)
delete process.env[envVar]
}
// returns empty object when no options set in process.env
delete process.env.DOTENV_CONFIG_ENCODING
delete process.env.DOTENV_CONFIG_PATH
delete process.env.DOTENV_CONFIG_QUIET
delete process.env.DOTENV_CONFIG_DEBUG
delete process.env.DOTENV_CONFIG_OVERRIDE
delete process.env.DOTENV_CONFIG_DOTENV_KEY
t.same(options(), {})
// sets encoding option
testOption('DOTENV_CONFIG_ENCODING', 'latin1', { encoding: 'latin1' })
// sets path option
testOption('DOTENV_CONFIG_PATH', '~/.env.test', { path: '~/.env.test' })
// sets quiet option
testOption('DOTENV_CONFIG_QUIET', 'true', { quiet: 'true' })
// sets debug option
testOption('DOTENV_CONFIG_DEBUG', 'true', { debug: 'true' })
// sets override option
testOption('DOTENV_CONFIG_OVERRIDE', 'true', { override: 'true' })
// sets DOTENV_KEY option
testOption('DOTENV_CONFIG_DOTENV_KEY', 'dotenv://:key_ddcaa26504cd70a@dotenvx.com/vault/.env.vault?environment=development', { DOTENV_KEY: 'dotenv://:key_ddcaa26504cd70a@dotenvx.com/vault/.env.vault?environment=development' })
// restore existing env
process.env.DOTENV_CONFIG_ENCODING = e
process.env.DOTENV_CONFIG_PATH = p
process.env.DOTENV_CONFIG_QUIET = q
process.env.DOTENV_CONFIG_DEBUG = d
process.env.DOTENV_CONFIG_OVERRIDE = o
process.env.DOTENV_CONFIG_DOTENV_KEY = dk
================================================
FILE: tests/test-parse-multiline.js
================================================
const fs = require('fs')
const t = require('tap')
const dotenv = require('../lib/main')
const parsed = dotenv.parse(fs.readFileSync('tests/.env.multiline', { encoding: 'utf8' }))
t.type(parsed, Object, 'should return an object')
t.equal(parsed.BASIC, 'basic', 'sets basic environment variable')
t.equal(parsed.AFTER_LINE, 'after_line', 'reads after a skipped line')
t.equal(parsed.EMPTY, '', 'defaults empty values to empty string')
t.equal(parsed.SINGLE_QUOTES, 'single_quotes', 'escapes single quoted values')
t.equal(parsed.SINGLE_QUOTES_SPACED, ' single quotes ', 'respects surrounding spaces in single quotes')
t.equal(parsed.DOUBLE_QUOTES, 'double_quotes', 'escapes double quoted values')
t.equal(parsed.DOUBLE_QUOTES_SPACED, ' double quotes ', 'respects surrounding spaces in double quotes')
t.equal(parsed.EXPAND_NEWLINES, 'expand\nnew\nlines', 'expands newlines but only if double quoted')
t.equal(parsed.DONT_EXPAND_UNQUOTED, 'dontexpand\\nnewlines', 'expands newlines but only if double quoted')
t.equal(parsed.DONT_EXPAND_SQUOTED, 'dontexpand\\nnewlines', 'expands newlines but only if double quoted')
t.notOk(parsed.COMMENTS, 'ignores commented lines')
t.equal(parsed.EQUAL_SIGNS, 'equals==', 'respects equals signs in values')
t.equal(parsed.RETAIN_INNER_QUOTES, '{"foo": "bar"}', 'retains inner quotes')
t.equal(parsed.RETAIN_INNER_QUOTES_AS_STRING, '{"foo": "bar"}', 'retains inner quotes')
t.equal(parsed.TRIM_SPACE_FROM_UNQUOTED, 'some spaced out string', 'retains spaces in string')
t.equal(parsed.USERNAME, 'therealnerdybeast@example.tld', 'parses email addresses completely')
t.equal(parsed.SPACED_KEY, 'parsed', 'parses keys and values surrounded by spaces')
t.equal(parsed.MULTI_DOUBLE_QUOTED, 'THIS\nIS\nA\nMULTILINE\nSTRING', 'parses multi-line strings when using double quotes')
t.equal(parsed.MULTI_SINGLE_QUOTED, 'THIS\nIS\nA\nMULTILINE\nSTRING', 'parses multi-line strings when using single quotes')
t.equal(parsed.MULTI_BACKTICKED, 'THIS\nIS\nA\n"MULTILINE\'S"\nSTRING', 'parses multi-line strings when using backticks')
const multiPem = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnNl1tL3QjKp3DZWM0T3u
LgGJQwu9WqyzHKZ6WIA5T+7zPjO1L8l3S8k8YzBrfH4mqWOD1GBI8Yjq2L1ac3Y/
bTdfHN8CmQr2iDJC0C6zY8YV93oZB3x0zC/LPbRYpF8f6OqX1lZj5vo2zJZy4fI/
kKcI5jHYc8VJq+KCuRZrvn+3V+KuL9tF9v8ZgjF2PZbU+LsCy5Yqg1M8f5Jp5f6V
u4QuUoobAgMBAAE=
-----END PUBLIC KEY-----`
t.equal(parsed.MULTI_PEM_DOUBLE_QUOTED, multiPem)
const payload = dotenv.parse(Buffer.from('BUFFER=true'))
t.equal(payload.BUFFER, 'true', 'should parse a buffer into an object')
const expectedPayload = { SERVER: 'localhost', PASSWORD: 'password', DB: 'tests' }
const RPayload = dotenv.parse(Buffer.from('SERVER=localhost\rPASSWORD=password\rDB=tests\r'))
t.same(RPayload, expectedPayload, 'can parse (\\r) line endings')
const NPayload = dotenv.parse(Buffer.from('SERVER=localhost\nPASSWORD=password\nDB=tests\n'))
t.same(NPayload, expectedPayload, 'can parse (\\n) line endings')
const RNPayload = dotenv.parse(Buffer.from('SERVER=localhost\r\nPASSWORD=password\r\nDB=tests\r\n'))
t.same(RNPayload, expectedPayload, 'can parse (\\r\\n) line endings')
================================================
FILE: tests/test-parse.js
================================================
const fs = require('fs')
const t = require('tap')
const dotenv = require('../lib/main')
const parsed = dotenv.parse(fs.readFileSync('tests/.env', { encoding: 'utf8' }))
t.type(parsed, Object, 'should return an object')
t.equal(parsed.BASIC, 'basic', 'sets basic environment variable')
t.equal(parsed.AFTER_LINE, 'after_line', 'reads after a skipped line')
t.equal(parsed.EMPTY, '', 'defaults empty values to empty string')
t.equal(parsed.EMPTY_SINGLE_QUOTES, '', 'defaults empty values to empty string')
t.equal(parsed.EMPTY_DOUBLE_QUOTES, '', 'defaults empty values to empty string')
t.equal(parsed.EMPTY_BACKTICKS, '', 'defaults empty values to empty string')
t.equal(parsed.SINGLE_QUOTES, 'single_quotes', 'escapes single quoted values')
t.equal(parsed.SINGLE_QUOTES_SPACED, ' single quotes ', 'respects surrounding spaces in single quotes')
t.equal(parsed.DOUBLE_QUOTES, 'double_quotes', 'escapes double quoted values')
t.equal(parsed.DOUBLE_QUOTES_SPACED, ' double quotes ', 'respects surrounding spaces in double quotes')
t.equal(parsed.DOUBLE_QUOTES_INSIDE_SINGLE, 'double "quotes" work inside single quotes', 'respects double quotes inside single quotes')
t.equal(parsed.DOUBLE_QUOTES_WITH_NO_SPACE_BRACKET, '{ port: $MONGOLAB_PORT}', 'respects spacing for badly formed brackets')
t.equal(parsed.SINGLE_QUOTES_INSIDE_DOUBLE, "single 'quotes' work inside double quotes", 'respects single quotes inside double quotes')
t.equal(parsed.BACKTICKS_INSIDE_SINGLE, '`backticks` work inside single quotes', 'respects backticks inside single quotes')
t.equal(parsed.BACKTICKS_INSIDE_DOUBLE, '`backticks` work inside double quotes', 'respects backticks inside double quotes')
t.equal(parsed.BACKTICKS, 'backticks')
t.equal(parsed.BACKTICKS_SPACED, ' backticks ')
t.equal(parsed.DOUBLE_QUOTES_INSIDE_BACKTICKS, 'double "quotes" work inside backticks', 'respects double quotes inside backticks')
t.equal(parsed.SINGLE_QUOTES_INSIDE_BACKTICKS, "single 'quotes' work inside backticks", 'respects single quotes inside backticks')
t.equal(parsed.DOUBLE_AND_SINGLE_QUOTES_INSIDE_BACKTICKS, "double \"quotes\" and single 'quotes' work inside backticks", 'respects single quotes inside backticks')
t.equal(parsed.EXPAND_NEWLINES, 'expand\nnew\nlines', 'expands newlines but only if double quoted')
t.equal(parsed.DONT_EXPAND_UNQUOTED, 'dontexpand\\nnewlines', 'expands newlines but only if double quoted')
t.equal(parsed.DONT_EXPAND_SQUOTED, 'dontexpand\\nnewlines', 'expands newlines but only if double quoted')
t.notOk(parsed.COMMENTS, 'ignores commented lines')
t.equal(parsed.INLINE_COMMENTS, 'inline comments', 'ignores inline comments')
t.equal(parsed.INLINE_COMMENTS_SINGLE_QUOTES, 'inline comments outside of #singlequotes', 'ignores inline comments and respects # character inside of single quotes')
t.equal(parsed.INLINE_COMMENTS_DOUBLE_QUOTES, 'inline comments outside of #doublequotes', 'ignores inline comments and respects # character inside of double quotes')
t.equal(parsed.INLINE_COMMENTS_BACKTICKS, 'inline comments outside of #backticks', 'ignores inline comments and respects # character inside of backticks')
t.equal(parsed.INLINE_COMMENTS_SPACE, 'inline comments start with a', 'treats # character as start of comment')
t.equal(parsed.EQUAL_SIGNS, 'equals==', 'respects equals signs in values')
t.equal(parsed.RETAIN_INNER_QUOTES, '{"foo": "bar"}', 'retains inner quotes')
t.equal(parsed.RETAIN_INNER_QUOTES_AS_STRING, '{"foo": "bar"}', 'retains inner quotes')
t.equal(parsed.RETAIN_INNER_QUOTES_AS_BACKTICKS, '{"foo": "bar\'s"}', 'retains inner quotes')
t.equal(parsed.TRIM_SPACE_FROM_UNQUOTED, 'some spaced out string', 'retains spaces in string')
t.equal(parsed.USERNAME, 'therealnerdybeast@example.tld', 'parses email addresses completely')
t.equal(parsed.SPACED_KEY, 'parsed', 'parses keys and values surrounded by spaces')
const payload = dotenv.parse(Buffer.from('BUFFER=true'))
t.equal(payload.BUFFER, 'true', 'should parse a buffer into an object')
const duplicate = dotenv.parse(Buffer.from('DUP=one\nDUP=two'))
t.equal(duplicate.DUP, 'two', 'last duplicate key wins')
const expectedPayload = { SERVER: 'localhost', PASSWORD: 'password', DB: 'tests' }
const RPayload = dotenv.parse(Buffer.from('SERVER=localhost\rPASSWORD=password\rDB=tests\r'))
t.same(RPayload, expectedPayload, 'can parse (\\r) line endings')
const NPayload = dotenv.parse(Buffer.from('SERVER=localhost\nPASSWORD=password\nDB=tests\n'))
t.same(NPayload, expectedPayload, 'can parse (\\n) line endings')
const RNPayload = dotenv.parse(Buffer.from('SERVER=localhost\r\nPASSWORD=password\r\nDB=tests\r\n'))
t.same(RNPayload, expectedPayload, 'can parse (\\r\\n) line endings')
================================================
FILE: tests/test-populate.js
================================================
const fs = require('fs')
const sinon = require('sinon')
const t = require('tap')
const dotenv = require('../lib/main')
const mockParseResponse = { test: 'foo' }
let readFileSyncStub
let parseStub
t.beforeEach(() => {
readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
parseStub = sinon.stub(dotenv, 'parse').returns(mockParseResponse)
})
t.afterEach(() => {
readFileSyncStub.restore()
parseStub.restore()
})
t.test('takes processEnv and check if all keys applied to processEnv', ct => {
ct.plan(1)
const parsed = { test: 1, home: 2 }
const processEnv = {}
dotenv.populate(processEnv, parsed)
ct.same(parsed, processEnv)
})
t.test('does not write over keys already in processEnv', ct => {
ct.plan(1)
const existing = 'bar'
const parsed = { test: 'test' }
process.env.test = existing
// 'test' returned as value in `beforeEach`. should keep this 'bar'
dotenv.populate(process.env, parsed)
ct.equal(process.env.test, existing)
})
t.test('does write over keys already in processEnv if override turned on', ct => {
ct.plan(1)
const existing = 'bar'
const parsed = { test: 'test' }
process.env.test = existing
// 'test' returned as value in `beforeEach`. should change this 'bar' to 'test'
dotenv.populate(process.env, parsed, { override: true })
ct.equal(process.env.test, parsed.test)
})
t.test('logs any errors populating when in debug mode but override turned off', ct => {
ct.plan(2)
const logStub = sinon.stub(console, 'log')
const parsed = { test: false }
process.env.test = true
dotenv.populate(process.env, parsed, { debug: true })
ct.not(process.env.test, parsed.test)
ct.ok(logStub.called)
logStub.restore()
})
t.test('logs populating when debug mode and override turned on', ct => {
ct.plan(1)
const logStub = sinon.stub(console, 'log')
const parsed = { test: false }
process.env.test = true
dotenv.populate(process.env, parsed, { debug: true, override: true })
console.log('process', process.env.test, parsed.test)
ct.ok(logStub.called)
logStub.restore()
})
t.test('returns any errors thrown on passing not json type', ct => {
ct.plan(1)
try {
dotenv.populate(process.env, '')
} catch (e) {
ct.equal(e.message, 'OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
}
})
================================================
FILE: tests/types/test.ts
================================================
import { config, parse } from "dotenv";
const env = config();
const dbUrl: string | null =
env.error || !env.parsed ? null : env.parsed["BASIC"];
config({
path: ".env-example",
encoding: "utf8",
debug: true,
});
parse("test");
const parsed = parse("NODE_ENV=production\nDB_HOST=a.b.c");
const dbHost: string = parsed["DB_HOST"];
const parsedFromBuffer = parse(Buffer.from("JUSTICE=league\n"));
const justice: string = parsedFromBuffer["JUSTICE"];
config({
// make sure the type accepts process.env (it didn't in the past)
processEnv: process.env,
});
================================================
FILE: tests/types/tsconfig.json
================================================
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"strict": true,
"noEmit": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": ".",
"paths": {
"dotenv": ["../../lib/main.d.ts"]
}
},
"include": ["./test.ts", "../../main.d.ts"]
}