Environment variables are one of the most important concepts of Nodejs that allow the application to behave differently for each environment such as development, stage, and production.
It is commonly used for:
- protecting secrets (DB config, API keys, etc)
- assigning dynamic system resources like port_name, host_name, etc.
How to read environment variables from node.js
The process core module of Node.js provides the env property which hosts all the environment variables that were set when the process was started. The process does not require a “require”, it’s automatically available.
In this article, we will learn how to set up multiple environments for our nodejs app. Before we start make sure we have nodejs installed on our machine. Use the below command to check:
Setting multiple environments for Nodejs Application
Let’s start setting the nodejs application for Multiple environments.
Let’s start with creating a new app. To create an app use npm init command. This will create a package.json file in the directory.
Install the libraries we require for our application. Install express and dotenv using the below command
npm i express –save
npm i dotenv –save
Let’s create three .env files for three different environments (development.env, staging.env, and production.env)
Now create config.js which will help us to call the specific .env file. config() method will allow us to read the specific env file and respective variable we have set.
Now create an index.js file, the main file of our app, which will run our application based on the selected config with command.
Now we will set up the npm run command to run the app for different environments. In package.json we will add three script command
Now let’s test our application, To run the application in the development environment use the below command:
npm run dev
In the above output, we can see that our application is running at port 3000, which we have set for development mode. Similarly, to run the application in a staging environment:
npm run qa
Now we can see our application is running at port 3001, which we have set for staging mode. Similarly, to run the application in a production environment:
npm run prod
we can see our application is running at port 3002. This way we can set our node application for multiple environments.
In this blog we learned, what is node environment variables, the purpose of the environment variables, how to read environment variables, and setting nodejs app for multiple environments.
Thank you for reading, if you really like the blog hit the like button and for more updates, please follow our LinkedIn page- FrontEnd Studio.