At some point in your web development career you may be required to configure your application so that it can work in different environments. You may also be using third-party resources which require API credentials, OAuth Tokens or SSH Keys to access them. However, exposing these credentials in the source code or committing them to version control is against convention for reasons you are quite aware of! This is where the use of environment variables comes handy. Sensitive or platform specific information required by the application can be stored locally in environment variables.

What is dotenv? Why use dotenv?

Dotenv is a module that we will use to access environment variables in our application. When a NodeJs application runs, it injects a global variable called process.env which contains information about the state of environment in which the application is running. Dotenv will allow us to load our environment variables stored in the .env file into process.env. Note that you can also pass environment variables through the terminal when running the NodeJs application; however, passing environment variables through the terminal can get quite ugly when you are dealing with a bunch of variables!

Overview

Today, we will implement a basic NodeJs server using Express and use environment variables to configure it. We will store our PORT and APP_SECRET in the .env file and load it into process.env using the dotenv module. We will then access these variables in our code to successfully run our application as specified by the environment.

NodeJs Project Setup

In a separate folder, run npm init to setup your NodeJs project.

NodeJS App Setup with npm init

Project Dependencies

We will use a set of dependencies with our NodeJs application. Run the following command in the terminal from the project’s root directory:

npm i express dotenv

Express will help us setup our server. We will use the dotenv module to load environment variables from the .env file into process.env.

Setup start script in package.json

Replace the existing scripts in package.json with the following script so that we can run our application:

"start": "node index.js"

package.json file

Setup Evironment Variables in the .env file

Create a .env file in the root directory of the project by running the following command in the terminal:

touch .env

We will specify the port our server listens on and our app secret by setting the PORT and APP_SECRET variables in the .env file.

PORT=3000

APP_SECRET="THIS_IS_TOP_SECRET"

Setup Initial Server Entry Point : index.js

Run the following command in the terminal from the project’s root directory to create the index.js file:

touch index.js

Load environment variables into process.env

Add the following lines at the top of the index.js file to load the environment variables from the .env file into process.env:

const dotenv = require("dotenv");

dotenv.config();

Note that it is recommended to add these lines as early as possible in the application code.

Access Environment variables

We will access our PORT and APP_SECRET loaded into process.env from our index.js file as follows:

const MY_PORT = process.env.PORT;

const MY_APP_SECRET = process.env.APP_SECRET;

Setup Express App

If you have worked with Express before, this should look pretty straight forward. You can checkout the Express documentation for detailed instructions on how to setup endpoints. We will create one basic endpoint that will return the APP_SECRET we accessed from our environment variables. Also, the server will listen on the port specified by our environment variables.

const express = require("express");

const app = express(); app.get("/", (req, res) => { return res.send(MY_APP_SECRET); });

app.listen(MY_PORT, () => console.log(`Server running on port ${MY_PORT}`))

Final index.js

Run the Application

You can run the following command in the terminal to run the web server using the start script from package.json :

npm start

npm start on terminal

localhost:3000 on browser

As expected, our server runs on the port specified by the environment and returns the configured APP_SECRET.

Add .env to .gitignore

Note that it is not recommended to commit environment variables to version control because it may contain confidential or environment specific information.

Create a .gitignore file in the application’s root directory:

touch .gitignore

Add the following text to the .gitignore file

.env

Conclusion

It is important to note that we have only scratched the surface in this tutorial and there is a lot more that Environment Variables can be used for! This is the link to the Github repository with the complete code of our application.

If you have any questions, feel free to leave a comment. Also, if this helped you, please like and share it with others. I publish articles related to web development regularly. Consider entering your email here to stay up to date with articles and tutorials related to web development. You can also find out more about what I do at abdullahsumsum.com