UNPKG

9.72 kBMarkdownView Raw
1# dotenv
2
3<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" />
4
5Dotenv 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.
6
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
15## Install
16
17```bash
18# with npm
19npm install dotenv
20
21# or with Yarn
22yarn add dotenv
23```
24
25## Usage
26
27As early as possible in your application, require and configure dotenv.
28
29```javascript
30require('dotenv').config()
31```
32
33Create a `.env` file in the root directory of your project. Add
34environment-specific variables on new lines in the form of `NAME=VALUE`.
35For example:
36
37```dosini
38DB_HOST=localhost
39DB_USER=root
40DB_PASS=s1mpl3
41```
42
43`process.env` now has the keys and values you defined in your `.env` file.
44
45```javascript
46const db = require('db')
47db.connect({
48 host: process.env.DB_HOST,
49 username: process.env.DB_USER,
50 password: process.env.DB_PASS
51})
52```
53
54### Preload
55
56You 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`.
57
58```bash
59$ node -r dotenv/config your_script.js
60```
61
62The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
63
64```bash
65$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars
66```
67
68Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
69
70```bash
71$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
72```
73
74```bash
75$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
76```
77
78## Config
79
80`config` will read your `.env` file, parse the contents, assign it to
81[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
82and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
83
84```js
85const result = dotenv.config()
86
87if (result.error) {
88 throw result.error
89}
90
91console.log(result.parsed)
92```
93
94You can additionally, pass options to `config`.
95
96### Options
97
98#### Path
99
100Default: `path.resolve(process.cwd(), '.env')`
101
102You may specify a custom path if your file containing environment variables is located elsewhere.
103
104```js
105require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' })
106```
107
108#### Encoding
109
110Default: `utf8`
111
112You may specify the encoding of your file containing environment variables.
113
114```js
115require('dotenv').config({ encoding: 'latin1' })
116```
117
118#### Debug
119
120Default: `false`
121
122You may turn on logging to help debug why certain keys or values are not being set as you expect.
123
124```js
125require('dotenv').config({ debug: process.env.DEBUG })
126```
127
128## Parse
129
130The engine which parses the contents of your file containing environment
131variables is available to use. It accepts a String or Buffer and will return
132an Object with the parsed keys and values.
133
134```js
135const dotenv = require('dotenv')
136const buf = Buffer.from('BASIC=basic')
137const config = dotenv.parse(buf) // will return an object
138console.log(typeof config, config) // object { BASIC : 'basic' }
139```
140
141### Options
142
143#### Debug
144
145Default: `false`
146
147You may turn on logging to help debug why certain keys or values are not being set as you expect.
148
149```js
150const dotenv = require('dotenv')
151const buf = Buffer.from('hello world')
152const opt = { debug: true }
153const config = dotenv.parse(buf, opt)
154// expect a debug message because the buffer is not in KEY=VAL form
155```
156
157### Rules
158
159The parsing engine currently supports the following rules:
160
161- `BASIC=basic` becomes `{BASIC: 'basic'}`
162- empty lines are skipped
163- lines beginning with `#` are treated as comments
164- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
165- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
166- 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'}`)
167- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
168- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
169- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
170
171```
172{MULTILINE: 'new
173line'}
174```
175
176## FAQ
177
178### Should I commit my `.env` file?
179
180No. We **strongly** recommend against committing your `.env` file to version
181control. It should only include environment-specific values such as database
182passwords or API keys. Your production database should have a different
183password than your development database.
184
185### Should I have multiple `.env` files?
186
187No. 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.
188
189> 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.
190>
191> – [The Twelve-Factor App](http://12factor.net/config)
192
193### What happens to environment variables that were already set?
194
195We 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.
196
197If you want to override `process.env` you can do something like this:
198
199```javascript
200const fs = require('fs')
201const dotenv = require('dotenv')
202const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
203for (const k in envConfig) {
204 process.env[k] = envConfig[k]
205}
206```
207
208### Can I customize/write plugins for dotenv?
209
210For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing
211the parsed `.env` file. This gives you everything you need to continue
212setting values on `process.env`. For example:
213
214```js
215const dotenv = require('dotenv')
216const variableExpansion = require('dotenv-expand')
217const myEnv = dotenv.config()
218variableExpansion(myEnv)
219```
220
221### What about variable expansion?
222
223Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
224
225### How do I use dotenv with `import`?
226
227ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`.
228
229> 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.
230>
231> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
232
233You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code:
234
235`errorReporter.js`:
236
237```js
238import { Client } from 'best-error-reporting-service'
239
240export const client = new Client(process.env.BEST_API_KEY)
241```
242
243`index.js`:
244
245```js
246import dotenv from 'dotenv'
247import errorReporter from './errorReporter'
248
249dotenv.config()
250errorReporter.client.report(new Error('faq example'))
251```
252
253`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.
254
2551. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
2562. 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_)
2573. 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)
258
259## Contributing Guide
260
261See [CONTRIBUTING.md](CONTRIBUTING.md)
262
263## Change Log
264
265See [CHANGELOG.md](CHANGELOG.md)
266
267## Who's using dotenv?
268
269[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
270
271Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).