dotenv

repository·master·Indexed 12 days ago

https://github.com/motdotla/dotenv

A zero-dependency module for loading environment variables from a .env file into process.env, following the Twelve-Factor App methodology. Version 17.4.2 includes a CLI for running commands with injected variables, a fast character-scanner parser, and support for multiline values, secure decryption via @dotenvx/dotenvx, and manual parsing via dotenv.parse().

Tokens
6.4K
Snippets
31
Records
38
Agent score
95%

What's inside dotenv

  1. Handle multiline values in .env

    master

    Multiline variables (like private keys) are supported in two ways:

    1. Using actual line breaks within quotes:
    PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
    ...
    -----END RSA PRIVATE KEY-----"
    1. Using double quotes and the \n character:
    PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
  2. Use comments in .env files

    master

    Comments can be added on their own line or inline using the # character.

    Warning: If your value contains a #, you must wrap the value in quotes to prevent it from being treated as a comment.

    # This is a comment
    SECRET_KEY=YOURSECRETKEYGOESHERE # comment
    SECRET_HASH="something-with-a-#-hash"
  3. Basic usage of dotenv

    master
    1. Create a .env file in your project root:
    HELLO="Dotenv"
    OPENAI_API_KEY="your-api-key-goes-here"
    1. Import and configure dotenv as early as possible in your application entry point.
    // index.js
    require('dotenv').config()
    // or import 'dotenv/config' // for esm
    
    console.log(`Hello ${process.env.HELLO}`)
  4. Use dotenv in Webpack/Frontend environments

    master

    Because dotenv relies on Node.js modules like fs and path, it cannot run directly in a browser. When using Webpack, you must provide polyfills or use a specialized plugin.

    This plugin handles the injection of environment variables into your bundle automatically.

    Option 2: Manual Webpack Configuration

    If you are manually configuring Webpack, you must:

    1. Install node-polyfill-webpack-plugin.
    2. Use webpack.DefinePlugin to map specific process.env keys to your bundle.

    Note for React users: If using create-react-app, environment variables must be prefixed with REACT_APP_ to be accessible in the client-side code.

    npm install node-polyfill-webpack-plugin
    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)
          }
        }),
      ]
    };
  5. Enable secure decryption with dotenvx

    master

    To decrypt encrypted values in your .env file, you must use the --secure flag with the CLI or { secure: true } in config(). This requires @dotenvx/dotenvx to be installed.

    CLI:

    $ npm i @dotenvx/dotenvx
    $ dotenv run --secure -- node index.js

    Code:

    require('dotenv').config({ secure: true })

    Environment Variable:

    $ DOTENV_CONFIG_SECURE=true dotenv run -- node index.js
  6. Use dotenv with ES6 imports

    master

    To use dotenv with ES modules (import), you must ensure environment variables are loaded before other modules that depend on them.

    There are two primary ways to accomplish this:

    1. Direct Import: Import dotenv/config at the very top of your entry file.
    2. CLI Injection: Use the dotenv run command to inject variables before the Node.js process starts.

    If your imported modules read environment variables during their initialization phase, use a dedicated wrapper file to ensure dotenv.config() executes first.

    // index.mjs (ESM)
    import 'dotenv/config'
    import express from 'express'
    dotenv run -- node index.mjs
    // load-env.mjs (Wrapper file)
    import dotenv from 'dotenv'
    dotenv.config({ path: '/custom/path/to/.env', debug: true })
    
    // index.mjs (Main file)
    import './load-env.mjs'
    import express from 'express'
  7. Decrypt environment variables with --secure

    master

    If your .env file contains encrypted values (prefixed with encrypted:), you must use the --secure flag. This flag instructs dotenv to delegate the execution to dotenvx for decryption.

    Requirement: You must have dotenvx installed in your environment. You can install it via:

    npm i @dotenvx/dotenvx

    Usage:

    dotenv run --secure -- <command>
  8. Use secure mode with @dotenvx/dotenvx

    master

    If your environment files contain encrypted values (e.g., SECRET=encrypted:abc123...), standard dotenv cannot decrypt them. You must install @dotenvx/dotenvx and use the secure: true option.

    Installation:

    npm i @dotenvx/dotenvx

    Usage:

    require('dotenv').config({ secure: true });
  9. Troubleshoot dotenv loading issues

    master

    If your environment variables are not appearing, the most common cause is that the .env file is not in the expected location.

    To diagnose, enable debug mode in your configuration. This will output helpful error messages to the console regarding the loading process.

    require('dotenv').config({ debug: true })
  10. Extend dotenv with plugins

    master

    The dotenv.config() method returns an object representing the parsed .env file. You can pass this object to other libraries to extend functionality, such as variable expansion.

    Example using dotenv-expand:

    const dotenv = require('dotenv')
    const variableExpansion = require('dotenv-expand')
    const myEnv = dotenv.config()
    variableExpansion(myEnv)