Easiest Way to Set & Use Environment Variables (.env) in Node.js

Robin
April 15, 2022

Environment variables in Node.js are used to safely store sensitive information for an application. That's why knowing how to set up and use them properly is a very important skill to have for every developer.

Most of the time new developers write their important information like database credentials, API keys, etc directly inside the source code. It puts their applications at risk.

In the beginning, it seems difficult to use environment variables. That's why new developers don't want to use them in their projects. But it is not as hard as your think.

In this article, I will walk you through every step so that you can set and use environment variables in Node.js applications with ease.

After reading this, you will not face any problems on this topic. But to understand this lesson properly, you should have the following:

  • Install Node.js version 12 or above.
  • Access to a package manager like npm or yarn.
  • Basic knowledge of JavaScript and Node.js to create a server.

I try to explain everything in detail so that it becomes easy for you. So, keeping it out of the way let's get started.

What are Environment Variables?

Environment variables are values that are set outside the program and they directly affect the way running processes behave in a computer. In simple terms, Environment variables are managed and stored by an operating system so that any program can use access them.

An environment variable is made up of a key-value pair format. That means, to set an environment variable you have to define a key with a value assigned to it. You can get the value by using that key.

Easiest Way to Set & Use Environment Variables (.env) in Node.js

Why Should You Use Environment Variables?

Environment variables allow setting values that are used by processes in different environments like development or production. It also provides a secure way to store sensitive data rather than putting that information directly in the source code.

For example, you can use different databases or accounts for different instances of a program by setting environment variables. During development, your program might use a test database but in the production environment, it will use the main database.

You can do this by using different environment variables. In this way, you don't need to edit your source code in development and production. You will be able to use the same source code in both situations.

It is also much more secure because sensitive data will be stored in the operating system environment, not in your code. Therefore, even if anyone gets access to your source code, they will not have those data.

Setting Up a Node.js Project

To set up a Node.js project first you have to create a packeage.json file. You can generate a package.json file using the following command.

          npm init --yes
        

Open your terminal window inside a directory where you want to create your Node.js project. In the terminal run the above command, it will generate a package.json file in that directory with the default configuration settings.

          npm install express
        

You can install the necessary packages for your application. For this project, I am installing the express package as the main dependency.

          npm install --save-dev nodemon
        

I am also installing nodemon as a dev dependency. It will restart our server automatically when we update our code.

Now create app.js file in that directory. This will be the entry point of your application. Add the following code in the app.js file to create a basic Node.js server.

          const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Node.js is working!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

        

If you want to use TypeScript in your project, you can follow our best TypeScript and Node.js setup guide.

How to Set Environment Variables in Node.js Using Command Line

You can set environment variables directly using your command line. But in this case, you have to follow different methods for different operating systems.

If you are using windows, you have to use the SET command for setting environment variables while running your Node.js application.

          // windows
SET PORT=8000 && nodemon app.js
        

The above command will set a PORT variable and run your server. Now you can access this variable inside your application.

If you need to set multiple variables then you have to use the following command.

          // windows
SET PORT=8000 && SET NODE_ENV=development && nodemon app.js
        

This will set PORT and NODE_ENV environment variables. The value for PORT and NODE_ENV will be 8000 and development respectively.

But if you are using Linux or MacOS, it is simple to set environment variables.

          // Linux or MacOS
PORT=8000 nodemon app.js
        

You can specify your variables in front of your Node.js script. This way you can set them using the command line.

How to Access Environment Variables in Node.js

You can access environment variables from the process.env just like a JavaScript object. All environment variables will be available in this process.env object as its properties.

          const PORT = process.env.PORT;
console.log(typeof PORT);
// string

        

The main difference is that this object will only contain string as its property value. That means, whatever you set as your environment variable number or boolean, inside your application, every value will be a string.

Here, we set the PORT variable with the value 8000 which is a number. But in the Node.js server, it becomes "8000". If you need to convert it into a number, you can use parseInt() method.

          const PORT = parseInt(process.env.PORT);
console.log(typeof PORT);
// number

        

How to Get an Environment Variable With a Default Value

You can get an environment variable along with a default value in case the variable is undefined. In this way, you can prevent your application from crashing if necessary.

          const PORT = parseInt(process.env.PORT) || 3000;
console.log(PORT);
// 8000 or 3000
        

Here, I am getting the process.env.PORT variable but also defining 3000 as a default value. If the environment variable is undefined then the PORT constant will contain 3000 as its value.

What is a .env File?

