Sling Academy
Home/Node.js/Using Environment Variables in Node.js (3 Approaches)

Using Environment Variables in Node.js (3 Approaches)

Last updated: December 28, 2023

Explore 3 different approaches to managing environment variables (env) in Node.js projects.

Solution 1: dotenv Package

The dotenv package is a zero-dependency module that loads environment variables from a .env file into process.env. This makes managing environment-specific settings easy and secure.

  • Install the dotenv package: Use npm to install dotenv to your Node.js project.
  • Create the .env file: Define your environment variables inside the .env file at the root of your project.
  • Require dotenv at the beginning of your main application file: This loads the variables before your application code uses them.
// Install dotenv
npm install dotenv

// .env file
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

// Main application file
require('dotenv').config();
console.log(process.env.DB_HOST);

Pros: Easy to use and integrate; Separates configuration from code; Not committed to version control (keeping secrets safe).

Cons: Requires an external package; Slightly increased load time from reading the file system.

Solution 2: Node.js process.env

Node.js provides a global process.env object that contains the environment variables that exist when the process started. Variables can be set directly in the operating system, shell, or through scripts.

  • Set environment variables: Define them inline before running your Node.js application or set them in your OS or shell profile.
  • Access variables in the application with process.env: Simply reference them using the global object.
// Set environment variables on the command line
DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3 node app.js

// Main application file
console.log(process.env.DB_HOST);

Pros: No external dependencies; Instant access to environment variables.

Cons: Less secure as variables might be visible in process lists; Harder to manage in different environments.

Solution 3: Cross-Platform Environment Configuration with cross-env

The cross-env module allows you to set environment variables in a script across different operating systems. This is useful when your Node.js application needs to run in multiple OS environments which may handle environment variables differently.

  • Install cross-env: Use npm to add the cross-env package to your project.
  • Modify package.json scripts: Prefix your run commands with cross-env and define your environment variables.
  • Run your scripts: Execute across different platforms seamlessly.
// Install cross-env
npm install --save-dev cross-env

// package.json
"scripts": {
  "start": "cross-env DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3 node app.js"
}

// Run script
npm start

// Main application file
console.log(process.env.DB_HOST);

Pros: Platform-independent; Eases environment variable management in JSON scripts.

Cons: Additional development dependency; Overhead for simple use cases.

Conclusion

Managing environment variables is a crucial part of developing a Node.js application. It enables you to separate configuration from code, cater to different environments, and secure sensitive data. The dotenv package provides a straightforward solution for local development, while direct usage of process.env caters to simpler use cases without additional dependencies. For cross-platform compatibility, cross-env is a useful tool. While each solution has its trade-offs, they collectively offer flexibility and security in managing your application’s configuration settings.

Next Article: How to Send Email in Node.js (3 Approaches)

Previous Article: How to Write C/C++ Addons for Node.js

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates