DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

Set up and test a .env file in Node

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.

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
Enter fullscreen mode Exit fullscreen mode
  1. Commit the updated .gitignore file.
git add .gitignore
git commit -m "Adding .env to .gitignore"
Enter fullscreen mode Exit fullscreen mode
  1. Install dotenv package
npm i dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Create a new .env file in project root directory.
touch .env
Enter fullscreen mode Exit fullscreen mode
  1. Add environment variables to .env file
# API connection
API_HOST=HOST-PLACEHOLDER-URL
API_KEY=TOP-SECRET
Enter fullscreen mode Exit fullscreen mode
  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);
Enter fullscreen mode Exit fullscreen mode
  1. Run the code
node index.js
Enter fullscreen mode Exit fullscreen mode

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'
  ]
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 docsHeyNode,dotenv

Top comments (0)