In Node.js, .env is a file that is used to declare multiple environment variables. Normally, this file will stay at the root of a project. It looks like a text document but only contains key-value pairs. It is possible to write a single-line comment using the hash (#) symbol.

Why should you use a .env file?

If you can pass environment variables directly using the command line then why this file is necessary. The thing is you can set your variables using the command line if you have a very small number of environment variables.

But if you need to set multiple variables for example 10, then it will be very difficult to manage them in the command line. That's why developers most of the time prefer to use a .env file to store environment variables.

How to Use a .env File in Node.js

You already know why you should use a .env file to store your environment variables. So, to use it in the Node.js project, you just have to follow 3 simple steps. These are:

  1. Create a .env file.
  2. Install dotenv package
  3. Load a .env file in the Node.js project.

Step 1: Create a .env File

First, you have to create a file with the name .env in the root of your project directory. Inside this file, you can write all of your environment variables. One in each line.

Each variable will have 2 parts separated by an equal (=) symbol. The left side is the key and the right side is the value. It will follow the similar structure that you have seen earlier. Here is an example of how a .env file will look like:

          PORT=8000
NODE_ENV=development

# API
API_KEY=K6fAWcc4a7T8I9lIMvVl28fRO02UQwnX


        

Here, you can see that I am using all capital letters for keys. It's just a convention. You don't have to use all capital letters for environment variables.

Step 2: Install dotenv Package

Node.js will not load your .env file automatically. Therefore, to load your environment variables in your project from a .env file, you have to use the dotenv package.

You can install this package in your project using the following command:

          npm install dotenv
        

This will install the package as a dependency. Now, you are ready to use it to load your .env file.

Step 3: Load a .env File in The Node.js Project

To load a .env file in the Node.js project, you have to import the config() function for the dotenv package. Then you need to call this function.

          const { config } = require('dotenv');
const express = require('express');

const app = express();

config();

app.get('/', (req, res) => {
    res.send('Node.js is working!');
});

const PORT = parseInt(process.env.PORT) || 3000;

app.listen(PORT, () => {
    console.log('Server is running on port ' + PORT);
});

        

In this example, I am importing and calling the config() function in your Node.js entry file. Now, the process.env object will have all the environment variables from that .env file. You can access them in a similar way.

If you don't want to import and use the config() function inside your JavaScript file, there is another way to load a .env file. You can load it using the command line.

          node -r dotenv/config app.js
        

You can use this command to start your Node.js server. It will load your .env file and then start the server.

But in the development, you might want to use nodemon to start your server. You can use this command to load .env file with the nodemon package.

          nodemon -r dotenv/config app.js
        

In this way, you can also access your environment variables from the process.env object inside your server.

Now, you can load a .env file using the config() function in your code or using the command line. Both will work fine. So, it's your choice which one you want to use.

How Do Environment Variables Work in Node.js?

When a Node.js application starts, It creates a new child process. This process then receives the environment variables from the parent process. Node.js parses all environment variables to create a process.env object.

You have seen how process.env object is used to access environment variables inside a Node.js application.

Now you know how Node creates this object in the first place. You can see environment variables are managed by a child process when the application starts. That's why, if you update or add new variables you have to restart your server manually.

In this way, by restarting the application, it gets access to the updated list of environment variables.

Changing Environment Variables in Node.js

You can easily change or add new environment variables in the .env files. But when you modify your .env file, you have to do a few things to get the updated values. These are:

  • You already know that when a Node.js server starts it creates a new child process that parses environment variables to create a process.env object. You have to manually stop and again start the server to pick up the updated values by the child process.
  • In the development, if you are using nodemon package, you might think that this package will restart the server. But this way the Node.js child process never gets created. Therefore, you have to do this manually, each time you modify your .env file.

Adding Scripts in The package.json File

Using scripts you can easily start or stop the server without writing commands manually every time. You have to add the scripts in the package.json file.

            "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },

        

There is a scripts block in the package.json file. In that block, you can add as many scripts as your need. Here, I am adding two scripts.

Each script has two parts. The left part is the name of the script. You can name anything you want. For example, I have used start and dev but you can choose any name.

The right side contains the actual command that will be executed when we run the script. Here, the start script will execute node app.js command and dev script will execute the nodemon app.js command.

The dev script is to start the server for development. It will use nodemon package. So, when we update our code our server automatically will restart. You can run the dev script using the following command in the command line.

          npm run dev
        

The start script will start the server in a production environment using node. You can urn the start script using the following command.

          npm run start
        

Conclusion

Environment variables in Node.js are used to manage information that is sensitive and you don't want to write it in your code. You can also store information in the environment variables if processes are dependent on it.

It gives you the flexibility to set up your application for different environments like development and production without changing the main source code.

In this article, you have learned how to set and use environment variables in Node.js applications. I hope it was helpful.

From now on you will be able to use environment variables in your next Node.js applications property.

Thank you so much for reading. Happy coding :)

Related Posts