| --- | ||
| name: dotenv | ||
| description: Load environment variables from a .env file into process.env for Node.js applications. Use when configuring apps with environment-specific secrets, setting up local development environments, managing API keys and database URLs, parsing .env file contents, or populating environment variables programmatically. Triggers on requests involving .env files, process.env, environment variable loading, twelve-factor app config, or Node.js secrets management. | ||
| --- | ||
| # dotenv | ||
| 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](https://12factor.net/config) methodology. | ||
| [Watch the tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g) | ||
| ## Usage | ||
| Install it. | ||
| ```sh | ||
| npm install dotenv --save | ||
| ``` | ||
| Create a `.env` file in the root of your project: | ||
| ```ini | ||
| # .env | ||
| S3_BUCKET="YOURS3BUCKET" | ||
| SECRET_KEY="YOURSECRETKEYGOESHERE" | ||
| ``` | ||
| And as early as possible in your application, import and configure dotenv: | ||
| ```javascript | ||
| require('dotenv').config() // or import 'dotenv/config' if you're using ES6 | ||
| ... | ||
| console.log(process.env) // remove this after you've confirmed it is working | ||
| ``` | ||
| That's it. `process.env` now has the keys and values you defined in your `.env` file: | ||
| ## Advanced | ||
| <details><summary>ES6</summary><br> | ||
| Import with [ES6](#how-do-i-use-dotenv-with-import): | ||
| ```javascript | ||
| import 'dotenv/config' | ||
| ``` | ||
| ES6 import if you need to set config options: | ||
| ```javascript | ||
| import dotenv from 'dotenv' | ||
| dotenv.config({ path: '/custom/path/to/.env' }) | ||
| ``` | ||
| </details> | ||
| <details><summary>bun</summary><br> | ||
| ```sh | ||
| bun add dotenv | ||
| ``` | ||
| </details> | ||
| <details><summary>yarn</summary><br> | ||
| ```sh | ||
| yarn add dotenv | ||
| ``` | ||
| </details> | ||
| <details><summary>pnpm</summary><br> | ||
| ```sh | ||
| pnpm add dotenv | ||
| ``` | ||
| </details> | ||
| <details><summary>Monorepos</summary><br> | ||
| For monorepos with a structure like `apps/backend/app.js`, put it the `.env` file in the root of the folder where your `app.js` process runs. | ||
| ```ini | ||
| # app/backend/.env | ||
| S3_BUCKET="YOURS3BUCKET" | ||
| SECRET_KEY="YOURSECRETKEYGOESHERE" | ||
| ``` | ||
| </details> | ||
| <details><summary>Multiline Values</summary><br> | ||
| If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks: | ||
| ```ini | ||
| PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- | ||
| ... | ||
| Kh9NV... | ||
| ... | ||
| -----END RSA PRIVATE KEY-----" | ||
| ``` | ||
| Alternatively, you can double quote strings and use the `\n` character: | ||
| ```ini | ||
| PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n" | ||
| ``` | ||
| </details> | ||
| <details><summary>Comments</summary><br> | ||
| Comments may be added to your file on their own line or inline: | ||
| ```ini | ||
| # This is a comment | ||
| SECRET_KEY=YOURSECRETKEYGOESHERE # comment | ||
| SECRET_HASH="something-with-a-#-hash" | ||
| ``` | ||
| Comments 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. | ||
| </details> | ||
| <details><summary>Parsing</summary><br> | ||
| The 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. | ||
| ```javascript | ||
| const dotenv = require('dotenv') | ||
| const buf = Buffer.from('BASIC=basic') | ||
| const config = dotenv.parse(buf) // will return an object | ||
| console.log(typeof config, config) // object { BASIC : 'basic' } | ||
| ``` | ||
| </details> | ||
| <details><summary>Preload</summary><br> | ||
| > Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so. | ||
| > | ||
| > 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://mot.la) | ||
| You 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. | ||
| ```bash | ||
| $ node -r dotenv/config your_script.js | ||
| ``` | ||
| The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value` | ||
| ```bash | ||
| $ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true | ||
| ``` | ||
| Additionally, you can use environment variables to set configuration options. Command line arguments will precede these. | ||
| ```bash | ||
| $ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js | ||
| ``` | ||
| ```bash | ||
| $ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env | ||
| ``` | ||
| </details> | ||
| <details><summary>Variable Expansion</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for variable expansion. | ||
| Reference and expand variables already on your machine for use in your .env file. | ||
| ```ini | ||
| # .env | ||
| USERNAME="username" | ||
| DATABASE_URL="postgres://${USERNAME}@localhost/my_database" | ||
| ``` | ||
| ```js | ||
| // index.js | ||
| console.log('DATABASE_URL', process.env.DATABASE_URL) | ||
| ``` | ||
| ```sh | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (2) from .env | ||
| DATABASE_URL postgres://username@localhost/my_database | ||
| ``` | ||
| </details> | ||
| <details><summary>Command Substitution</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for command substitution. | ||
| Add the output of a command to one of your variables in your .env file. | ||
| ```ini | ||
| # .env | ||
| DATABASE_URL="postgres://$(whoami)@localhost/my_database" | ||
| ``` | ||
| ```js | ||
| // index.js | ||
| console.log('DATABASE_URL', process.env.DATABASE_URL) | ||
| ``` | ||
| ```sh | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (1) from .env | ||
| DATABASE_URL postgres://yourusername@localhost/my_database | ||
| ``` | ||
| </details> | ||
| <details><summary>Encryption</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for encryption. | ||
| Add encryption to your `.env` files with a single command. | ||
| ``` | ||
| $ dotenvx set HELLO Production -f .env.production | ||
| $ echo "console.log('Hello ' + process.env.HELLO)" > index.js | ||
| $ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js | ||
| [dotenvx] injecting env (2) from .env.production | ||
| Hello Production | ||
| ``` | ||
| [learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption) | ||
| </details> | ||
| <details><summary>Multiple Environments</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to manage multiple environments. | ||
| Run any environment locally. Create a `.env.ENVIRONMENT` file and use `-f` to load it. It's straightforward, yet flexible. | ||
| ```bash | ||
| $ echo "HELLO=production" > .env.production | ||
| $ echo "console.log('Hello ' + process.env.HELLO)" > index.js | ||
| $ dotenvx run -f=.env.production -- node index.js | ||
| Hello production | ||
| > ^^ | ||
| ``` | ||
| or with multiple .env files | ||
| ```bash | ||
| $ echo "HELLO=local" > .env.local | ||
| $ echo "HELLO=World" > .env | ||
| $ echo "console.log('Hello ' + process.env.HELLO)" > index.js | ||
| $ dotenvx run -f=.env.local -f=.env -- node index.js | ||
| Hello local | ||
| ``` | ||
| [more environment examples](https://dotenvx.com/docs/quickstart/environments) | ||
| </details> | ||
| <details><summary>Production</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for production deploys. | ||
| Create a `.env.production` file. | ||
| ```sh | ||
| $ echo "HELLO=production" > .env.production | ||
| ``` | ||
| Encrypt it. | ||
| ```sh | ||
| $ dotenvx encrypt -f .env.production | ||
| ``` | ||
| Set `DOTENV_PRIVATE_KEY_PRODUCTION` (found in `.env.keys`) on your server. | ||
| ``` | ||
| $ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION=value | ||
| ``` | ||
| Commit your `.env.production` file to code and deploy. | ||
| ``` | ||
| $ git add .env.production | ||
| $ git commit -m "encrypted .env.production" | ||
| $ git push heroku main | ||
| ``` | ||
| Dotenvx will decrypt and inject the secrets at runtime using `dotenvx run -- node index.js`. | ||
| </details> | ||
| <details><summary>Syncing</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to sync your .env files. | ||
| Encrypt them with `dotenvx encrypt -f .env` and safely include them in source control. Your secrets are securely synced with your git. | ||
| This still subscribes to the twelve-factor app rules by generating a decryption key separate from code. | ||
| </details> | ||
| <details><summary>More Examples</summary><br> | ||
| See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations. | ||
| * [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs) | ||
| * [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug) | ||
| * [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override) | ||
| * [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target) | ||
| * [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm) | ||
| * [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload) | ||
| * [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript) | ||
| * [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse) | ||
| * [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config) | ||
| * [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack) | ||
| * [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2) | ||
| * [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react) | ||
| * [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript) | ||
| * [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express) | ||
| * [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs) | ||
| * [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify) | ||
| </details> | ||
| ## Agents | ||
| <img src="https://dotenvx.com/assets/img/as2/9.jpg" height="400" alt="dotenvx-as2" align="right"/> | ||
| > Software is changing, and dotenv must change with it—that is why I built [agentic secret storage (AS2)](https://dotenvx.com/as2). Agents run code without humans at terminals, so plaintext `.env` files are the wrong primitive. | ||
| > | ||
| > AS2 is built for autonomous software: encrypted by default, zero console access, and cryptography‑first delivery that keeps operators out of the loop. | ||
| > | ||
| > It is backed by [Vestauth](https://github.com/vestauth/vestauth), the trusted, pioneering auth layer for agents—giving each agent a cryptographic identity so requests are signed with private keys and verified with public keys. No shared secrets to leak. | ||
| > | ||
| > It's what I'm using now. - [motdotla](https://mot.la) | ||
| ### Quickstart | ||
| Install vestauth and initialize your agent. | ||
| ```bash | ||
| npm i -g vestauth | ||
| vestauth agent init | ||
| ``` | ||
| Your agent `set`s secrets with a simple `curl` endpoint: | ||
| ```bash | ||
| vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}' | ||
| ``` | ||
| And your agent `get`s secrets with a simple `curl` endpoint: | ||
| ```bash | ||
| vestauth agent curl "https://as2.dotenvx.com/get?key=KEY" | ||
| ``` | ||
| That's it! This new primitive unlocks secrets access for agents without human-in-the-loop, oauth flows, or API keys. It's the future for agents. | ||
| ## FAQ | ||
| <details><summary>Should I commit my `.env` file?</summary><br/> | ||
| No. | ||
| Unless you encrypt it with [dotenvx](https://github.com/dotenvx/dotenvx). Then we recommend you do. | ||
| </details> | ||
| <details><summary>What about variable expansion?</summary><br/> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx). | ||
| </details> | ||
| <details><summary>Should I have multiple `.env` files?</summary><br/> | ||
| We 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 from `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file. | ||
| > 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. | ||
| > | ||
| > – [The Twelve-Factor App](http://12factor.net/config) | ||
| Additionally, we recommend using [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt and manage these. | ||
| </details> | ||
| <details><summary>How do I use dotenv with `import`?</summary><br/> | ||
| Simply.. | ||
| ```javascript | ||
| // index.mjs (ESM) | ||
| import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import | ||
| import express from 'express' | ||
| ``` | ||
| A little background.. | ||
| > 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. | ||
| > | ||
| > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) | ||
| What does this mean in plain language? It means you would think the following would work but it won't. | ||
| `errorReporter.mjs`: | ||
| ```js | ||
| class Client { | ||
| constructor (apiKey) { | ||
| console.log('apiKey', apiKey) | ||
| this.apiKey = apiKey | ||
| } | ||
| } | ||
| export default new Client(process.env.API_KEY) | ||
| ``` | ||
| `index.mjs`: | ||
| ```js | ||
| // Note: this is INCORRECT and will not work | ||
| import * as dotenv from 'dotenv' | ||
| dotenv.config() | ||
| import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank! | ||
| ``` | ||
| `process.env.API_KEY` will be blank. | ||
| Instead, `index.mjs` should be written as.. | ||
| ```js | ||
| import 'dotenv/config' | ||
| import errorReporter from './errorReporter.mjs' | ||
| ``` | ||
| Does 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). | ||
| There are two alternatives to this approach: | ||
| 1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_) | ||
| 2. 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) | ||
| </details> | ||
| <details><summary>Can I customize/write plugins for dotenv?</summary><br/> | ||
| Yes! `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: | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const variableExpansion = require('dotenv-expand') | ||
| const myEnv = dotenv.config() | ||
| variableExpansion(myEnv) | ||
| ``` | ||
| </details> | ||
| <details><summary>What rules does the parsing engine follow?</summary><br/> | ||
| The parsing engine currently supports the following rules: | ||
| - `BASIC=basic` becomes `{BASIC: 'basic'}` | ||
| - empty lines are skipped | ||
| - lines beginning with `#` are treated as comments | ||
| - `#` marks the beginning of a comment (unless when the value is wrapped in quotes) | ||
| - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`) | ||
| - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`) | ||
| - 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'}`) | ||
| - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`) | ||
| - single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`) | ||
| - double quoted values expand new lines (`MULTILINE="new\nline"` becomes | ||
| ``` | ||
| {MULTILINE: 'new | ||
| line'} | ||
| ``` | ||
| - backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``) | ||
| </details> | ||
| <details><summary>What about syncing and securing .env files?</summary><br/> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to unlock syncing encrypted .env files over git. | ||
| </details> | ||
| <details><summary>What if I accidentally commit my `.env` file to code?</summary><br/> | ||
| Remove 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. | ||
| ``` | ||
| npm i -g @dotenvx/dotenvx | ||
| dotenvx precommit --install | ||
| ``` | ||
| </details> | ||
| <details><summary>What happens to environment variables that were already set?</summary><br/> | ||
| By 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. | ||
| If instead, you want to override `process.env` use the `override` option. | ||
| ```javascript | ||
| require('dotenv').config({ override: true }) | ||
| ``` | ||
| </details> | ||
| <details><summary>How can I prevent committing my `.env` file to a Docker build?</summary><br/> | ||
| Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild). | ||
| ```bash | ||
| # Dockerfile | ||
| ... | ||
| RUN curl -fsS https://dotenvx.sh/ | sh | ||
| ... | ||
| RUN dotenvx prebuild | ||
| CMD ["dotenvx", "run", "--", "node", "index.js"] | ||
| ``` | ||
| </details> | ||
| <details><summary>How come my environment variables are not showing up for React?</summary><br/> | ||
| Your 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. | ||
| If 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. | ||
| If 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. | ||
| </details> | ||
| <details><summary>Why is the `.env` file not loading my environment variables successfully?</summary><br/> | ||
| Most 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). | ||
| Turn on debug mode and try again.. | ||
| ```js | ||
| require('dotenv').config({ debug: true }) | ||
| ``` | ||
| You will receive a helpful error outputted to your console. | ||
| </details> | ||
| <details><summary>Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?</summary><br/> | ||
| You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following: | ||
| ```bash | ||
| npm install node-polyfill-webpack-plugin | ||
| ``` | ||
| Configure your `webpack.config.js` to something like the following. | ||
| ```js | ||
| require('dotenv').config() | ||
| const path = require('path'); | ||
| const webpack = require('webpack') | ||
| const NodePolyfillPlugin = require('node-polyfill-webpack-plugin') | ||
| module.exports = { | ||
| mode: 'development', | ||
| entry: './src/index.ts', | ||
| output: { | ||
| filename: 'bundle.js', | ||
| path: path.resolve(__dirname, 'dist'), | ||
| }, | ||
| plugins: [ | ||
| new NodePolyfillPlugin(), | ||
| new webpack.DefinePlugin({ | ||
| 'process.env': { | ||
| HELLO: JSON.stringify(process.env.HELLO) | ||
| } | ||
| }), | ||
| ] | ||
| }; | ||
| ``` | ||
| Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you. | ||
| </details> | ||
| ## Docs | ||
| Dotenv exposes four functions: | ||
| * `config` | ||
| * `parse` | ||
| * `populate` | ||
| ### Config | ||
| `config` will read your `.env` file, parse the contents, assign it to | ||
| [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env), | ||
| and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. | ||
| ```js | ||
| const result = dotenv.config() | ||
| if (result.error) { | ||
| throw result.error | ||
| } | ||
| console.log(result.parsed) | ||
| ``` | ||
| You can additionally, pass options to `config`. | ||
| #### Options | ||
| ##### path | ||
| Default: `path.resolve(process.cwd(), '.env')` | ||
| Specify a custom path if your file containing environment variables is located elsewhere. | ||
| ```js | ||
| require('dotenv').config({ path: '/custom/path/to/.env' }) | ||
| ``` | ||
| By default, `config` will look for a file called .env in the current working directory. | ||
| Pass 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. | ||
| ```js | ||
| require('dotenv').config({ path: ['.env.local', '.env'] }) | ||
| ``` | ||
| ##### quiet | ||
| Default: `false` | ||
| Suppress runtime logging message. | ||
| ```js | ||
| // index.js | ||
| require('dotenv').config({ quiet: false }) // change to true to suppress | ||
| console.log(`Hello ${process.env.HELLO}`) | ||
| ``` | ||
| ```ini | ||
| # .env | ||
| HELLO=World | ||
| ``` | ||
| ```sh | ||
| $ node index.js | ||
| [dotenv@17.0.0] injecting env (1) from .env | ||
| Hello World | ||
| ``` | ||
| ##### encoding | ||
| Default: `utf8` | ||
| Specify the encoding of your file containing environment variables. | ||
| ```js | ||
| require('dotenv').config({ encoding: 'latin1' }) | ||
| ``` | ||
| ##### debug | ||
| Default: `false` | ||
| Turn on logging to help debug why certain keys or values are not being set as you expect. | ||
| ```js | ||
| require('dotenv').config({ debug: process.env.DEBUG }) | ||
| ``` | ||
| ##### override | ||
| Default: `false` | ||
| Override 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. | ||
| ```js | ||
| require('dotenv').config({ override: true }) | ||
| ``` | ||
| ##### processEnv | ||
| Default: `process.env` | ||
| Specify an object to write your environment variables to. Defaults to `process.env` environment variables. | ||
| ```js | ||
| const myObject = {} | ||
| require('dotenv').config({ processEnv: myObject }) | ||
| console.log(myObject) // values from .env | ||
| console.log(process.env) // this was not changed or written to | ||
| ``` | ||
| ### Parse | ||
| The 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. | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const buf = Buffer.from('BASIC=basic') | ||
| const config = dotenv.parse(buf) // will return an object | ||
| console.log(typeof config, config) // object { BASIC : 'basic' } | ||
| ``` | ||
| #### Options | ||
| ##### debug | ||
| Default: `false` | ||
| Turn on logging to help debug why certain keys or values are not being set as you expect. | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const buf = Buffer.from('hello world') | ||
| const opt = { debug: true } | ||
| const config = dotenv.parse(buf, opt) | ||
| // expect a debug message because the buffer is not in KEY=VAL form | ||
| ``` | ||
| ### Populate | ||
| The 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. | ||
| For example, customizing the source: | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const parsed = { HELLO: 'world' } | ||
| dotenv.populate(process.env, parsed) | ||
| console.log(process.env.HELLO) // world | ||
| ``` | ||
| For example, customizing the source AND target: | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const parsed = { HELLO: 'universe' } | ||
| const target = { HELLO: 'world' } // empty object | ||
| dotenv.populate(target, parsed, { override: true, debug: true }) | ||
| console.log(target) // { HELLO: 'universe' } | ||
| ``` | ||
| #### options | ||
| ##### Debug | ||
| Default: `false` | ||
| Turn on logging to help debug why certain keys or values are not being populated as you expect. | ||
| ##### override | ||
| Default: `false` | ||
| Override any environment variables that have already been set. | ||
| ## CHANGELOG | ||
| See [CHANGELOG.md](CHANGELOG.md) | ||
| ## Who's using dotenv? | ||
| [These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv) | ||
| Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv). |
| --- | ||
| name: dotenvx | ||
| description: Encrypt .env files, use multiple environments, expand variables, and run any command with environment variables injected using dotenvx. Use when the task involves secret encryption, .env.production or .env.staging setups, variable expansion like ${DATABASE_URL}, running CLI commands with env vars, CI/CD secret management, or migrating beyond basic dotenv. Triggers on requests involving dotenvx, encrypted .env files, multiple environment configs, agentic secret storage, or AS2. | ||
| --- | ||
| # dotenvx | ||
| *a secure dotenv* — from the creator of [`dotenv`](https://github.com/motdotla/dotenv). | ||
| * run anywhere (cross-platform) | ||
| * multi-environment | ||
| * encrypted envs | ||
| [Read the whitepaper](https://dotenvx.com/dotenvx.pdf?v=README) | ||
| ## Quickstart | ||
| Install and use it in code just like `dotenv`. | ||
| ```sh | ||
| npm install @dotenvx/dotenvx --save | ||
| ``` | ||
| ```js | ||
| // index.js | ||
| require('@dotenvx/dotenvx').config() | ||
| // or import '@dotenvx/dotenvx/config' // for esm | ||
| console.log(`Hello ${process.env.HELLO}`) | ||
| ``` | ||
| or install globally — *unlocks dotenv for any language, framework, or platform!* | ||
| ```sh | ||
| # curl | ||
| curl -sfS https://dotenvx.sh | sh | ||
| # brew | ||
| brew install dotenvx/brew/dotenvx | ||
| # docker | ||
| docker run -it --rm -v $(pwd):/app dotenv/dotenvx help | ||
| # windows | ||
| winget install dotenvx | ||
| ``` | ||
| ## Run Anywhere | ||
| ```sh | ||
| $ echo "HELLO=World" > .env | ||
| $ echo "console.log('Hello ' + process.env.HELLO)" > index.js | ||
| $ node index.js | ||
| Hello undefined # without dotenvx | ||
| $ dotenvx run -- node index.js | ||
| Hello World # with dotenvx | ||
| ``` | ||
| Works with TypeScript, Deno, Bun, Python, PHP, Ruby, Go, Rust, Java, .NET, Bash, and more. See [extended quickstart guide](https://dotenvx.com/docs/quickstart). | ||
| Framework shortcuts: | ||
| ```sh | ||
| $ dotenvx run -- next dev | ||
| $ dotenvx run -- npm start | ||
| $ dotenvx run -- bin/rails s | ||
| $ dotenvx run -- php artisan serve | ||
| ``` | ||
| ## Multiple Environments | ||
| Create a `.env.production` file and use `-f` to load it: | ||
| ```sh | ||
| $ echo "HELLO=production" > .env.production | ||
| $ echo "console.log('Hello ' + process.env.HELLO)" > index.js | ||
| $ dotenvx run -f .env.production -- node index.js | ||
| [dotenvx@1.X.X] injecting env (1) from .env.production | ||
| Hello production | ||
| ``` | ||
| Load multiple files (first value wins): | ||
| ```sh | ||
| $ echo "HELLO=local" > .env.local | ||
| $ echo "HELLO=World" > .env | ||
| $ dotenvx run -f .env.local -f .env -- node index.js | ||
| [dotenvx@1.X.X] injecting env (1) from .env.local,.env | ||
| Hello local | ||
| ``` | ||
| Use `--overload` to make subsequent files win instead: | ||
| ```sh | ||
| $ dotenvx run -f .env.local -f .env --overload -- node index.js | ||
| Hello World | ||
| ``` | ||
| ### Convention-based loading | ||
| ```sh | ||
| # Next.js convention | ||
| $ dotenvx run --convention=nextjs -- node index.js | ||
| # dotenv-flow convention | ||
| $ dotenvx run --convention=flow -- node index.js | ||
| ``` | ||
| ## Encryption | ||
| Add encryption to your `.env` files with a single command: | ||
| ```sh | ||
| $ dotenvx encrypt | ||
| ✔ encrypted (.env) | ||
| ``` | ||
| A `DOTENV_PUBLIC_KEY` (encryption key) and a `DOTENV_PRIVATE_KEY` (decryption key) are generated using the same public-key cryptography as Bitcoin (secp256k1). | ||
| Encrypt a specific environment file: | ||
| ```sh | ||
| $ dotenvx encrypt -f .env.production | ||
| ``` | ||
| Decrypt at runtime by setting the private key (found in `.env.keys`): | ||
| ```sh | ||
| $ DOTENV_PRIVATE_KEY="<key from .env.keys>" dotenvx run -- node index.js | ||
| [dotenvx@1.X.X] injecting env (2) from .env | ||
| Hello World | ||
| ``` | ||
| Per-environment private keys follow the pattern `DOTENV_PRIVATE_KEY_<ENVIRONMENT>`: | ||
| ```sh | ||
| $ DOTENV_PRIVATE_KEY_PRODUCTION="<key>" dotenvx run -- node index.js | ||
| # loads .env.production | ||
| $ DOTENV_PRIVATE_KEY_CI="<key>" dotenvx run -- node index.js | ||
| # loads .env.ci | ||
| ``` | ||
| Combine multiple encrypted files: | ||
| ```sh | ||
| $ DOTENV_PRIVATE_KEY="<key>" DOTENV_PRIVATE_KEY_PRODUCTION="<key>" dotenvx run -- node index.js | ||
| [dotenvx@1.X.X] injecting env (3) from .env, .env.production | ||
| ``` | ||
| **Commit the encrypted `.env` file. Never commit `.env.keys`.** | ||
| ```sh | ||
| # .gitignore | ||
| .env.keys | ||
| ``` | ||
| ## CI/CD | ||
| ```yaml | ||
| # GitHub Actions | ||
| - name: Run app | ||
| env: | ||
| DOTENV_PRIVATE_KEY_PRODUCTION: ${{ secrets.DOTENV_PRIVATE_KEY_PRODUCTION }} | ||
| run: dotenvx run -f .env.production -- node index.js | ||
| ``` | ||
| Install in CI: | ||
| ```sh | ||
| curl -fsS https://dotenvx.sh/install.sh | sh | ||
| ``` | ||
| ## Advanced | ||
| ### Variable Expansion | ||
| Reference and expand variables already on your machine: | ||
| ```ini | ||
| # .env | ||
| USERNAME="username" | ||
| DATABASE_URL="postgres://${USERNAME}@localhost/my_database" | ||
| ``` | ||
| ```sh | ||
| $ dotenvx run -- node index.js | ||
| DATABASE_URL postgres://username@localhost/my_database | ||
| ``` | ||
| ### Default Values | ||
| ```ini | ||
| # .env | ||
| DATABASE_HOST=${DB_HOST:-localhost} | ||
| DATABASE_PORT=${DB_PORT:-5432} | ||
| ``` | ||
| ### Alternate Values | ||
| ```ini | ||
| # .env | ||
| NODE_ENV=production | ||
| DEBUG_MODE=${NODE_ENV:+false} | ||
| ``` | ||
| ### Interpolation Syntax Summary | ||
| ```ini | ||
| # Default value - use variable if set/non-empty, otherwise use default | ||
| TEST=${DEFINED_VAR:-fallback} # "hello" (if DEFINED_VAR=hello) | ||
| TEST=${UNDEFINED_VAR:-fallback} # "fallback" | ||
| # Default value (no colon) - use variable if set, otherwise use default | ||
| TEST=${EMPTY_VAR-fallback} # "" (empty, but set) | ||
| TEST=${UNDEFINED_VAR-fallback} # "fallback" | ||
| # Alternate value - use alternate if variable is set/non-empty, otherwise empty | ||
| TEST=${DEFINED_VAR:+alternate} # "alternate" | ||
| TEST=${EMPTY_VAR:+alternate} # "" (empty) | ||
| # Alternate value (no colon) - use alternate if variable is set, otherwise empty | ||
| TEST=${EMPTY_VAR+alternate} # "alternate" (empty but set counts) | ||
| ``` | ||
| ### Command Substitution | ||
| ```ini | ||
| # .env | ||
| DATABASE_URL="postgres://$(whoami)@localhost/my_database" | ||
| ``` | ||
| ### `get` — Read a value | ||
| ```sh | ||
| $ echo "HELLO=World" > .env | ||
| $ dotenvx get HELLO | ||
| World | ||
| $ dotenvx get HELLO -f .env.production | ||
| production | ||
| $ dotenvx get # all key/value pairs as JSON | ||
| {"HELLO":"World"} | ||
| ``` | ||
| ### `set` — Write a value (auto-encrypts if file is encrypted) | ||
| ```sh | ||
| $ dotenvx set HELLO World | ||
| $ dotenvx set HELLO Production -f .env.production | ||
| ``` | ||
| ### Pre-commit hook — Prevent committing plaintext secrets | ||
| ```sh | ||
| npm i -g @dotenvx/dotenvx | ||
| dotenvx precommit --install | ||
| ``` | ||
| ### `--strict` — Fail on errors | ||
| ```sh | ||
| $ dotenvx run -f .env.missing --strict -- node index.js | ||
| [MISSING_ENV_FILE] missing .env.missing file | ||
| ``` | ||
| ### Quiet / Debug / Log levels | ||
| ```sh | ||
| $ dotenvx run -f .env.production --quiet -- node index.js # suppress output | ||
| $ dotenvx run -f .env.production --debug -- node index.js # verbose debug | ||
| $ dotenvx run -f .env.production --log-level=error -- node index.js | ||
| ``` | ||
| ## Agentic Secret Storage (AS2) | ||
| > Agents run code without humans at terminals, so plaintext `.env` files are the wrong primitive. AS2 is built for autonomous software: encrypted by default, zero console access, and cryptography‑first delivery. | ||
| Install vestauth and initialize your agent: | ||
| ```bash | ||
| npm i -g vestauth | ||
| vestauth agent init | ||
| ``` | ||
| Set secrets: | ||
| ```bash | ||
| vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}' | ||
| ``` | ||
| Get secrets: | ||
| ```bash | ||
| vestauth agent curl "https://as2.dotenvx.com/get?key=KEY" | ||
| ``` | ||
| See [dotenvx.com/as2](https://dotenvx.com/as2) for the full specification. | ||
| ## Comparison: dotenv vs dotenvx | ||
| | Feature | dotenv | dotenvx | | ||
| |---------|--------|---------| | ||
| | Load `.env` | ✅ | ✅ | | ||
| | Variable expansion | ❌ | ✅ | | ||
| | Command substitution | ❌ | ✅ | | ||
| | Encryption | ❌ | ✅ | | ||
| | Multiple environments | basic | ✅ | | ||
| | Works with any language | ❌ | ✅ | | ||
| | Agentic secret storage | ❌ | ✅ | | ||
| For basic `.env` loading in Node.js, see the [dotenv skill](../dotenv/SKILL.md). | ||
| ## FAQ | ||
| **Should I commit my `.env` file?** | ||
| No — unless you encrypt it with `dotenvx encrypt`. Then yes, commit the encrypted `.env` and keep `.env.keys` out of source control. | ||
| **How do I use dotenvx in Docker?** | ||
| ```sh | ||
| FROM node:latest | ||
| RUN curl -fsS https://dotenvx.sh/install.sh | sh | ||
| CMD ["dotenvx", "run", "--", "node", "index.js"] | ||
| ``` | ||
| **How do I handle environment variable precedence in containers?** | ||
| By default, existing environment variables take precedence over `.env` files (historic dotenv principle). Use `--overload` to make `.env` files win instead. | ||
| ```sh | ||
| # Env var from cloud provider wins (default) | ||
| $ MODEL_REGISTRY=registry.azure.com/v2 dotenvx run -f .env.prod -- node app.js | ||
| # .env.prod wins (with --overload) | ||
| $ MODEL_REGISTRY=registry.azure.com/v2 dotenvx run -f .env.prod --overload -- node app.js | ||
| ``` |
+11
-1
@@ -5,4 +5,14 @@ # Changelog | ||
| ## [Unreleased](https://github.com/motdotla/dotenv/compare/v17.3.1...master) | ||
| ## [Unreleased](https://github.com/motdotla/dotenv/compare/v17.4.0...master) | ||
| ## [17.4.0](https://github.com/motdotla/dotenv/compare/v17.3.1...v17.4.0) (2026-04-01) | ||
| ### Added | ||
| * Add `skills/` folder with focused agent skills: `skills/dotenv/SKILL.md` (core usage) and `skills/dotenvx/SKILL.md` (encryption, multiple environments, variable expansion) for AI coding agent discovery via the skills.sh ecosystem (`npx skills add motdotla/dotenv`) | ||
| ### Changed | ||
| * Tighten up logs: `◇ injecting env (14) from .env` ([#1003](https://github.com/motdotla/dotenv/pull/1003)) | ||
| ## [17.3.1](https://github.com/motdotla/dotenv/compare/v17.3.0...v17.3.1) (2026-02-12) | ||
@@ -9,0 +19,0 @@ |
+5
-5
@@ -98,3 +98,3 @@ // TypeScript Version: 3.0 | ||
| type DotenvError = Error & { | ||
| code: | ||
| code: | ||
| | 'MISSING_DATA' | ||
@@ -113,3 +113,3 @@ | 'INVALID_DOTENV_KEY' | ||
| * | ||
| * example: `require('dotenv').config({ debug: process.env.DEBUG })` | ||
| * example: `require('dotenv').populate(processEnv, parsed, { debug: true })` | ||
| */ | ||
@@ -123,3 +123,3 @@ debug?: boolean; | ||
| * | ||
| * example: `require('dotenv').config({ override: true })` | ||
| * example: `require('dotenv').populate(processEnv, parsed, { override: true })` | ||
| */ | ||
@@ -162,3 +162,3 @@ override?: boolean; | ||
| * @param parsed - the source JSON object | ||
| * @param options - additional options. example: `{ quiet: false, debug: true, override: false }` | ||
| * @param options - additional options. example: `{ debug: true, override: false }` | ||
| * @returns an object with the keys and values that were actually set | ||
@@ -170,3 +170,3 @@ * | ||
| parsed: DotenvPopulateInput, | ||
| options?: DotenvConfigOptions | ||
| options?: DotenvPopulateOptions | ||
| ): DotenvPopulateOutput; | ||
@@ -173,0 +173,0 @@ |
+17
-25
@@ -5,21 +5,13 @@ const fs = require('fs') | ||
| const crypto = require('crypto') | ||
| const packageJson = require('../package.json') | ||
| const version = packageJson.version | ||
| // Array of tips to display randomly | ||
| const TIPS = [ | ||
| '🔐 encrypt with Dotenvx: https://dotenvx.com', | ||
| '🔐 prevent committing .env to code: https://dotenvx.com/precommit', | ||
| '🔐 prevent building .env in docker: https://dotenvx.com/prebuild', | ||
| '🤖 agentic secret storage: https://dotenvx.com/as2', | ||
| '⚡️ secrets for agents: https://dotenvx.com/as2', | ||
| '🛡️ auth for agents: https://vestauth.com', | ||
| '🛠️ run anywhere with `dotenvx run -- yourcommand`', | ||
| '⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }', | ||
| '⚙️ enable debug logging with { debug: true }', | ||
| '⚙️ override existing env vars with { override: true }', | ||
| '⚙️ suppress all logs with { quiet: true }', | ||
| '⚙️ write to custom object with { processEnv: myObject }', | ||
| '⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }' | ||
| '◈ encrypted .env [www.dotenvx.com]', | ||
| '◈ secrets for agents [www.dotenvx.com]', | ||
| '⌁ auth for agents [www.vestauth.com]', | ||
| '⌘ custom filepath { path: \'/custom/path/.env\' }', | ||
| '⌘ enable debugging { debug: true }', | ||
| '⌘ override existing { override: true }', | ||
| '⌘ suppress logs { quiet: true }', | ||
| '⌘ multiple files { path: [\'.env.local\', \'.env\'] }' | ||
| ] | ||
@@ -132,11 +124,11 @@ | ||
| function _warn (message) { | ||
| console.error(`[dotenv@${version}][WARN] ${message}`) | ||
| console.error(`⚠ ${message}`) | ||
| } | ||
| function _debug (message) { | ||
| console.log(`[dotenv@${version}][DEBUG] ${message}`) | ||
| console.log(`┆ ${message}`) | ||
| } | ||
| function _log (message) { | ||
| console.log(`[dotenv@${version}] ${message}`) | ||
| console.log(`◇ ${message}`) | ||
| } | ||
@@ -235,3 +227,3 @@ | ||
| if (debug || !quiet) { | ||
| _log('Loading env from encrypted .env.vault') | ||
| _log('loading env from encrypted .env.vault') | ||
| } | ||
@@ -265,3 +257,3 @@ | ||
| if (debug) { | ||
| _debug('No encoding is specified. UTF-8 is used by default') | ||
| _debug('no encoding is specified (UTF-8 is used by default)') | ||
| } | ||
@@ -294,3 +286,3 @@ } | ||
| if (debug) { | ||
| _debug(`Failed to load ${path} ${e.message}`) | ||
| _debug(`failed to load ${path} ${e.message}`) | ||
| } | ||
@@ -316,3 +308,3 @@ lastError = e | ||
| if (debug) { | ||
| _debug(`Failed to load ${filePath} ${e.message}`) | ||
| _debug(`failed to load ${filePath} ${e.message}`) | ||
| } | ||
@@ -323,3 +315,3 @@ lastError = e | ||
| _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`) | ||
| _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`// tip: ${_getRandomTip()}`)}`) | ||
| } | ||
@@ -345,3 +337,3 @@ | ||
| if (!vaultPath) { | ||
| _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`) | ||
| _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`) | ||
@@ -348,0 +340,0 @@ return DotenvModule.configDotenv(options) |
+1
-1
| { | ||
| "name": "dotenv", | ||
| "version": "17.3.1", | ||
| "version": "17.4.0", | ||
| "description": "Loads environment variables from .env file", | ||
@@ -5,0 +5,0 @@ "main": "lib/main.js", |
+175
-207
@@ -0,1 +1,3 @@ | ||
| <a href="https://dotenvx.com/?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=banner"><img src="https://dotenvx.com/dotenv-banner.png" alt="dotenvx" /></a> | ||
| # dotenv [](https://www.npmjs.com/package/dotenv) [](https://www.npmjs.com/package/dotenv) | ||
@@ -5,11 +7,11 @@ | ||
| 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](https://12factor.net/config) methodology. | ||
| Dotenv es un módulo sin dependencias que carga variables de entorno desde un archivo `.env` en [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Guardar la configuración en el entorno, separada del código, se basa en la metodología de [The Twelve-Factor App](https://12factor.net/config). | ||
| [Watch the tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g) | ||
| [Ver el tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g) | ||
| | ||
| ## Usage | ||
| ## Uso | ||
| Install it. | ||
| Instálalo. | ||
@@ -20,3 +22,3 @@ ```sh | ||
| Create a `.env` file in the root of your project: | ||
| Crea un archivo `.env` en la raíz de tu proyecto: | ||
@@ -29,19 +31,24 @@ ```ini | ||
| And as early as possible in your application, import and configure dotenv: | ||
| Y lo antes posible en tu aplicación, importa y configura dotenv: | ||
| ```javascript | ||
| require('dotenv').config() // or import 'dotenv/config' if you're using ES6 | ||
| // index.js | ||
| require('dotenv').config() // o import 'dotenv/config' si usas ES6 | ||
| ... | ||
| console.log(process.env) // remove this after you've confirmed it is working | ||
| console.log(process.env) // elimínalo después de confirmar que funciona | ||
| ``` | ||
| ```sh | ||
| $ node index.js | ||
| ◇ injecting env (14) from .env | ||
| ``` | ||
| That's it. `process.env` now has the keys and values you defined in your `.env` file: | ||
| Eso es todo. `process.env` ahora tiene las claves y valores que definiste en tu archivo `.env`. | ||
| | ||
| ## Advanced | ||
| ## Avanzado | ||
| <details><summary>ES6</summary><br> | ||
| Import with [ES6](#how-do-i-use-dotenv-with-import): | ||
| Importa con [ES6](#como-uso-dotenv-con-import): | ||
@@ -52,3 +59,3 @@ ```javascript | ||
| ES6 import if you need to set config options: | ||
| Import con ES6 si necesitas establecer opciones de configuración: | ||
@@ -84,3 +91,3 @@ ```javascript | ||
| For monorepos with a structure like `apps/backend/app.js`, put it the `.env` file in the root of the folder where your `app.js` process runs. | ||
| Para monorepos con una estructura como `apps/backend/app.js`, coloca el archivo `.env` en la raíz de la carpeta donde corre tu proceso `app.js`. | ||
@@ -94,5 +101,5 @@ ```ini | ||
| </details> | ||
| <details><summary>Multiline Values</summary><br> | ||
| <details><summary>Valores Multilínea</summary><br> | ||
| If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks: | ||
| Si necesitas variables multilínea, por ejemplo claves privadas, ya son compatibles (`>= v15.0.0`) con saltos de línea: | ||
@@ -107,3 +114,3 @@ ```ini | ||
| Alternatively, you can double quote strings and use the `\n` character: | ||
| Como alternativa, puedes usar comillas dobles y el carácter `\n`: | ||
@@ -115,18 +122,18 @@ ```ini | ||
| </details> | ||
| <details><summary>Comments</summary><br> | ||
| <details><summary>Comentarios</summary><br> | ||
| Comments may be added to your file on their own line or inline: | ||
| Puedes agregar comentarios en su propia línea o al final de una línea: | ||
| ```ini | ||
| # This is a comment | ||
| SECRET_KEY=YOURSECRETKEYGOESHERE # comment | ||
| # Este es un comentario | ||
| SECRET_KEY=YOURSECRETKEYGOESHERE # comentario | ||
| SECRET_HASH="something-with-a-#-hash" | ||
| ``` | ||
| Comments 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. | ||
| Los comentarios empiezan donde aparece `#`, así que si tu valor contiene `#` debes envolverlo entre comillas. Este es un cambio incompatible desde `>= v15.0.0`. | ||
| </details> | ||
| <details><summary>Parsing</summary><br> | ||
| <details><summary>Análisis</summary><br> | ||
| The 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. | ||
| El motor que analiza el contenido del archivo de variables de entorno está disponible para su uso. Acepta un String o Buffer y devuelve un objeto con las claves y valores analizados. | ||
@@ -136,14 +143,14 @@ ```javascript | ||
| const buf = Buffer.from('BASIC=basic') | ||
| const config = dotenv.parse(buf) // will return an object | ||
| console.log(typeof config, config) // object { BASIC : 'basic' } | ||
| const config = dotenv.parse(buf) // devolverá un objeto | ||
| console.log(typeof config, config) // objeto { BASIC : 'basic' } | ||
| ``` | ||
| </details> | ||
| <details><summary>Preload</summary><br> | ||
| <details><summary>Precarga</summary><br> | ||
| > Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so. | ||
| > Nota: considera usar [`dotenvx`](https://github.com/dotenvx/dotenvx) en lugar de precargar. Ahora lo hago (y lo recomiendo). | ||
| > | ||
| > 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://mot.la) | ||
| > Cumple el mismo propósito (no necesitas hacer require y cargar dotenv), agrega mejor depuración y funciona con CUALQUIER lenguaje, framework o plataforma. – [motdotla](https://not.la) | ||
| You 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. | ||
| Puedes usar la [opción de línea de comandos](https://nodejs.org/api/cli.html#-r---require-module) `--require` (`-r`) para precargar dotenv. Con esto no necesitas requerir ni cargar dotenv en el código de tu aplicación. | ||
@@ -154,3 +161,3 @@ ```bash | ||
| The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value` | ||
| Las opciones de configuración de abajo se aceptan como argumentos de línea de comandos en el formato `dotenv_config_<option>=value` | ||
@@ -161,3 +168,3 @@ ```bash | ||
| Additionally, you can use environment variables to set configuration options. Command line arguments will precede these. | ||
| Además, puedes usar variables de entorno para establecer opciones de configuración. Los argumentos de línea de comandos tienen prioridad. | ||
@@ -173,7 +180,7 @@ ```bash | ||
| </details> | ||
| <details><summary>Variable Expansion</summary><br> | ||
| <details><summary>Expansión de Variables</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for variable expansion. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para expansión de variables. | ||
| Reference and expand variables already on your machine for use in your .env file. | ||
| Referencia y expande variables que ya existen en tu máquina para usarlas en tu archivo .env. | ||
@@ -191,3 +198,3 @@ ```ini | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (2) from .env | ||
| ⟐ injecting env (2) from .env · dotenvx@1.59.1 | ||
| DATABASE_URL postgres://username@localhost/my_database | ||
@@ -197,7 +204,7 @@ ``` | ||
| </details> | ||
| <details><summary>Command Substitution</summary><br> | ||
| <details><summary>Sustitución de Comandos</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for command substitution. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para sustitución de comandos. | ||
| Add the output of a command to one of your variables in your .env file. | ||
| Agrega la salida de un comando a una de tus variables en tu archivo .env. | ||
@@ -214,3 +221,3 @@ ```ini | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (1) from .env | ||
| ⟐ injecting env (1) from .env · dotenvx@1.59.1 | ||
| DATABASE_URL postgres://yourusername@localhost/my_database | ||
@@ -220,7 +227,7 @@ ``` | ||
| </details> | ||
| <details><summary>Encryption</summary><br> | ||
| <details><summary>Cifrado</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for encryption. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para cifrado. | ||
| Add encryption to your `.env` files with a single command. | ||
| Agrega cifrado a tus archivos `.env` con un solo comando. | ||
@@ -232,14 +239,14 @@ ``` | ||
| $ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js | ||
| [dotenvx] injecting env (2) from .env.production | ||
| ⟐ injecting env (2) from .env.production · dotenvx@1.59.1 | ||
| Hello Production | ||
| ``` | ||
| [learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption) | ||
| [más información](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption) | ||
| </details> | ||
| <details><summary>Multiple Environments</summary><br> | ||
| <details><summary>Múltiples Entornos</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to manage multiple environments. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para administrar múltiples entornos. | ||
| Run any environment locally. Create a `.env.ENVIRONMENT` file and use `-f` to load it. It's straightforward, yet flexible. | ||
| Ejecuta cualquier entorno localmente. Crea un archivo `.env.ENVIRONMENT` y usa `-f` para cargarlo. Es simple y flexible. | ||
@@ -255,3 +262,3 @@ ```bash | ||
| or with multiple .env files | ||
| o con múltiples archivos .env | ||
@@ -267,10 +274,10 @@ ```bash | ||
| [more environment examples](https://dotenvx.com/docs/quickstart/environments) | ||
| [más ejemplos de entornos](https://dotenvx.com/docs/quickstart/environments?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-environments) | ||
| </details> | ||
| <details><summary>Production</summary><br> | ||
| <details><summary>Producción</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) for production deploys. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para despliegues en producción. | ||
| Create a `.env.production` file. | ||
| Crea un archivo `.env.production`. | ||
@@ -281,3 +288,3 @@ ```sh | ||
| Encrypt it. | ||
| Cífralo. | ||
@@ -288,3 +295,3 @@ ```sh | ||
| Set `DOTENV_PRIVATE_KEY_PRODUCTION` (found in `.env.keys`) on your server. | ||
| Configura `DOTENV_PRIVATE_KEY_PRODUCTION` (está en `.env.keys`) en tu servidor. | ||
@@ -295,3 +302,3 @@ ``` | ||
| Commit your `.env.production` file to code and deploy. | ||
| Haz commit de tu archivo `.env.production` y despliega. | ||
@@ -304,17 +311,17 @@ ``` | ||
| Dotenvx will decrypt and inject the secrets at runtime using `dotenvx run -- node index.js`. | ||
| Dotenvx descifrará e inyectará los secretos en runtime usando `dotenvx run -- node index.js`. | ||
| </details> | ||
| <details><summary>Syncing</summary><br> | ||
| <details><summary>Sincronización</summary><br> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to sync your .env files. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para sincronizar tus archivos .env. | ||
| Encrypt them with `dotenvx encrypt -f .env` and safely include them in source control. Your secrets are securely synced with your git. | ||
| Cífralos con `dotenvx encrypt -f .env` e inclúyelos de forma segura en el control de código fuente. Tus secretos se sincronizan de forma segura con git. | ||
| This still subscribes to the twelve-factor app rules by generating a decryption key separate from code. | ||
| Esto sigue las reglas de Twelve-Factor App al generar una clave de descifrado separada del código. | ||
| </details> | ||
| <details><summary>More Examples</summary><br> | ||
| <details><summary>Más Ejemplos</summary><br> | ||
| See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations. | ||
| Mira [ejemplos](https://github.com/dotenv-org/examples) de uso de dotenv con distintos frameworks, lenguajes y configuraciones. | ||
@@ -342,83 +349,45 @@ * [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs) | ||
| ## Agentes | ||
| ## Preguntas Frecuentes | ||
| <img src="https://dotenvx.com/assets/img/as2/9.jpg" height="400" alt="dotenvx-as2" align="right"/> | ||
| <details><summary>¿Debo hacer commit de mi archivo `.env`?</summary><br/> | ||
| > El software está cambiando, y dotenv debe cambiar con él—por eso construí [agentic secret storage (AS2)](https://dotenvx.com/as2). Los agentes ejecutan código sin humanos en la terminal, por lo que los archivos `.env` en texto plano son el primitivo equivocado. | ||
| > | ||
| > AS2 está diseñado para software autónomo: cifrado por defecto, cero acceso a consola y entrega priorizando la criptografía que mantiene a los operadores fuera del circuito. | ||
| > | ||
| > Está respaldado por [Vestauth](https://github.com/vestauth/vestauth), la capa de autenticación pionera y de confianza para agentes—que otorga a cada agente una identidad criptográfica para firmar solicitudes con claves privadas y verificarlas con claves públicas. Sin secretos compartidos que se filtren. | ||
| > | ||
| > Es lo que uso ahora. - [motdotla](https://mot.la) | ||
| ### Inicio rápido | ||
| Instala vestauth e inicializa tu agente. | ||
| ```bash | ||
| npm i -g vestauth | ||
| vestauth agent init | ||
| ``` | ||
| Tu agente puede `set` secretos con un endpoint `curl` simple: | ||
| ```bash | ||
| vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}' | ||
| ``` | ||
| Y tu agente puede `get` secretos con un endpoint `curl` simple: | ||
| ```bash | ||
| vestauth agent curl https://as2.dotenvx.com/get?key=KEY | ||
| ``` | ||
| ¡Eso es todo! Este nuevo primitivo habilita el acceso a secretos para agentes sin intervención humana, flujos de OAuth ni claves API. Es el futuro para los agentes. | ||
| | ||
| ## FAQ | ||
| <details><summary>Should I commit my `.env` file?</summary><br/> | ||
| No. | ||
| Unless you encrypt it with [dotenvx](https://github.com/dotenvx/dotenvx). Then we recommend you do. | ||
| A menos que lo cifres con [dotenvx](https://github.com/dotenvx/dotenvx). En ese caso sí lo recomendamos. | ||
| </details> | ||
| <details><summary>What about variable expansion?</summary><br/> | ||
| <details><summary>¿Qué pasa con la expansión de variables?</summary><br/> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx). | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx). | ||
| </details> | ||
| <details><summary>Should I have multiple `.env` files?</summary><br/> | ||
| <details><summary>¿Debo tener múltiples archivos `.env`?</summary><br/> | ||
| We 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. | ||
| Recomendamos crear un archivo `.env` por entorno. Usa `.env` para local/desarrollo, `.env.production` para producción, etc. Esto sigue los principios de Twelve-Factor porque cada uno pertenece de forma independiente a su entorno. Evita configuraciones personalizadas con herencia (`.env.production` hereda valores de `.env`, por ejemplo). Es mejor duplicar valores cuando sea necesario en cada archivo `.env.environment`. | ||
| > 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. | ||
| > En una app twelve-factor, las variables de entorno son controles granulares, totalmente ortogonales entre sí. Nunca se agrupan como “entornos”; en cambio, se administran de forma independiente por despliegue. Este modelo escala de forma natural a medida que la app crece en más despliegues a lo largo del tiempo. | ||
| > | ||
| > – [The Twelve-Factor App](http://12factor.net/config) | ||
| Additionally, we recommend using [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt and manage these. | ||
| Además, recomendamos usar [dotenvx](https://github.com/dotenvx/dotenvx) para cifrarlos y administrarlos. | ||
| </details> | ||
| <details><summary>How do I use dotenv with `import`?</summary><br/> | ||
| <details><summary>¿Cómo uso dotenv con `import`?</summary><br/> | ||
| Simply.. | ||
| Simplemente.. | ||
| ```javascript | ||
| // index.mjs (ESM) | ||
| import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import | ||
| import 'dotenv/config' // ver https://github.com/motdotla/dotenv#como-uso-dotenv-con-import | ||
| import express from 'express' | ||
| ``` | ||
| A little background.. | ||
| Un poco de contexto.. | ||
| > 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. | ||
| > Cuando ejecutas un módulo que contiene una declaración `import`, primero se cargan los módulos importados y luego se ejecuta cada cuerpo de módulo en un recorrido en profundidad del grafo de dependencias, evitando ciclos al omitir lo que ya se ejecutó. | ||
| > | ||
| > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) | ||
| What does this mean in plain language? It means you would think the following would work but it won't. | ||
| ¿Qué significa esto en lenguaje simple? Que parece que lo siguiente debería funcionar, pero no funciona. | ||
@@ -439,12 +408,12 @@ `errorReporter.mjs`: | ||
| ```js | ||
| // Note: this is INCORRECT and will not work | ||
| // Nota: esto es INCORRECTO y no funcionará | ||
| import * as dotenv from 'dotenv' | ||
| dotenv.config() | ||
| import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank! | ||
| import errorReporter from './errorReporter.mjs' // process.env.API_KEY estará vacío | ||
| ``` | ||
| `process.env.API_KEY` will be blank. | ||
| `process.env.API_KEY` estará vacío. | ||
| Instead, `index.mjs` should be written as.. | ||
| En su lugar, `index.mjs` debería escribirse así.. | ||
@@ -457,13 +426,13 @@ ```js | ||
| Does 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). | ||
| ¿Tiene sentido? Es un poco poco intuitivo, pero así funciona la importación de módulos ES6. Aquí tienes un [ejemplo funcional de este problema](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall). | ||
| There are two alternatives to this approach: | ||
| Hay dos alternativas a este enfoque: | ||
| 1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_) | ||
| 2. 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) | ||
| 1. Precargar con dotenvx: `dotenvx run -- node index.js` (_Nota: con este enfoque no necesitas `import` dotenv_) | ||
| 2. Crear un archivo separado que ejecute `config` primero, como se indica en [este comentario de #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822) | ||
| </details> | ||
| <details><summary>Can I customize/write plugins for dotenv?</summary><br/> | ||
| <details><summary>¿Puedo personalizar/escribir plugins para dotenv?</summary><br/> | ||
| Yes! `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: | ||
| Sí. `dotenv.config()` devuelve un objeto que representa el archivo `.env` analizado. Con eso tienes lo necesario para seguir estableciendo valores en `process.env`. Por ejemplo: | ||
@@ -478,16 +447,16 @@ ```js | ||
| </details> | ||
| <details><summary>What rules does the parsing engine follow?</summary><br/> | ||
| <details><summary>¿Qué reglas sigue el motor de análisis?</summary><br/> | ||
| The parsing engine currently supports the following rules: | ||
| El motor de análisis actualmente soporta las siguientes reglas: | ||
| - `BASIC=basic` becomes `{BASIC: 'basic'}` | ||
| - empty lines are skipped | ||
| - lines beginning with `#` are treated as comments | ||
| - `#` marks the beginning of a comment (unless when the value is wrapped in quotes) | ||
| - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`) | ||
| - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`) | ||
| - 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'}`) | ||
| - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`) | ||
| - single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`) | ||
| - double quoted values expand new lines (`MULTILINE="new\nline"` becomes | ||
| - `BASIC=basic` se convierte en `{BASIC: 'basic'}` | ||
| - las líneas vacías se omiten | ||
| - las líneas que empiezan con `#` se tratan como comentarios | ||
| - `#` marca el inicio de un comentario (a menos que el valor esté entre comillas) | ||
| - los valores vacíos se convierten en cadenas vacías (`EMPTY=` pasa a `{EMPTY: ''}`) | ||
| - las comillas internas se conservan (piensa en JSON) (`JSON={"foo": "bar"}` se convierte en `{JSON:"{\"foo\": \"bar\"}"`) | ||
| - se elimina el espacio al principio y al final de valores sin comillas (más en [`trim`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String/trim)) (`FOO= some value ` pasa a `{FOO: 'some value'}`) | ||
| - los valores con comillas simples o dobles se escapan (`SINGLE_QUOTE='quoted'` pasa a `{SINGLE_QUOTE: "quoted"}`) | ||
| - los valores entre comillas simples o dobles mantienen los espacios en ambos extremos (`FOO=" some value "` pasa a `{FOO: ' some value '}`) | ||
| - los valores entre comillas dobles expanden saltos de línea (`MULTILINE="new\nline"` pasa a | ||
@@ -499,13 +468,13 @@ ``` | ||
| - backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``) | ||
| - se admiten backticks (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``) | ||
| </details> | ||
| <details><summary>What about syncing and securing .env files?</summary><br/> | ||
| <details><summary>¿Qué hay de sincronizar y proteger archivos .env?</summary><br/> | ||
| Use [dotenvx](https://github.com/dotenvx/dotenvx) to unlock syncing encrypted .env files over git. | ||
| Usa [dotenvx](https://github.com/dotenvx/dotenvx) para habilitar la sincronización de archivos .env cifrados sobre git. | ||
| </details> | ||
| <details><summary>What if I accidentally commit my `.env` file to code?</summary><br/> | ||
| <details><summary>¿Qué pasa si hago commit accidentalmente de mi archivo `.env`?</summary><br/> | ||
| Remove 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. | ||
| Elimínalo, [borra el historial de git](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) y luego instala el [hook de pre-commit de git](https://github.com/dotenvx/dotenvx#pre-commit) para evitar que vuelva a pasar. | ||
@@ -518,7 +487,7 @@ ``` | ||
| </details> | ||
| <details><summary>What happens to environment variables that were already set?</summary><br/> | ||
| <details><summary>¿Qué pasa con variables de entorno que ya estaban definidas?</summary><br/> | ||
| By 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. | ||
| Por defecto, nunca modificamos variables de entorno que ya estén definidas. En particular, si hay una variable en tu archivo `.env` que colisiona con una ya existente en tu entorno, esa variable se omite. | ||
| If instead, you want to override `process.env` use the `override` option. | ||
| Si en cambio quieres sobrescribir `process.env`, usa la opción `override`. | ||
@@ -530,5 +499,5 @@ ```javascript | ||
| </details> | ||
| <details><summary>How can I prevent committing my `.env` file to a Docker build?</summary><br/> | ||
| <details><summary>¿Cómo evito incluir mi archivo `.env` en un build de Docker?</summary><br/> | ||
| Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild). | ||
| Usa el [hook de prebuild para docker](https://dotenvx.com/docs/features/prebuild?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-prebuild). | ||
@@ -545,16 +514,16 @@ ```bash | ||
| </details> | ||
| <details><summary>How come my environment variables are not showing up for React?</summary><br/> | ||
| <details><summary>¿Por qué no aparecen mis variables de entorno en React?</summary><br/> | ||
| Your 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. | ||
| Tu código React corre en Webpack, donde el módulo `fs` o incluso el global `process` no son accesibles de forma predeterminada. `process.env` solo se puede inyectar mediante configuración de Webpack. | ||
| If 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. | ||
| Si usas [`react-scripts`](https://www.npmjs.com/package/react-scripts), distribuido vía [`create-react-app`](https://create-react-app.dev/), ya incluye dotenv, pero con una condición. Antepone `REACT_APP_` a tus variables de entorno. Mira [este stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) para más detalles. | ||
| If 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. | ||
| Si usas otros frameworks (por ejemplo, Next.js, Gatsby...), debes revisar su documentación para inyectar variables de entorno en el cliente. | ||
| </details> | ||
| <details><summary>Why is the `.env` file not loading my environment variables successfully?</summary><br/> | ||
| <details><summary>¿Por qué el archivo `.env` no carga mis variables de entorno correctamente?</summary><br/> | ||
| Most 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). | ||
| Lo más probable es que tu archivo `.env` no esté en el lugar correcto. [Mira este stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables). | ||
| Turn on debug mode and try again.. | ||
| Activa el modo debug y prueba de nuevo.. | ||
@@ -565,8 +534,8 @@ ```js | ||
| You will receive a helpful error outputted to your console. | ||
| Recibirás un error útil en la consola. | ||
| </details> | ||
| <details><summary>Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?</summary><br/> | ||
| <details><summary>¿Por qué recibo el error `Module not found: Error: Can't resolve 'crypto|os|path'`?</summary><br/> | ||
| You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following: | ||
| Estás usando dotenv en el front-end y no incluiste un polyfill. Webpack < 5 solía incluirlos. Haz lo siguiente: | ||
@@ -577,3 +546,3 @@ ```bash | ||
| Configure your `webpack.config.js` to something like the following. | ||
| Configura tu `webpack.config.js` con algo como lo siguiente. | ||
@@ -606,3 +575,3 @@ ```js | ||
| Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you. | ||
| Como alternativa, usa [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack), que hace esto y más por detrás. | ||
@@ -613,5 +582,5 @@ </details> | ||
| ## Docs | ||
| ## Documentación | ||
| Dotenv exposes four functions: | ||
| Dotenv expone tres funciones: | ||
@@ -624,5 +593,5 @@ * `config` | ||
| `config` will read your `.env` file, parse the contents, assign it to | ||
| `config` leerá tu archivo `.env`, analizará su contenido, lo asignará a | ||
| [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env), | ||
| and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. | ||
| y devolverá un objeto con una clave `parsed` con el contenido cargado o una clave `error` si falla. | ||
@@ -639,11 +608,11 @@ ```js | ||
| You can additionally, pass options to `config`. | ||
| También puedes pasar opciones a `config`. | ||
| #### Options | ||
| #### Opciones | ||
| ##### path | ||
| Default: `path.resolve(process.cwd(), '.env')` | ||
| Por defecto: `path.resolve(process.cwd(), '.env')` | ||
| Specify a custom path if your file containing environment variables is located elsewhere. | ||
| Especifica una ruta personalizada si tu archivo de variables de entorno está en otro lugar. | ||
@@ -654,5 +623,5 @@ ```js | ||
| By default, `config` will look for a file called .env in the current working directory. | ||
| Por defecto, `config` buscará un archivo llamado .env en el directorio de trabajo actual. | ||
| Pass 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. | ||
| Pasa múltiples archivos como un arreglo; se analizarán en orden y se combinarán con `process.env` (o `option.processEnv`, si se define). El primer valor asignado a una variable prevalece, salvo que `options.override` esté activo; en ese caso prevalece el último. Si un valor ya existe en `process.env` y `options.override` NO está activo, no se hará ningún cambio en ese valor. | ||
@@ -665,9 +634,9 @@ ```js | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Suppress runtime logging message. | ||
| Suprime el mensaje de logging en tiempo de ejecución. | ||
| ```js | ||
| // index.js | ||
| require('dotenv').config({ quiet: false }) // change to true to suppress | ||
| require('dotenv').config({ quiet: false }) // cambia a true para suprimir | ||
| console.log(`Hello ${process.env.HELLO}`) | ||
@@ -683,4 +652,3 @@ ``` | ||
| $ node index.js | ||
| [dotenv@17.0.0] injecting env (1) from .env | ||
| Hello World | ||
| Hola Mundo | ||
| ``` | ||
@@ -690,5 +658,5 @@ | ||
| Default: `utf8` | ||
| Por defecto: `utf8` | ||
| Specify the encoding of your file containing environment variables. | ||
| Especifica la codificación del archivo que contiene variables de entorno. | ||
@@ -701,5 +669,5 @@ ```js | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Turn on logging to help debug why certain keys or values are not being set as you expect. | ||
| Activa logs para depurar por qué ciertas claves o valores no se establecen como esperas. | ||
@@ -712,5 +680,5 @@ ```js | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Override 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. | ||
| Sobrescribe cualquier variable de entorno ya definida en tu máquina con valores de tus archivos .env. Si se proporcionan múltiples archivos en `option.path`, `override` también aplica al combinar cada archivo con el siguiente. Sin `override`, prevalece el primer valor. Con `override`, prevalece el último. | ||
@@ -723,5 +691,5 @@ ```js | ||
| Default: `process.env` | ||
| Por defecto: `process.env` | ||
| Specify an object to write your environment variables to. Defaults to `process.env` environment variables. | ||
| Especifica un objeto donde escribir tus variables de entorno. Por defecto usa `process.env`. | ||
@@ -732,4 +700,4 @@ ```js | ||
| console.log(myObject) // values from .env | ||
| console.log(process.env) // this was not changed or written to | ||
| console.log(myObject) // valores desde .env | ||
| console.log(process.env) // esto no se modificó ni escribió | ||
| ``` | ||
@@ -739,5 +707,5 @@ | ||
| The 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. | ||
| El motor que analiza el contenido de tu archivo de variables | ||
| de entorno está disponible para usar. Acepta un String o Buffer y devuelve | ||
| un objeto con las claves y valores analizados. | ||
@@ -747,20 +715,20 @@ ```js | ||
| const buf = Buffer.from('BASIC=basic') | ||
| const config = dotenv.parse(buf) // will return an object | ||
| console.log(typeof config, config) // object { BASIC : 'basic' } | ||
| const config = dotenv.parse(buf) // devolverá un objeto | ||
| console.log(typeof config, config) // objeto { BASIC : 'basic' } | ||
| ``` | ||
| #### Options | ||
| #### Opciones | ||
| ##### debug | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Turn on logging to help debug why certain keys or values are not being set as you expect. | ||
| Activa logs para depurar por qué ciertas claves o valores no se establecen como esperas. | ||
| ```js | ||
| const dotenv = require('dotenv') | ||
| const buf = Buffer.from('hello world') | ||
| const buf = Buffer.from('hola mundo') | ||
| const opt = { debug: true } | ||
| const config = dotenv.parse(buf, opt) | ||
| // expect a debug message because the buffer is not in KEY=VAL form | ||
| // espera un mensaje de depuración porque el buffer no tiene formato KEY=VAL | ||
| ``` | ||
@@ -770,5 +738,5 @@ | ||
| The 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. | ||
| El motor que carga el contenido de tu archivo .env en `process.env` está disponible para su uso. Acepta un objetivo, una fuente y opciones. Es útil para usuarios avanzados que quieren proveer sus propios objetos. | ||
| For example, customizing the source: | ||
| Por ejemplo, personalizando la fuente: | ||
@@ -784,3 +752,3 @@ ```js | ||
| For example, customizing the source AND target: | ||
| Por ejemplo, personalizando la fuente Y el objetivo: | ||
@@ -790,3 +758,3 @@ ```js | ||
| const parsed = { HELLO: 'universe' } | ||
| const target = { HELLO: 'world' } // empty object | ||
| const target = { HELLO: 'world' } // objeto inicial | ||
@@ -798,15 +766,15 @@ dotenv.populate(target, parsed, { override: true, debug: true }) | ||
| #### options | ||
| #### opciones | ||
| ##### Debug | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Turn on logging to help debug why certain keys or values are not being populated as you expect. | ||
| Activa logs para depurar por qué ciertas claves o valores no se están cargando como esperas. | ||
| ##### override | ||
| Default: `false` | ||
| Por defecto: `false` | ||
| Override any environment variables that have already been set. | ||
| Sobrescribe cualquier variable de entorno que ya haya sido definida. | ||
@@ -817,10 +785,10 @@ | ||
| See [CHANGELOG.md](CHANGELOG.md) | ||
| Ver [CHANGELOG.md](CHANGELOG.md) | ||
| | ||
| ## Who's using dotenv? | ||
| ## ¿Quién usa dotenv? | ||
| [These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv) | ||
| [Estos módulos de npm dependen de él.](https://www.npmjs.com/browse/depended/dotenv) | ||
| Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv). | ||
| Los proyectos que lo extienden suelen usar la [palabra clave "dotenv" en npm](https://www.npmjs.com/search?q=keywords:dotenv). |
+15
-47
@@ -0,1 +1,3 @@ | ||
| <a href="https://dotenvx.com/?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=banner"><img src="https://dotenvx.com/dotenv-banner.png" alt="dotenvx" /></a> | ||
| # dotenv [](https://www.npmjs.com/package/dotenv) [](https://www.npmjs.com/package/dotenv) | ||
@@ -30,2 +32,3 @@ | ||
| ```javascript | ||
| // index.js | ||
| require('dotenv').config() // or import 'dotenv/config' if you're using ES6 | ||
@@ -35,4 +38,8 @@ ... | ||
| ``` | ||
| ```sh | ||
| $ node index.js | ||
| ◇ injecting env (14) from .env | ||
| ``` | ||
| That's it. `process.env` now has the keys and values you defined in your `.env` file: | ||
| That's it. `process.env` now has the keys and values you defined in your `.env` file. | ||
@@ -139,3 +146,3 @@ | ||
| > | ||
| > 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://mot.la) | ||
| > 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://not.la) | ||
@@ -182,3 +189,3 @@ You 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. | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (2) from .env | ||
| ⟐ injecting env (2) from .env · dotenvx@1.59.1 | ||
| DATABASE_URL postgres://username@localhost/my_database | ||
@@ -204,3 +211,3 @@ ``` | ||
| $ dotenvx run --debug -- node index.js | ||
| [dotenvx@0.14.1] injecting env (1) from .env | ||
| ⟐ injecting env (1) from .env · dotenvx@1.59.1 | ||
| DATABASE_URL postgres://yourusername@localhost/my_database | ||
@@ -221,3 +228,3 @@ ``` | ||
| $ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js | ||
| [dotenvx] injecting env (2) from .env.production | ||
| ⟐ injecting env (2) from .env.production · dotenvx@1.59.1 | ||
| Hello Production | ||
@@ -255,3 +262,3 @@ ``` | ||
| [more environment examples](https://dotenvx.com/docs/quickstart/environments) | ||
| [more environment examples](https://dotenvx.com/docs/quickstart/environments?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-environments) | ||
@@ -326,40 +333,2 @@ </details> | ||
| ## Agents | ||
| <img src="https://dotenvx.com/assets/img/as2/9.jpg" height="400" alt="dotenvx-as2" align="right"/> | ||
| > Software is changing, and dotenv must change with it—that is why I built [agentic secret storage (AS2)](https://dotenvx.com/as2). Agents run code without humans at terminals, so plaintext `.env` files are the wrong primitive. | ||
| > | ||
| > AS2 is built for autonomous software: encrypted by default, zero console access, and cryptography‑first delivery that keeps operators out of the loop. | ||
| > | ||
| > It is backed by [Vestauth](https://github.com/vestauth/vestauth), the trusted, pioneering auth layer for agents—giving each agent a cryptographic identity so requests are signed with private keys and verified with public keys. No shared secrets to leak. | ||
| > | ||
| > It's what I'm using now. - [motdotla](https://mot.la) | ||
| ### Quickstart | ||
| Install vestauth and initialize your agent. | ||
| ```bash | ||
| npm i -g vestauth | ||
| vestauth agent init | ||
| ``` | ||
| Your agent `set`s secrets with a simple `curl` endpoint: | ||
| ```bash | ||
| vestauth agent curl -X POST https://as2.dotenvx.com/set -d '{"KEY":"value"}' | ||
| ``` | ||
| And your agent `get`s secrets with a simple `curl` endpoint: | ||
| ```bash | ||
| vestauth agent curl https://as2.dotenvx.com/get?key=KEY | ||
| ``` | ||
| That's it! This new primitive unlocks secrets access for agents without human-in-the-loop, oauth flows, or API keys. It's the future for agents. | ||
| | ||
| ## FAQ | ||
@@ -381,3 +350,3 @@ | ||
| We 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. | ||
| We 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 from `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file. | ||
@@ -512,3 +481,3 @@ > 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. | ||
| Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild). | ||
| Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-prebuild). | ||
@@ -654,3 +623,2 @@ ```bash | ||
| $ node index.js | ||
| [dotenv@17.0.0] injecting env (1) from .env | ||
| Hello World | ||
@@ -657,0 +625,0 @@ ``` |
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
124341
33.23%14
16.67%553
-1.25%743
-4.13%