You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

275 lines
9.8 KiB

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