source: node_modules/dotenv/README.md

main
Last change on this file was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 21.9 KB
LineΒ 
1<div align="center">
2πŸŽ‰ announcing <a href="https://github.com/dotenvx/dotenvx">dotenvx</a>. <em>run anywhere, multi-environment, encrypted envs</em>.
3</div>
4
5&nbsp;
6
7<div align="center">
8
9**Special thanks to [our sponsors](https://github.com/sponsors/motdotla)**
10
11<br>
12<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv"><img src="https://res.cloudinary.com/dotenv-org/image/upload/v1744035073/graphite_lgsrl8.gif" width="240" alt="Graphite" /></a>
13<br>
14<a href="https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv">
15 <b>Graphite is the AI developer productivity platform helping teams on GitHub ship higher quality software, faster.</b>
16</a>
17<hr>
18</div>
19
20# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
21
22<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
23
24Dotenv 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.
25
26[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
27[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
28[![codecov](https://codecov.io/gh/motdotla/dotenv-expand/graph/badge.svg?token=pawWEyaMfg)](https://codecov.io/gh/motdotla/dotenv-expand)
29
30* [🌱 Install](#-install)
31* [πŸ—οΈ Usage (.env)](#%EF%B8%8F-usage)
32* [🌴 Multiple Environments πŸ†•](#-manage-multiple-environments)
33* [πŸš€ Deploying (encryption) πŸ†•](#-deploying)
34* [πŸ“š Examples](#-examples)
35* [πŸ“– Docs](#-documentation)
36* [❓ FAQ](#-faq)
37* [⏱️ Changelog](./CHANGELOG.md)
38
39## 🌱 Install
40
41```bash
42npm install dotenv --save
43```
44
45You can also use an npm-compatible package manager like yarn, bun or pnpm:
46
47```bash
48yarn add dotenv
49```
50```bash
51bun add dotenv
52```
53```bash
54pnpm add dotenv
55```
56
57## πŸ—οΈ Usage
58
59<a href="https://www.youtube.com/watch?v=YtkZR0NFd1g">
60<div align="right">
61<img src="https://img.youtube.com/vi/YtkZR0NFd1g/hqdefault.jpg" alt="how to use dotenv video tutorial" align="right" width="330" />
62<img src="https://simpleicons.vercel.app/youtube/ff0000" alt="youtube/@dotenvorg" align="right" width="24" />
63</div>
64</a>
65
66Create a `.env` file in the root of your project (if using a monorepo structure like `apps/backend/app.js`, put it in the root of the folder where your `app.js` process runs):
67
68```dosini
69S3_BUCKET="YOURS3BUCKET"
70SECRET_KEY="YOURSECRETKEYGOESHERE"
71```
72
73As early as possible in your application, import and configure dotenv:
74
75```javascript
76require('dotenv').config()
77console.log(process.env) // remove this after you've confirmed it is working
78```
79
80.. [or using ES6?](#how-do-i-use-dotenv-with-import)
81
82```javascript
83import 'dotenv/config'
84```
85
86That's it. `process.env` now has the keys and values you defined in your `.env` file:
87
88```javascript
89require('dotenv').config()
90// or import 'dotenv/config' if you're using ES6
91
92...
93
94s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
95```
96
97### Multiline values
98
99If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
100
101```dosini
102PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
103...
104Kh9NV...
105...
106-----END RSA PRIVATE KEY-----"
107```
108
109Alternatively, you can double quote strings and use the `\n` character:
110
111```dosini
112PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
113```
114
115### Comments
116
117Comments may be added to your file on their own line or inline:
118
119```dosini
120# This is a comment
121SECRET_KEY=YOURSECRETKEYGOESHERE # comment
122SECRET_HASH="something-with-a-#-hash"
123```
124
125Comments 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.
126
127### Parsing
128
129The 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.
130
131```javascript
132const dotenv = require('dotenv')
133const buf = Buffer.from('BASIC=basic')
134const config = dotenv.parse(buf) // will return an object
135console.log(typeof config, config) // object { BASIC : 'basic' }
136```
137
138### Preload
139
140> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
141>
142> 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://github.com/motdotla)
143
144You 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.
145
146```bash
147$ node -r dotenv/config your_script.js
148```
149
150The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
151
152```bash
153$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
154```
155
156Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
157
158```bash
159$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
160```
161
162```bash
163$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
164```
165
166### Variable Expansion
167
168You need to add the value of another variable in one of your variables? Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).
169
170### Command Substitution
171
172Use [dotenvx](https://github.com/dotenvx/dotenvx) to use command substitution.
173
174Add the output of a command to one of your variables in your .env file.
175
176```ini
177# .env
178DATABASE_URL="postgres://$(whoami)@localhost/my_database"
179```
180```js
181// index.js
182console.log('DATABASE_URL', process.env.DATABASE_URL)
183```
184```sh
185$ dotenvx run --debug -- node index.js
186[dotenvx@0.14.1] injecting env (1) from .env
187DATABASE_URL postgres://yourusername@localhost/my_database
188```
189
190### Syncing
191
192You need to keep `.env` files in sync between machines, environments, or team members? Use [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt your `.env` files and safely include them in source control. This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
193
194### Multiple Environments
195
196Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate `.env.ci`, `.env.production` files, and more.
197
198### Deploying
199
200You need to deploy your secrets in a cloud-agnostic manner? Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate a private decryption key that is set on your production server.
201
202## 🌴 Manage Multiple Environments
203
204Use [dotenvx](https://github.com/dotenvx/dotenvx)
205
206Run any environment locally. Create a `.env.ENVIRONMENT` file and use `--env-file` to load it. It's straightforward, yet flexible.
207
208```bash
209$ echo "HELLO=production" > .env.production
210$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
211
212$ dotenvx run --env-file=.env.production -- node index.js
213Hello production
214> ^^
215```
216
217or with multiple .env files
218
219```bash
220$ echo "HELLO=local" > .env.local
221$ echo "HELLO=World" > .env
222$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
223
224$ dotenvx run --env-file=.env.local --env-file=.env -- node index.js
225Hello local
226```
227
228[more environment examples](https://dotenvx.com/docs/quickstart/environments)
229
230## πŸš€ Deploying
231
232Use [dotenvx](https://github.com/dotenvx/dotenvx).
233
234Add encryption to your `.env` files with a single command. Pass the `--encrypt` flag.
235
236```
237$ dotenvx set HELLO Production --encrypt -f .env.production
238$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
239
240$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
241[dotenvx] injecting env (2) from .env.production
242Hello Production
243```
244
245[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
246
247## πŸ“š Examples
248
249See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
250
251* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
252* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
253* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
254* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
255* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
256* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
257* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
258* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
259* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
260* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
261* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
262* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
263* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
264* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
265* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
266* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
267
268## πŸ“– Documentation
269
270Dotenv exposes four functions:
271
272* `config`
273* `parse`
274* `populate`
275* `decrypt`
276
277### Config
278
279`config` will read your `.env` file, parse the contents, assign it to
280[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
281and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
282
283```js
284const result = dotenv.config()
285
286if (result.error) {
287 throw result.error
288}
289
290console.log(result.parsed)
291```
292
293You can additionally, pass options to `config`.
294
295#### Options
296
297##### path
298
299Default: `path.resolve(process.cwd(), '.env')`
300
301Specify a custom path if your file containing environment variables is located elsewhere.
302
303```js
304require('dotenv').config({ path: '/custom/path/to/.env' })
305```
306
307By default, `config` will look for a file called .env in the current working directory.
308
309Pass 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.
310
311```js
312require('dotenv').config({ path: ['.env.local', '.env'] })
313```
314
315##### encoding
316
317Default: `utf8`
318
319Specify the encoding of your file containing environment variables.
320
321```js
322require('dotenv').config({ encoding: 'latin1' })
323```
324
325##### debug
326
327Default: `false`
328
329Turn on logging to help debug why certain keys or values are not being set as you expect.
330
331```js
332require('dotenv').config({ debug: process.env.DEBUG })
333```
334
335##### override
336
337Default: `false`
338
339Override 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.
340
341```js
342require('dotenv').config({ override: true })
343```
344
345##### processEnv
346
347Default: `process.env`
348
349Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
350
351```js
352const myObject = {}
353require('dotenv').config({ processEnv: myObject })
354
355console.log(myObject) // values from .env
356console.log(process.env) // this was not changed or written to
357```
358
359### Parse
360
361The engine which parses the contents of your file containing environment
362variables is available to use. It accepts a String or Buffer and will return
363an Object with the parsed keys and values.
364
365```js
366const dotenv = require('dotenv')
367const buf = Buffer.from('BASIC=basic')
368const config = dotenv.parse(buf) // will return an object
369console.log(typeof config, config) // object { BASIC : 'basic' }
370```
371
372#### Options
373
374##### debug
375
376Default: `false`
377
378Turn on logging to help debug why certain keys or values are not being set as you expect.
379
380```js
381const dotenv = require('dotenv')
382const buf = Buffer.from('hello world')
383const opt = { debug: true }
384const config = dotenv.parse(buf, opt)
385// expect a debug message because the buffer is not in KEY=VAL form
386```
387
388### Populate
389
390The 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.
391
392For example, customizing the source:
393
394```js
395const dotenv = require('dotenv')
396const parsed = { HELLO: 'world' }
397
398dotenv.populate(process.env, parsed)
399
400console.log(process.env.HELLO) // world
401```
402
403For example, customizing the source AND target:
404
405```js
406const dotenv = require('dotenv')
407const parsed = { HELLO: 'universe' }
408const target = { HELLO: 'world' } // empty object
409
410dotenv.populate(target, parsed, { override: true, debug: true })
411
412console.log(target) // { HELLO: 'universe' }
413```
414
415#### options
416
417##### Debug
418
419Default: `false`
420
421Turn on logging to help debug why certain keys or values are not being populated as you expect.
422
423##### override
424
425Default: `false`
426
427Override any environment variables that have already been set.
428
429## ❓ FAQ
430
431### Why is the `.env` file not loading my environment variables successfully?
432
433Most 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).
434
435Turn on debug mode and try again..
436
437```js
438require('dotenv').config({ debug: true })
439```
440
441You will receive a helpful error outputted to your console.
442
443### Should I commit my `.env` file?
444
445No. We **strongly** recommend against committing your `.env` file to version
446control. It should only include environment-specific values such as database
447passwords or API keys. Your production database should have a different
448password than your development database.
449
450### Should I have multiple `.env` files?
451
452We 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.
453
454> 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.
455>
456> – [The Twelve-Factor App](http://12factor.net/config)
457
458### What rules does the parsing engine follow?
459
460The parsing engine currently supports the following rules:
461
462- `BASIC=basic` becomes `{BASIC: 'basic'}`
463- empty lines are skipped
464- lines beginning with `#` are treated as comments
465- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
466- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
467- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
468- 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'}`)
469- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
470- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
471- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
472
473```
474{MULTILINE: 'new
475line'}
476```
477
478- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
479
480### What happens to environment variables that were already set?
481
482By 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.
483
484If instead, you want to override `process.env` use the `override` option.
485
486```javascript
487require('dotenv').config({ override: true })
488```
489
490### How come my environment variables are not showing up for React?
491
492Your 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.
493
494If 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.
495
496If 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.
497
498### Can I customize/write plugins for dotenv?
499
500Yes! `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:
501
502```js
503const dotenv = require('dotenv')
504const variableExpansion = require('dotenv-expand')
505const myEnv = dotenv.config()
506variableExpansion(myEnv)
507```
508
509### How do I use dotenv with `import`?
510
511Simply..
512
513```javascript
514// index.mjs (ESM)
515import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
516import express from 'express'
517```
518
519A little background..
520
521> 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.
522>
523> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
524
525What does this mean in plain language? It means you would think the following would work but it won't.
526
527`errorReporter.mjs`:
528```js
529class Client {
530 constructor (apiKey) {
531 console.log('apiKey', apiKey)
532
533 this.apiKey = apiKey
534 }
535}
536
537export default new Client(process.env.API_KEY)
538```
539`index.mjs`:
540```js
541// Note: this is INCORRECT and will not work
542import * as dotenv from 'dotenv'
543dotenv.config()
544
545import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
546```
547
548`process.env.API_KEY` will be blank.
549
550Instead, `index.mjs` should be written as..
551
552```js
553import 'dotenv/config'
554
555import errorReporter from './errorReporter.mjs'
556```
557
558Does 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).
559
560There are two alternatives to this approach:
561
5621. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
5632. 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)
564
565### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
566
567You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
568
569```bash
570npm install node-polyfill-webpack-plugin
571```
572
573Configure your `webpack.config.js` to something like the following.
574
575```js
576require('dotenv').config()
577
578const path = require('path');
579const webpack = require('webpack')
580
581const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
582
583module.exports = {
584 mode: 'development',
585 entry: './src/index.ts',
586 output: {
587 filename: 'bundle.js',
588 path: path.resolve(__dirname, 'dist'),
589 },
590 plugins: [
591 new NodePolyfillPlugin(),
592 new webpack.DefinePlugin({
593 'process.env': {
594 HELLO: JSON.stringify(process.env.HELLO)
595 }
596 }),
597 ]
598};
599```
600
601Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
602
603### What about variable expansion?
604
605Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
606
607### What about syncing and securing .env files?
608
609Use [dotenvx](https://github.com/dotenvx/dotenvx)
610
611### What if I accidentally commit my `.env` file to code?
612
613Remove 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.
614
615```
616brew install dotenvx/brew/dotenvx
617dotenvx precommit --install
618```
619
620### How can I prevent committing my `.env` file to a Docker build?
621
622Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).
623
624```bash
625# Dockerfile
626...
627RUN curl -fsS https://dotenvx.sh/ | sh
628...
629RUN dotenvx prebuild
630CMD ["dotenvx", "run", "--", "node", "index.js"]
631```
632
633## Contributing Guide
634
635See [CONTRIBUTING.md](CONTRIBUTING.md)
636
637## CHANGELOG
638
639See [CHANGELOG.md](CHANGELOG.md)
640
641## Who's using dotenv?
642
643[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
644
645Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
Note: See TracBrowser for help on using the repository browser.