Skip to main content

Environment Variables

Environment variables...

  1. Listing environment variables

    console.log(process.env);
  2. The following will add the environment variable API_KEY before running the index.js file with the node command.

    API_KEY=the-value-of-the-key-goes-here node index.js
  3. Setting environment variables in a node script

    process.env.APP_NAME = 'Dabble Lab Example App';

Using .env files

You can load environment variable from a file named .env using the dotenv npm module

  1. Install the npm package

    npm install dotenv --save
  2. Add a file to the project named .env with each variable and value on its own line

    API_KEY=the-value-of-the-key-goes-here
    APP_NAME = 'Dabble Lab Example App'
  3. Add the following require command before using the environment variable

    require('dotenv').config();
  4. Check for the NODE_ENV

    if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config();
    }
  5. Use the variable

    console.log('App Name:', process.env.APP_NAME);