Enhance Your Node.js App Security with dotenv

Discover How Using The dotenv Package Can Help You Manage Environment Variables Efficiently and Keep Your Sensitive Data Safe.

Ishan Hansaka Silva
LinkIT
4 min readMay 18, 2024

--

photo by pzena.com

dotenv is a popular Node.js package that helps manage Environment Variables. It allows to load environment variables from a .env file into main application(e.g., app.js,index.js , server.js), making it easier to manage configuration settings separately.

In this article, lets gain a brief understanding of the dotenv package, Environment Variables and provide a complete demonstration of how to add the dotenv package to a simple Express application.

What are the Environment Variables?

Environment Variables are dynamic values that can affect the way running processes behave on a computer. They are used to configure the environment in which a program runs, allowing the same code base to run in different environments. Here are a few examples of environment variables.

  • Application settings — Define settings like port numbers, logging levels.
  • Database credentials — Store database connection details.
  • API keys and other secret Keys

Key Features of dotenv

  • Easy to use — Easier to manage environment variables and change settings without modifying the code base.
  • Security — Helps in keeping sensitive information such as API keys, database credentials, and other configuration details out of the source code and version control.

How to works with dotenv?

1. Create .env file and add Environment Variables.

PORT = 5000
DB_HOST = localhost
DB_USER = root

2. Install dotenv package.

Use npm to install the dotenv package:

npm install dotenv

3. Load the .env file in application.

At the beginning of main application file (e.g., app.js or index.js), load the environment variables to ensure that environment variables are loaded before they are accessed:

require('dotenv').config();

4. Access Environment Variables:

Access the variable using process.env:

const port = process.env.PORT;
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;

Complete Beginner’s Guide to Project Setup

In this beginner’s guide, lets walk through the step-by-step process of create basic Node.js Express application and implementing dotenv to your Express app.

Before you begin, ensure you have Node.js and npm (Node Package Manager) installed on your machine. You can download them from the official Node.js website.

After you can follow through these steps to create basic Express app.

1. Open your terminal.

2. Navigate to your project folder using the cd command. For example,

cd path/to/your/project/folder

3. Initialize a new Node.js project:

npm init -y

This will create a package.json file with default settings.

4. Install Express.js

Install Express by running the following command:

npm install express

5. Set up a basic Express server

To set up an Express server, first create your main application file (e.g., app.js or index.js) in your folder. After that, add the following code to that file:

const express = require('express');
const app = express();
const port = 5000;

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
photo by author

Now that you have created an Express app, let’s move on to implementing dotenv.

Step 1:Install dotenv package

To install the dotenv package, navigate to your project directory in terminal and run the following command to install dotenv.

npm install dotenv

This command will install the dotenv package and add it to your project's dependencies.

Step 2: Create .env file

After installing dotenv, you can create a .env file in your project's root directory to store environment variables. Here's an example of how you can use dotenv with your Express.js server:

1. Create a .env file in project folder.

2. Add your environment variables to the .env file. For example,

PORT = 5000
photo by author

Step 3: Modify your main application

1. Load the environment variables:

At the very beginning of main file (e.g., app.js or index.js), load the environment variables:

require('dotenv').config();

This code use to load environment variables from .env file

2. Modify port value:

Next, you can add your port value from the .env file to your main file. Getting the port value from the .env file via process.env.PORT rather than adding it directly makes the code more flexible and adaptable.

const port = process.env.PORT;
photo by author

Now, you can run your Express app with these new implementations : )

Security Considerations

It’s crucial not to commit .env files to version control systems like Git. These files often contain sensitive information such as API keys, database passwords, and other credentials. Including them in version control repositories exposes this sensitive data to potential threats.

Add .env to .gitignore:

  • To prevent this, you can add .env to your .gitignore file. By doing so, you instruct Git to ignore this file and not include it in your repository. This prevents accidental exposure of sensitive information to unauthorized users.
photo by author

Summary

dotenv is a simple yet powerful tool to manage environment variables in Node.js applications. It promotes best practices by separating configuration from code and enhancing security by keeping sensitive information out of the source code. By following the steps outlined above, you can effectively use dotenv to manage your application’s configuration.

References

--

--

Ishan Hansaka Silva
LinkIT
Writer for

Undergraduate at University of Moratuwa Faculty of Information Technology Technical Writer at LinkIT Publication https://www.linkedin.com/in/ishanhansakasilva/