Load Environment Variables for Node.js Apps

Introduction

Managing configuration in a Node.js application is critical for security, maintainability, and flexibility. Environment variables allow you to configure your application dynamically for different environments—like development, testing, and production—without modifying the code. This approach not only streamlines workflows but also protects sensitive information.

In this guide, you'll learn how to:

Setting Environment Variables

Via Command Line

You can set environment variables directly from the command line when starting your application. For example:

PORT=8080 node app.js
      

This command sets a variable PORT with the value 8080. You can also define multiple variables:

PORT=8080 NODE_ENV=development node app.js
      

Special Case: NODE_ENV

The NODE_ENV variable is a widely-used convention to define the application's environment (e.g., development, testing, or production). Setting it to production optimizes your application for performance, while development enables debugging features.

Via npm Scripts

You can also set environment variables in your package.json file under the scripts section:


{
  "scripts": {
    "start": "PORT=8080 NODE_ENV=development node app.js"
  }
}

      

Accessing Environment Variables in Node.js

Environment variables are stored in the global process.env object. Here's an example of accessing the PORT variable:

const port = process.env.PORT;
      

If the variable is undefined, you can provide a default value:

const port = process.env.PORT || 8080;
      

This ensures your application always has a fallback configuration.

Using a .env File

Manually passing environment variables via the command line can become cumbersome. A .env file provides a centralized, readable way to define them. The file consists of key-value pairs:


PORT=8080
SECRET=password
NODE_ENV=production

      

To include whitespace in a value, wrap it in quotes:

SPACES="this is a value with spaces"
      

Using the dotenv Package

The dotenv package reads variables from a .env file and sets them on process.env. To use it:

  1. Install the package:
    npm install dotenv
              
  2. Create a .env file in the project root and add your variables.
  3. Load the variables in your application:
    
    // app.js
    require('dotenv').config();
    const express = require('express');
    const app = express();
    
    const port = process.env.PORT || 8080;
    app.listen(port, () => console.log(\`Server running on port \${port}\`));
    
              

Using dotenv-cli for Command-Line Configuration

The dotenv-cli package extends the functionality of dotenv for the command line. Install it alongside dotenv:

npm install dotenv dotenv-cli
      

Then run your application using:

dotenv node app.js
      

This method is useful for running scripts with preloaded environment variables.

Best Practices

Think of your .env file as the control panel of your application. It holds the "settings" that allow your application to adapt to different environments securely.

What You Learned

By leveraging environment variables effectively, you can create secure, flexible, and scalable Node.js applications that adapt seamlessly to any environment.