CoolFace
Apppublic

HarshvardhanCn01/Voice-Assistant

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
README.md652 linesDownload Raw Back to dotenv
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<p>10  <sup>11    <a href="https://github.com/sponsors/motdotla">Dotenv is supported by the community.</a>12  </sup>13</p>14<sup>Special thanks to:</sup>15<br>16<br>17<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=dotenv_p_20220831">18  <div>19    <img src="https://res.cloudinary.com/dotenv-org/image/upload/v1661980709/warp_hi8oqj.png" width="230" alt="Warp">20  </div>21  <b>Warp is a blazingly fast, Rust-based terminal reimagined to work like a modern app.</b>22  <div>23    <sup>Get more done in the CLI with real text editing, block-based output, and AI command search.</sup>24  </div>25</a>26<br>27<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=dotenv&utm_source=github">28  <div>29    <img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_400/v1665605496/68747470733a2f2f73696e647265736f726875732e636f6d2f6173736574732f7468616e6b732f776f726b6f732d6c6f676f2d77686974652d62672e737667_zdmsbu.svg" width="270" alt="WorkOS">30  </div>31  <b>Your App, Enterprise Ready.</b>32  <div>33    <sup>Add Single Sign-On, Multi-Factor Auth, and more, in minutes instead of months.</sup>34  </div>35</a>36<hr>37</div>38 39# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)40 41<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />42 43Dotenv 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.44 45[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)46[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)47[![codecov](https://codecov.io/gh/motdotla/dotenv-expand/graph/badge.svg?token=pawWEyaMfg)](https://codecov.io/gh/motdotla/dotenv-expand)48 49* [🌱 Install](#-install)50* [πŸ—οΈ Usage (.env)](#%EF%B8%8F-usage)51* [🌴 Multiple Environments πŸ†•](#-manage-multiple-environments)52* [πŸš€ Deploying (encryption) πŸ†•](#-deploying)53* [πŸ“š Examples](#-examples)54* [πŸ“– Docs](#-documentation)55* [❓ FAQ](#-faq)56* [⏱️ Changelog](./CHANGELOG.md)57 58## 🌱 Install59 60```bash61# install locally (recommended)62npm install dotenv --save63```64 65Or installing with yarn? `yarn add dotenv`66 67## πŸ—οΈ Usage68 69<a href="https://www.youtube.com/watch?v=YtkZR0NFd1g">70<div align="right">71<img src="https://img.youtube.com/vi/YtkZR0NFd1g/hqdefault.jpg" alt="how to use dotenv video tutorial" align="right" width="330" />72<img src="https://simpleicons.vercel.app/youtube/ff0000" alt="youtube/@dotenvorg" align="right" width="24" />73</div>74</a>75 76Create 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):77 78```dosini79S3_BUCKET="YOURS3BUCKET"80SECRET_KEY="YOURSECRETKEYGOESHERE"81```82 83As early as possible in your application, import and configure dotenv:84 85```javascript86require('dotenv').config()87console.log(process.env) // remove this after you've confirmed it is working88```89 90.. [or using ES6?](#how-do-i-use-dotenv-with-import)91 92```javascript93import 'dotenv/config'94```95 96That's it. `process.env` now has the keys and values you defined in your `.env` file:97 98```javascript99require('dotenv').config()100// or import 'dotenv/config' if you're using ES6101 102...103 104s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})105```106 107### Multiline values108 109If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:110 111```dosini112PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----113...114Kh9NV...115...116-----END RSA PRIVATE KEY-----"117```118 119Alternatively, you can double quote strings and use the `\n` character:120 121```dosini122PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"123```124 125### Comments126 127Comments may be added to your file on their own line or inline:128 129```dosini130# This is a comment131SECRET_KEY=YOURSECRETKEYGOESHERE # comment132SECRET_HASH="something-with-a-#-hash"133```134 135Comments 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.136 137### Parsing138 139The 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.140 141```javascript142const dotenv = require('dotenv')143const buf = Buffer.from('BASIC=basic')144const config = dotenv.parse(buf) // will return an object145console.log(typeof config, config) // object { BASIC : 'basic' }146```147 148### Preload149 150> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.151>152> 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)153 154You 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.155 156```bash157$ node -r dotenv/config your_script.js158```159 160The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`161 162```bash163$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true164```165 166Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.167 168```bash169$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js170```171 172```bash173$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env174```175 176### Variable Expansion177 178You need to add the value of another variable in one of your variables? Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).179 180### Command Substitution181 182Use [dotenvx](https://github.com/dotenvx/dotenvx) to use command substitution.183 184Add the output of a command to one of your variables in your .env file.185 186```ini187# .env188DATABASE_URL="postgres://$(whoami)@localhost/my_database"189```190```js191// index.js192console.log('DATABASE_URL', process.env.DATABASE_URL)193```194```sh195$ dotenvx run --debug -- node index.js196[dotenvx@0.14.1] injecting env (1) from .env197DATABASE_URL postgres://yourusername@localhost/my_database198```199 200### Syncing201 202You 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.203 204### Multiple Environments205 206Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate `.env.ci`, `.env.production` files, and more.207 208### Deploying209 210You 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.211 212## 🌴 Manage Multiple Environments213 214Use [dotenvx](https://github.com/dotenvx/dotenvx)215 216Run any environment locally. Create a `.env.ENVIRONMENT` file and use `--env-file` to load it. It's straightforward, yet flexible.217 218```bash219$ echo "HELLO=production" > .env.production220$ echo "console.log('Hello ' + process.env.HELLO)" > index.js221 222$ dotenvx run --env-file=.env.production -- node index.js223Hello production224> ^^225```226 227or with multiple .env files228 229```bash230$ echo "HELLO=local" > .env.local231$ echo "HELLO=World" > .env232$ echo "console.log('Hello ' + process.env.HELLO)" > index.js233 234$ dotenvx run --env-file=.env.local --env-file=.env -- node index.js235Hello local236```237 238[more environment examples](https://dotenvx.com/docs/quickstart/environments)239 240## πŸš€ Deploying241 242Use [dotenvx](https://github.com/dotenvx/dotenvx).243 244Add encryption to your `.env` files with a single command. Pass the `--encrypt` flag.245 246```247$ dotenvx set HELLO Production --encrypt -f .env.production248$ echo "console.log('Hello ' + process.env.HELLO)" > index.js249 250$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js251[dotenvx] injecting env (2) from .env.production252Hello Production253```254 255[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)256 257## πŸ“š Examples258 259See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.260 261* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)262* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)263* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)264* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)265* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)266* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)267* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)268* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)269* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)270* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)271* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)272* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)273* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)274* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)275* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)276* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)277 278## πŸ“– Documentation279 280Dotenv exposes four functions:281 282* `config`283* `parse`284* `populate`285* `decrypt`286 287### Config288 289`config` will read your `.env` file, parse the contents, assign it to290[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),291and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.292 293```js294const result = dotenv.config()295 296if (result.error) {297  throw result.error298}299 300console.log(result.parsed)301```302 303You can additionally, pass options to `config`.304 305#### Options306 307##### path308 309Default: `path.resolve(process.cwd(), '.env')`310 311Specify a custom path if your file containing environment variables is located elsewhere.312 313```js314require('dotenv').config({ path: '/custom/path/to/.env' })315```316 317By default, `config` will look for a file called .env in the current working directory.318 319Pass 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. 320 321```js  322require('dotenv').config({ path: ['.env.local', '.env'] })323```324 325##### encoding326 327Default: `utf8`328 329Specify the encoding of your file containing environment variables.330 331```js332require('dotenv').config({ encoding: 'latin1' })333```334 335##### debug336 337Default: `false`338 339Turn on logging to help debug why certain keys or values are not being set as you expect.340 341```js342require('dotenv').config({ debug: process.env.DEBUG })343```344 345##### override346 347Default: `false`348 349Override 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. 350 351```js352require('dotenv').config({ override: true })353```354 355##### processEnv356 357Default: `process.env`358 359Specify an object to write your secrets to. Defaults to `process.env` environment variables.360 361```js362const myObject = {}363require('dotenv').config({ processEnv: myObject })364 365console.log(myObject) // values from .env366console.log(process.env) // this was not changed or written to367```368 369### Parse370 371The engine which parses the contents of your file containing environment372variables is available to use. It accepts a String or Buffer and will return373an Object with the parsed keys and values.374 375```js376const dotenv = require('dotenv')377const buf = Buffer.from('BASIC=basic')378const config = dotenv.parse(buf) // will return an object379console.log(typeof config, config) // object { BASIC : 'basic' }380```381 382#### Options383 384##### debug385 386Default: `false`387 388Turn on logging to help debug why certain keys or values are not being set as you expect.389 390```js391const dotenv = require('dotenv')392const buf = Buffer.from('hello world')393const opt = { debug: true }394const config = dotenv.parse(buf, opt)395// expect a debug message because the buffer is not in KEY=VAL form396```397 398### Populate399 400The 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.401 402For example, customizing the source:403 404```js405const dotenv = require('dotenv')406const parsed = { HELLO: 'world' }407 408dotenv.populate(process.env, parsed)409 410console.log(process.env.HELLO) // world411```412 413For example, customizing the source AND target:414 415```js416const dotenv = require('dotenv')417const parsed = { HELLO: 'universe' }418const target = { HELLO: 'world' } // empty object419 420dotenv.populate(target, parsed, { override: true, debug: true })421 422console.log(target) // { HELLO: 'universe' }423```424 425#### options426 427##### Debug428 429Default: `false`430 431Turn on logging to help debug why certain keys or values are not being populated as you expect.432 433##### override434 435Default: `false`436 437Override any environment variables that have already been set.438 439## ❓ FAQ440 441### Why is the `.env` file not loading my environment variables successfully?442 443Most 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).444 445Turn on debug mode and try again..446 447```js448require('dotenv').config({ debug: true })449```450 451You will receive a helpful error outputted to your console.452 453### Should I commit my `.env` file?454 455No. We **strongly** recommend against committing your `.env` file to version456control. It should only include environment-specific values such as database457passwords or API keys. Your production database should have a different458password than your development database.459 460### Should I have multiple `.env` files?461 462We 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.463 464> 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.465>466> – [The Twelve-Factor App](http://12factor.net/config)467 468### What rules does the parsing engine follow?469 470The parsing engine currently supports the following rules:471 472- `BASIC=basic` becomes `{BASIC: 'basic'}`473- empty lines are skipped474- lines beginning with `#` are treated as comments475- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)476- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)477- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)478- 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'}`)479- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)480- single and double quoted values maintain whitespace from both ends (`FOO="  some value  "` becomes `{FOO: '  some value  '}`)481- double quoted values expand new lines (`MULTILINE="new\nline"` becomes482 483```484{MULTILINE: 'new485line'}486```487 488- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)489 490### What happens to environment variables that were already set?491 492By 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.493 494If instead, you want to override `process.env` use the `override` option.495 496```javascript497require('dotenv').config({ override: true })498```499 500### How come my environment variables are not showing up for React?501 502Your 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.503 504If 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.505 506If 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.507 508### Can I customize/write plugins for dotenv?509 510Yes! `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:511 512```js513const dotenv = require('dotenv')514const variableExpansion = require('dotenv-expand')515const myEnv = dotenv.config()516variableExpansion(myEnv)517```518 519### How do I use dotenv with `import`?520 521Simply..522 523```javascript524// index.mjs (ESM)525import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import526import express from 'express'527```528 529A little background..530 531> 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.532>533> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)534 535What does this mean in plain language? It means you would think the following would work but it won't.536 537`errorReporter.mjs`:538```js539import { Client } from 'best-error-reporting-service'540 541export default new Client(process.env.API_KEY)542```543`index.mjs`:544```js545// Note: this is INCORRECT and will not work546import * as dotenv from 'dotenv'547dotenv.config()548 549import errorReporter from './errorReporter.mjs'550errorReporter.report(new Error('documented example'))551```552 553`process.env.API_KEY` will be blank.554 555Instead, `index.mjs` should be written as..556 557```js558import 'dotenv/config'559 560import errorReporter from './errorReporter.mjs'561errorReporter.report(new Error('documented example'))562```563 564Does 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).565 566There are two alternatives to this approach:567 5681. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)5692. 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)570 571### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?572 573You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:574 575```bash576npm install node-polyfill-webpack-plugin577```578 579Configure your `webpack.config.js` to something like the following.580 581```js582require('dotenv').config()583 584const path = require('path');585const webpack = require('webpack')586 587const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')588 589module.exports = {590  mode: 'development',591  entry: './src/index.ts',592  output: {593    filename: 'bundle.js',594    path: path.resolve(__dirname, 'dist'),595  },596  plugins: [597    new NodePolyfillPlugin(),598    new webpack.DefinePlugin({599      'process.env': {600        HELLO: JSON.stringify(process.env.HELLO)601      }602    }),603  ]604};605```606 607Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.608 609### What about variable expansion?610 611Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)612 613### What about syncing and securing .env files?614 615Use [dotenvx](https://github.com/dotenvx/dotenvx)616 617### What if I accidentally commit my `.env` file to code?618 619Remove 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. 620 621```622brew install dotenvx/brew/dotenvx623dotenvx precommit --install624```625 626### How can I prevent committing my `.env` file to a Docker build?627 628Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).629 630```bash631# Dockerfile632...633RUN curl -fsS https://dotenvx.sh/ | sh634...635RUN dotenvx prebuild636CMD ["dotenvx", "run", "--", "node", "index.js"]637```638 639## Contributing Guide640 641See [CONTRIBUTING.md](CONTRIBUTING.md)642 643## CHANGELOG644 645See [CHANGELOG.md](CHANGELOG.md)646 647## Who's using dotenv?648 649[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)650 651Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).652