How to Use Environment Variables in Node.js: A Practical Guide

Environment variables are key-value pairs that store configuration data outside your application code. In Node.js, they help you manage sensitive information like API keys, database credentials, and server ports without hardcoding them. This guide shows you the essential techniques.

Node.js provides built-in support for environment variables through the process.env object. This global object contains all the environment variables available to the process at runtime, making it straightforward to access configuration values anywhere in your application.

Article illustration

Accessing Environment Variables

The simplest way to read an environment variable is:

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

The || operator provides a default value when the variable is undefined, which is a common pattern for local development.

Setting Environment Variables

There are several ways to set them:

  • Terminal (Linux/macOS): export PORT=5000 && node app.js
  • Terminal (Windows): set PORT=5000 && node app.js
  • Dotenv package: Create a .env file and load it with require('dotenv').config().

Using the dotenv Package

The dotenv package is the industry standard for managing environment variables in Node.js. Install it with npm install dotenv. Create a .env file in your project root:

DB_HOST=localhost
DB_USER=admin
DB_PASS=secret123

Then load it at the top of your entry file:

require('dotenv').config();

Best Practices

  • Never commit your .env file to version control—add it to .gitignore.
  • Use .env.example to document required variables with placeholder values.
  • Validate environment variables at startup to fail fast if critical config is missing.

Mastering environment variables keeps your Node.js apps secure, portable, and easy to configure across different environments—from local development to production deployment.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *