10c2d5485e9010708cfe7055a3fd9320adfd43ce9f19693207436eb41cd218b24699000cf1ddd339890d53fdcd216063faa06a911aab32a2dda7323cdbcb5f 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. **Announcement 📣** - From the makers that brought you .env, introducing [.env.me](http://npmjs.org/package/dotenv-me). Sync your .env files across machines. [Join the early access list.](https://me.dotenv.org/)
  2. # dotenv
  3. <img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" />
  4. 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](http://12factor.net/config) methodology.
  5. [![BuildStatus](https://img.shields.io/travis/motdotla/dotenv/master.svg?style=flat-square)](https://travis-ci.org/motdotla/dotenv)
  6. [![Build status](https://ci.appveyor.com/api/projects/status/github/motdotla/dotenv?svg=true)](https://ci.appveyor.com/project/motdotla/dotenv/branch/master)
  7. [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
  8. [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
  9. [![Coverage Status](https://img.shields.io/coveralls/motdotla/dotenv/master.svg?style=flat-square)](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration)
  10. [![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
  11. [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
  12. ## Install
  13. ```bash
  14. # with npm
  15. npm install dotenv
  16. # or with Yarn
  17. yarn add dotenv
  18. ```
  19. ## Usage
  20. As early as possible in your application, require and configure dotenv.
  21. ```javascript
  22. require('dotenv').config()
  23. ```
  24. Create a `.env` file in the root directory of your project. Add
  25. environment-specific variables on new lines in the form of `NAME=VALUE`.
  26. For example:
  27. ```dosini
  28. DB_HOST=localhost
  29. DB_USER=root
  30. DB_PASS=s1mpl3
  31. ```
  32. `process.env` now has the keys and values you defined in your `.env` file.
  33. ```javascript
  34. const db = require('db')
  35. db.connect({
  36. host: process.env.DB_HOST,
  37. username: process.env.DB_USER,
  38. password: process.env.DB_PASS
  39. })
  40. ```
  41. ### Preload
  42. You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#cli_r_require_module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using `import` instead of `require`.
  43. ```bash
  44. $ node -r dotenv/config your_script.js
  45. ```
  46. The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
  47. ```bash
  48. $ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
  49. ```
  50. Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
  51. ```bash
  52. $ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
  53. ```
  54. ```bash
  55. $ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
  56. ```
  57. ## Config
  58. `config` will read your `.env` file, parse the contents, assign it to
  59. [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
  60. and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
  61. ```js
  62. const result = dotenv.config()
  63. if (result.error) {
  64. throw result.error
  65. }
  66. console.log(result.parsed)
  67. ```
  68. You can additionally, pass options to `config`.
  69. ### Options
  70. #### Path
  71. Default: `path.resolve(process.cwd(), '.env')`
  72. You may specify a custom path if your file containing environment variables is located elsewhere.
  73. ```js
  74. require('dotenv').config({ path: '/custom/path/to/.env' })
  75. ```
  76. #### Encoding
  77. Default: `utf8`
  78. You may specify the encoding of your file containing environment variables.
  79. ```js
  80. require('dotenv').config({ encoding: 'latin1' })
  81. ```
  82. #### Debug
  83. Default: `false`
  84. You may turn on logging to help debug why certain keys or values are not being set as you expect.
  85. ```js
  86. require('dotenv').config({ debug: process.env.DEBUG })
  87. ```
  88. ## Parse
  89. The engine which parses the contents of your file containing environment
  90. variables is available to use. It accepts a String or Buffer and will return
  91. an Object with the parsed keys and values.
  92. ```js
  93. const dotenv = require('dotenv')
  94. const buf = Buffer.from('BASIC=basic')
  95. const config = dotenv.parse(buf) // will return an object
  96. console.log(typeof config, config) // object { BASIC : 'basic' }
  97. ```
  98. ### Options
  99. #### Debug
  100. Default: `false`
  101. You may turn on logging to help debug why certain keys or values are not being set as you expect.
  102. ```js
  103. const dotenv = require('dotenv')
  104. const buf = Buffer.from('hello world')
  105. const opt = { debug: true }
  106. const config = dotenv.parse(buf, opt)
  107. // expect a debug message because the buffer is not in KEY=VAL form
  108. ```
  109. ### Rules
  110. The parsing engine currently supports the following rules:
  111. - `BASIC=basic` becomes `{BASIC: 'basic'}`
  112. - empty lines are skipped
  113. - lines beginning with `#` are treated as comments
  114. - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
  115. - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
  116. - 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'}`)
  117. - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
  118. - single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
  119. - double quoted values expand new lines (`MULTILINE="new\nline"` becomes
  120. ```
  121. {MULTILINE: 'new
  122. line'}
  123. ```
  124. ## FAQ
  125. ### Should I commit my `.env` file?
  126. No. We **strongly** recommend against committing your `.env` file to version
  127. control. It should only include environment-specific values such as database
  128. passwords or API keys. Your production database should have a different
  129. password than your development database.
  130. ### Should I have multiple `.env` files?
  131. No. We **strongly** recommend against having a "main" `.env` file and an "environment" `.env` file like `.env.test`. Your config should vary between deploys, and you should not be sharing values between environments.
  132. > 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.
  133. >
  134. > – [The Twelve-Factor App](http://12factor.net/config)
  135. ### What happens to environment variables that were already set?
  136. 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. This behavior allows you to override all `.env` configurations with a machine-specific environment, although it is not recommended.
  137. If you want to override `process.env` you can do something like this:
  138. ```javascript
  139. const fs = require('fs')
  140. const dotenv = require('dotenv')
  141. const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
  142. for (const k in envConfig) {
  143. process.env[k] = envConfig[k]
  144. }
  145. ```
  146. ### Can I customize/write plugins for dotenv?
  147. For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing
  148. the parsed `.env` file. This gives you everything you need to continue
  149. setting values on `process.env`. For example:
  150. ```js
  151. const dotenv = require('dotenv')
  152. const variableExpansion = require('dotenv-expand')
  153. const myEnv = dotenv.config()
  154. variableExpansion(myEnv)
  155. ```
  156. ### What about variable expansion?
  157. Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
  158. ### How do I use dotenv with `import`?
  159. ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`.
  160. > 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.
  161. >
  162. > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
  163. You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code:
  164. `errorReporter.js`:
  165. ```js
  166. import { Client } from 'best-error-reporting-service'
  167. export const client = new Client(process.env.BEST_API_KEY)
  168. ```
  169. `index.js`:
  170. ```js
  171. import dotenv from 'dotenv'
  172. import errorReporter from './errorReporter'
  173. dotenv.config()
  174. errorReporter.client.report(new Error('faq example'))
  175. ```
  176. `client` will not be configured correctly because it was constructed before `dotenv.config()` was executed. There are (at least) 3 ways to make this work.
  177. 1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
  178. 2. Import `dotenv/config` instead of `dotenv` (_Note: you do not need to call `dotenv.config()` and must pass options via the command line or environment variables with this approach_)
  179. 3. 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)
  180. ## Contributing Guide
  181. See [CONTRIBUTING.md](CONTRIBUTING.md)
  182. ## Change Log
  183. See [CHANGELOG.md](CHANGELOG.md)
  184. ## Who's using dotenv?
  185. [These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
  186. Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).