How to Use Environment Variables in Node
© https://nodejs.org/en/

How to Use Environment Variables in Node

Handle sensitive data the right way.

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

This article is based on Node v16.14.0.

Environment variables provide information about the environment (production, development, build pipeline, etc.) in which the process is running. Node environment variables are used to handle sensitive data like passwords, API credentials, or anything else, which shouldn't be written directly in code. Any variables or configuration details, which might change between environments have to be configured through environment variables.

Environment Variables in Node.js

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

With Node.js environment variables are accessible on the global process.env object.

What are Environment Variables?

Environment variables allow your application to behave differently based on the environment in which the application is running in. Using environment variables to separate different configurations is best practice. Just consider one of these use cases:

  • The production version of an application usually runs in a cloud environment (AWS, GCP, AZURE) or in a serverless function.
  • One team member is using Linux, another one MacOS and another one Win10 to develop locally.
  • The application runs in a docker container, for some users.
  • For testing purposes you have to connect to the production version (load testing).

There can be quite some use cases and multiple scenarios, so rather than hard coding values that change based on environment, it is better and best practice, to make these environment variables.

In general, environment variables are variables whose value is set outside the process itself, and allow dynamic data between the different environments (host and specific). Environment variables are already part of the Node.js ecosystem and this is a big advantage against other configuration options like a config.js or, a config.json file. Especially, when you have an automation, like a build pipeline, environment variables allow you to avoid doing awkward things like scripting configuration files.

Common use cases for .env variables

The $HOME variable provided by the OS, which points to the home directory of the user. Any application has access to this variable and, can use it for different purposes. In Node.js applications .env variables are used for credentials, which should not be hard coded or change based on the environment. Other use cases are for example:

  • Execution mode of application (production, stage, development)
  • API keys
  • Which HTTP port a server should use
  • Configs that need to be secure
  • location of the host environment's temporary files directory, etc.

Environment configuration vs. application configuration

It's important to distinguish between environment configuration and application configuration.

Environment configuration is any configuration that could vary per environment (staging, production, development) and should never exist in the code itself. Application configuration is a configuration, which doesn't vary between deploys/environments, like route configuration, which authentication middleware to use, content of emails, signup flows, or similar. This should be best kept in version control.

Reading environment variables with Node.js

Node.js loads automatically at runtime the environment variables into the global object process.env to make them available. To read an environment variable:

// hello.js
const name = process.env.NAME;
console.log(`Hello, ${name}!`);

Run hello.js and set the NAME environment variable for the process:

NAME="Mario" node hello.js

The output will be Hello, Mario!.

Setting environment variables for Node.js

In general, the host environment defines how environment variables are to set. This can vary in different cloud providers and different systems. The best way to handle this is to have a look in the documentation of the environment.

In a bash shell you can just simply export them:

export NAME='Mario'
export DEBUG=true

node ./hello.js

The output will be Hello, Mario!.

Using a .env file to set environment variables

Managing multiple environment variables for your application this way can be quite cumbersome. The most common solution in the Node.js world is to use the zero-dependency module dotenv, see dotenv github. This allows you to create a .env file in the root directory of your app, which contains key/value pairs defining the environment variables. The module dotenv reads this file and appends it to process.env, which makes it available for the application.

Never commit sensitive information to version control, use environment variables instead.

TL;DR

  • Use dotenv to manage multiple environment variables in Node.
  • Never commit sensitive information to version control.
  • Handling of environment variables varies depending on the host system, refer to the specific docs for details.

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

Node.js, Node.js docs HeyNode, dotenv

More node articles:

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