Set up and test a .env file in Node
© https://nodejs.org/en/

Set up and test a .env file in Node

Set up and test a .env file.

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.

The dotenv package enables loading of a .env file in a Node.js project, which serves as a central place to manage environment variables. This single file approach makes updating and maintaining environment variables easy.

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

If you are new to environment variables, read this article first Environment variables in Node.js

Setting up and reading a .env file

The most common solution in the Node.js world is the dotenv package for managing environment variables. You can create a .env file in the root directory of the application, which contains key/value pairs defining the needed environment variables for your project. This .env file is then read by the dotenv library and appended to process.env. Please do not commit your .env file.

Let's update .gitignore, create a .env file and read it in 7 steps:

  1. Update your .gitignore file.
# Ignore .env files
.env
  1. Commit the updated .gitignore file.
git add .gitignore
git commit -m "Adding .env to .gitignore"
  1. Install dotenv package
npm i dotenv
  1. Create a new .env file in project root directory.
touch .env
  1. Add environment variables to .env file
# API connection
API_HOST=HOST-PLACEHOLDER-URL
API_KEY=TOP-SECRET
  1. Read and use the environment variables in .env

Require dotenv and call the config() method, as early as possible, usually this is done in the entrypoint like the index.js file.

require('dotenv').config();

console.log(process.env.API_HOST);
  1. Run the code
node index.js

The log message outputs HOST-PLACEHOLDER-URL, which is the environment variable set for API_HOST as defined in the .env file.

Optionally create a config.js module

For applications with many configuration options creating a separate config module is recommended. This module has to be committed into version control.

A config.js module could look like this:


const dotenv = require('dotenv');
dotenv.config();

module.exports = {
  version: '1.2.3',
  canonical_url: process.env.APPLICATION_ROOT,
  api: {
    host: process.env.API_HOST,
    key: process.env.API_KEY,
    secret: process.env.API_SECRET,
  },
  plugins: [
    'plugin-one',
    'plugin.two'
  ]
};

The above example mixes together configuration from the .env file to remain specific for the environment, while also other configuration values can be directly used (like the plugins).

This also has the benefit of being able to import configurations wherever it's needed, and use destructuring to pull out only the needed values we need. This makes the code much cleaner.

Document your application with an example for .env file

The .env file should be specific to the environment and not checked into version control, it is best practice documenting the .env file with an example. This .env.example file documents the mandatory variables for the application, and it can be committed to version control. This provides a useful reference and speeds up the on-boarding process for new team members, since the time to dig through the codebase to find out what has to be set up is reduced.

A .env.example could look like this:

# Environment variables.

# Base URL of the API server to use. No trailing slash.
API_HOST=https://example.com
# API access credentials.
API_KEY=key
API_SECRET=secret

# Enable debug mode (true) or disable it (false).
DEBUG=false

What happens to environment variables that already exist?

The dotenv library will never modify any environment variables that have already been set. If a variable has already been set in your environment, and the variable in the .env file collides with it, the variable in the .env file will be skipped.

TL;DR

  • A .env file is needed for a clean separation of environment-specific configurations.
  • The dotenv packaged is used to read a .env file at runtime containing environment variables and append them on the process.env object.
  • Creating an example for a .env file to document the mandatory variables speeds up project setup time.
  • Never commit a .env file to version control.

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 ↑