Using npm dotenv Package to Manage Node.js Environment Variables

npm dotenv blog banner

What Is npm dotenv? 

dotenv is a zero-dependency module, available through the npm package manager, which loads environment variables from a .env file into process.env. As a Node.js developer, you might be familiar with the process.env global object which is made available by Node.js at runtime. This object is used to store environment-specific settings such as database passwords, API keys, or even the port on which your application should run.

The npm dotenv package lets you manage these settings efficiently, without having to hard-code them into your application. This is useful when working with sensitive data that should not be exposed, such as secret API keys or database credentials. 

However, it is important to note that while using dotenv is more secure than adding sensitive info to your source code, it is not completely secure, because environment variables are still stored in plaintext within your runtime environment. For sensitive data like passwords and credentials, it is more secure to use secrets management or configuration management tools.

How Does dotenv npm Work? 

When you start your Node.js application, npm dotenv will automatically load all the variables stored in your .env file into the process.env object. From there, you can access these variables just like any other property of the process.env object.

To get started with npm dotenv, you first need to install it as a dependency in your project. This can be easily done by running the following command in your terminal: npm install dotenv. 

Once installed, you can require and configure dotenv at the top of your main file (e.g., index.js or server.js) like so:

require('dotenv').config()

After this, you can create a .env file in the root of your project and start adding your environment variables. The syntax is straightforward: each line in the .env file represents a new variable, with the name and value separated by an equals sign. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

What Are the Benefits of Using dotenv npm? 

Flexibility in Configuration

With dotenv, configuration values are stored in a separate .env file, so you can easily change them per the environment your application is running in without changing your code.

For instance, when developing your application locally, you might want to connect to a local database. However, when deploying your application to a production server, you would need to connect to a different database. By using npm dotenv, you can easily manage these differences in configuration without having to modify your code.

Separation of Code and Configuration

The principle of separating code from configuration is a well-known best practice in software development. The idea is to keep your configuration settings separate from your codebase, as they tend to vary across different environments.

npm dotenv allows you to adhere to this principle by providing a separate .env file for your configuration. This way, you can avoid hard-coding configuration values into your code, making your application more flexible and easier to maintain.

No Need for Global Variables

By using npm dotenv, there’s no need to use global variables to store your configuration values. Global variables can lead to a variety of issues, including naming conflicts and unexpected behavior. By storing your configuration in a .env file and loading it into the process.env object, you can avoid these issues and keep your code clean and maintainable.

Security

Using npm dotenv improves security. By storing sensitive data such as API keys and database credentials in a .env file, you can ensure that this information is not exposed in your codebase. Saving this type of data in source code is a major security risk, especially when code is committed to a version control system like Git.

It is important to add the .env file to your .gitignore file to ensure that it’s not tracked by Git. This way, people viewing code in your repository won’t be able to see your sensitive data. It is equally important to select proper file permissions for .env file and the folder it resides in.

Important note: Using dotenv for sensitive data is not completely secure, because environment variables are still stored in plaintext within your runtime environment. For sensitive data like passwords and credentials, use secrets management or configuration management tools.

How to Install and Use dotenv npm 

Setting Up Your Node.js Project

Before we can install npm dotenv, we need to set up a Node.js project. If you’re new to Node.js, don’t worry, I’ll guide you through the process. First, we need to install Node.js and npm on our system. You can download them from the official Node.js website. Once installed, you can verify the installation by running the following commands in your terminal:

node -v
npm -v

After installing Node.js and npm, let’s create a new Node.js project. Navigate to the directory where you want to create your project and run the following command:

npm init -y

This command will create a new Node.js project and a package.json file, which will keep track of all the dependencies of our project.

Installing dotenv

Now that we have our Node.js project set up, we can proceed with installing npm dotenv. To install dotenv, navigate to your project directory and run the command:

npm install dotenv

This command installs the dotenv library in our project and adds it to our package.json file as a dependency. You can confirm the installation by checking the node_modules folder in your project directory.

With the dotenv library installed, we’re ready to start using it to manage our environment variables.

Creating an Environment File

The next step in using npm dotenv is creating a .env file. This file will store all our environment variables. In the root directory of your project, create a new file and name it .env.

touch .env

Inside this file, we can define our environment variables. The format is NAME=VALUE. For example, let’s say we have a variable called API_KEY. We can define it in our .env file like this:

API_KEY=123456789

You can define as many environment variables as you need in the .env file. Remember, each variable should be on a new line.

Using dotenv in Your Application

Now that we have our .env file set up, it’s time to use dotenv in our application. To do this, we need to require the dotenv library at the top of our main application file (usually app.js or index.js).

require('dotenv').config()

The config() function reads the .env file, parses the contents, and assigns it to process.env. Now, all the environment variables we defined in our .env file are available in our application through process.env.

Accessing Environment Variables

Accessing our environment variables is straightforward. Since we’ve assigned our .env file’s contents to process.env, we can access any variable like this:

console.log(process.env.API_KEY)

This command will log the value of API_KEY to the console. You can access all your environment variables in this way, which makes managing them much easier and more organized.

Managing npm Environment Variables with Configu

Configu is a configuration management platform comprised of two main components:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free