Reading Environment Variables From Node.js
Environment Variable: The two fundamental concepts of any programming language are variables and constants. As we know that constants and variables both represent the unique memory locations that contain data the program uses in its calculations.
The variable which exists outside your code is a part of your server environment and can help you by both streamlining and making more secure the process of running your script and applications.
During the application initialization, these are loaded into the process.env and accessed by suffixing the name of the variable.
Environment variables in backend applications relies on the commands of the operating system to define the environment variables along with their value. A system administrator may define it through a shell-script instead of a CLI interface. Environment variables typically aren’t globally accessible across the operating system, they are usually session-specific.
Reading Environment Variable: Node.js provides the env property under the core module i.e process which hosts all the environment variables that were set at the moment when the process was started.
The following example covers how to accesses the NODE_ENV environment variable, which is set to development by default.
Note: The process module does not require a require() method because it is automatically available on it.
process.env.NODE_ENV // "development"
Now setting this into Production before the script runs it will tell Node.js which is the production environment. Here we can access any type of custom variable which was set by us or already set in the environment.
How to set our own Environment variable in Node.js?
We can set our own environment variable in Node.js using the following simple steps:
Step 1: Build our own .env file which will include all the environment variables in one place. Just be sure not to put them in source control, otherwise, your history will contain references to your files.
NODE_ENV=development PORT=8626 // You can add port no. as your preferences # Set your database/API connection information here API_KEY=************************** API_URL=**************************
- Step 2: Now create our own .gitignore file and add .env to it as shown in the following image and .gitignore will tell source control to ignore the files (or file patterns) which we will list.
Note: Be careful while adding .env to your .gitignore file and that changes before you add your .env file otherwise you run into the risk of committing an early version of your .env source control.