How To Use Environment Variables in Node.js

Channel: Linux
Abstract: you will have to set the port. Here is the code you can use. // server.js const port = process.env.PORTyou will have to create the variable in your .e

Instead of defining the variables directly, you can use Environmental variables in node.js. You can use the Environmental variable anytime when you want to change the value depending on the environment. There are various use cases here.

If you start using the environmental variable, you won’t face issues where the client says 「It doesn’t work in my system」. This guide will cover all the things you should know about defining the Environmental variables and how you can use them in node.js. It has a lot to do with the .env file a well as with server.js. So, let’s begin the steps and see the steps.

  • You may like: How to Parse Command-Line Variables in Node.js

Please read the code as you will have to enter some of the information such as key, port number, etc. We have mentioned it in the code itself and if possible, we have also added the comments.

Step 1 – Preparation

At first, you will have to set the port. Here is the code you can use.

// server.js const port = process.env.PORT; console.log(`Your port is ${port}`);123// server.jsconst port = process.env.PORT;console.log(`Your port is ${port}`);

This code will go in the server.js file. You will have to create a file with the same name.
Thereafter, you also need to create the .env file. As of now, you don’t need to add anything to the env file.
You can do it by the command line. Just enter the name of the variable and then you can use the 「=」 sign for the value.

Here is an example of the same.

PORT=8626 node server.js 

In the same way, if you want to pass two variables, you can see the below given example.

PORT=8626 NODE_ENV=development node server.js 

Now, this was how you can do the procedure using the command line. People don’t use the command line because there could be typing mistakes and it’s too complicated.

We will now focus on the .env file and do things from there.

You can add the following code in the env file.

# Set your database/API connection information here
Step 2 – Focus on .gitingore

Don’t forget about the .gitignore. You need to ensure that you have added the env file before you commit the changes.

One can simply press CMD + Shift + F and it will open the command prompt. You can enter 「ignore」 and then select the file you want to add.

Step 3 – Create package.json

You will first have to create a package.json. Run the code and it will then create a file for you with all the basic details.

npminit -y 

This file is needed to read the env file.

Step 4 – Install and edit env file

You can use the below code to install the env file.

npm install dotenv 

The above-mentioned line will fill the entry in the package.json that we created in the above step.

You can then replace the content of server.js with the following code.

// server.js console.log(`Your port is ${process.env.PORT}`); // undefined constdotenv = require('dotenv'); dotenv.config(); console.log(`Your port is ${process.env.PORT}`); // 862612345// server.jsconsole.log(`Your port is ${process.env.PORT}`); // undefinedconstdotenv = require('dotenv');dotenv.config();console.log(`Your port is ${process.env.PORT}`); // 8626

Step 5 – Find the Variables

You can run the code and find the variables with ease. We will again use the command line here. We will get the list from server.js.

node server.js 

You can define the variable now. To do that, you will have to create the variable in your .env file.


It’s time to organize things manually. You can create a config.js file and add the code there.

// config.js constdotenv = require('dotenv'); dotenv.config(); module.exports = { endpoint: process.env.API_URL, masterKey: process.env.API_KEY, port: process.env.PORT };12345678// config.jsconstdotenv = require('dotenv');dotenv.config();module.exports = {endpoint: process.env.API_URL,masterKey: process.env.API_KEY,port: process.env.PORT};

Once you do this, it’s time to modify the server.js file.

// server.js const { port } = require('./config'); console.log(`Your port is ${port}`); // 8626123// server.jsconst { port } = require('./config');console.log(`Your port is ${port}`); // 8626

Define the constant in Config.js by adding the belw code.

const{ endpoint, masterKey, port } = require(‘./config’);1const{ endpoint, masterKey, port } = require(./config);

Step 6 – Reduce the Dependencies

It’s time to reduce the dependencies of the code. Nobody likes runtime dependencies. It’s not good in the long term. Luckily, there is a code through which you can remove the runtime dependencies in dotenv package.

You can load all the variables at first. This will decrease the time of execution. The next thing you can do here is to save the dependencies as dev dependencies. You can run the following line. This is where we will install dotenv and save it as dev. Here is the code for the same.

npm install dotenv --save-dev 

Thereafter, you can remove the code that has dependencies. This will also include the code from dotenv.config().

But wait, there exists a small problem. We were previously dependent on the .env file to load the variables. Now, we will preload all of them. The 「- require (-r)」 command will do the work.

You can also remove all the references.

node -r dotenv/config server.js 

The above-given code will be much useful in this.

As the code is preloaded, half of the work is done but there are still some of the things that need to be defined.

Step 7 – NPM Scripts

Put all the commands in the NPM script. This will make it easier to run and will give you a better loading time with fewer errors.

Here is the code you can have a look at.

scripts: { "start_local": "node -r dotenv/config server.js" }123scripts: {"start_local": "node -r dotenv/config server.js"}

Step 8 – NPM Extensions

It becomes hard to learn all the scripts. Therefore, you can use the extension. There is a great extension you can use here. It’s the npm extension. You can also use the npm script outline if you want.
This will make it easier to remember the lines.

Step 9 – Finalize

Now, it’s time to finalize all the things before you share them with the team. Check all the things before you send them to them.

Additionally, you can also use the .env.example to send the file.

# .env.example
# DB information

What we have done here is that we have created a template of the file. The template is very much useful when you are defining the environmental variables.

Final Words

To summarize, this is how you can start using environmental variables in your node.js. You can share it with your team and it will work smoothly. Whether you want to run in your system or your client’s system, there will be no issues. If you are using Docker like most of the pro developers do, the code will surely run there too. So, there will be no issues. You can easily run the code. What we recommend here is to add your logic and write a better code depending on your requirement.

Ref From: tecadmin

Related articles