Environment Variables in Node.js

Environment Variables are variables that are set by the Operating System. They are decoupled from application logic. They can be accessed from applications and programs through various APIs.

There is a Node.js library called dotenv that helps you manage and load environment variables. Let’s take a look at the purpose of environment variables, how to use them, and their role in a development environment.

1. Purpose of Environment Variables

Environment Variables are important to a software developer for multiple reasons.

  • Separation of Concerns
  • Protecting Config Keys

1.1. Separation of Concerns

Separation of Concerns refers to a software design principle that states that computer programs should be divided into distinct sections, such that each section addresses a separate concern. This means that a developer working on one section needs to have minimal knowledge about other sections. The details of other sections are placed on the sideline.

Application Configuration is a section of the code that should be decoupled from the application. Good software practices state that app config requires strict separation of config from code. Such config files can be stored as environment variables.

1.2. Protecting Config Keys

With the increasing popularity of cloud computing, more applications are using cloud services and other external APIs. Most of these come with config keys for control and access management. If the API keys are added to the application, and the code is pushed to a public repository on GitHub, this could lead to an unmonitored access problem. Unknown parties might end up using your API keys, leading to an unintended bill for your cloud services, and other potential security issues.

To solve this problem, the config keys can be added as environment variables and invoked from a closed environment from where the application is deployed.

2. Environment Variables in Node.js

In Node.js, process.env is a global variable that is injected during runtime. It is a view of the state of the system environment variables. When we set an environment variable, it is loaded into process.env during runtime and can later be accessed.

dotenv is a module available on npm to load environment variables into process.envdotenv can be added to your Node.js project by installing it from npm or yarn:

# with npm
npm install dotenv

# or with Yarn
yarn add dotenv

In a production environment, the IP address and the port on which it runs might change every single time, depending on the server. Since we cannot hardcode the server port, we can solve it by using dotenv.

Create a file called index.js and add the following code to it.

const express = require("express");
require("dotenv").config();

const app = express();
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server is running on the port ${port}.`);
});

Suppose we want to use sensitive credentials like username and password in an open-source project, we can use dotenv for that as well.

require("dotenv").config();

const mysql = require("mysql");
let con = mysql.createConnection({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
});

Now, to set the env variables, create a .env file at the root of the project directory.

DB_HOST=localhost
DB_USER=admin
DB_PASS=password

Enter the values of the following variables. This will load these variables into process.env. We can add this .env file to .gitignore so that our credentials are protected.

3. Environment Variables in Deployment

When deploying to services like MaiXuanViet.com, Vercel, Netlify or Heroku, environment variables can be set so that our deployed apps can access them.

Netlify Dashboard

Using Netlify as an example, open the Netlify Dashboard of the app you’re about to deploy.

Netlify Settings

Go to Build and Deploy -> Environment Variables

Environment Variables

Now, set the variables and save.

Your environment variables are successfully set for deployment on Netlify.

4. Further Reading

  • For detailed documentation and advanced configuration options for the dotenv module, visit the GitHub Page.
  • Learn how to use environment variables with the Nuxt Framework.
  • Read about good software development practices at The Twelve Factor App.

Related posts:

Node.js vs. PHP – Which is better for Backend development?
Consuming the Unsplash API using Node.js Graphql API
Making a Discord Bot (With Node.js)
Writing A Multiplayer Text Adventure Engine In Node.js (Part 1)
Understanding Asynchronous Control Flows in Node.js Using Async.js
Session Management in Node.js using ExpressJS and Express Session
Debugging a Node.Js app using Chrome Dev Tools
How to Implement Caching using Adonis.js 5
Most Useful Node.js Packages
How to Generate Fake Data in Node.js Using Faker.js
Build a Twitch Chatbot in Node.js
Getting Started with Node.js Rate Limiting
Deploying RESTful APIs using Node.js, Express 4 to Kubernetes clusters
Documenting a Node.js REST API using Swagger
How to use TypeScript with Node.js
Consuming the TinEye Reverse Image Search API in Node.js
How to Generate QR Code Using Node.js
Choosing Between NPM and Yarn
Developing A Chatbot Using Microsoft’s Bot Framework, LUIS And Node.js
Hapi vs Koa vs Express
Getting Started with EJS Templating Engine
Node.js vs Python for Backend Development
Getting Started with Google Translate API with Node.js
Node.js CLI Input
Node.js vs Nuxt - The Key Differences
Open-source packages & Code Security using NPM
Getting Started with billboard.js charts
Creating Secure Password Resets With JSON Web Tokens
Keeping Node.js Fast: Tools, Techniques, And Tips For Making High-Performance Node.js Servers
The Nodemailer package in a Node.js Server
Getting Started with the Quasar Framework
Uploading Files using Formidable in a Node.js Application