What are Environment Variables?
Environment Variables are variables that are set by the Operating System. They are decoupled from application logic. They can be accessed from applications and programs through various APIs.
Why to use them?
Using environment variables helps the app to behave according to the environment in which the app is to be deployed. Environment variables also help to encapsulate the data.
How to use them in NodeJs application?
At first, we need to install a package named dotenv. We can use npm i dotenv
or yarn add dotenv
to install the package.
Then we need to create a file named .env
. Note that we need to add .env
file in .gitignore.
This will help us in encapsulation of our data. Now we can define our variables in .env
file.
Declare all the variables in .env
file in uppercase, i.e, use Snake Case, but all letters should be in uppercase.
For e.g. VARIABLE_NAME = 23
.
Once you declare the variables in .env
file, then let's see how to access them in our app.
In our app, import the dotenv
package where we want to access the environment variables as require('dotenv').config()
. There is no need to save it in a variable like we save other packages such as, we import express as const express = require('express')
Now, to access the environment variables, just use the following syntax: process.env.VARIABLE_NAME
Example with code
1. .env
file
TEST_VARIABLE = thereIsNoNeedToEncloseStringInQuotes
PORT = 5000
2. index.js
file
require('dotenv').config();
const hostname = '127.0.0.1'
const port = process.env.PORT;
const testVariable = process.env.TEST_VARIABLE;
console.log(testVariable);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Console output
Server running at 5000
thereIsNoNeedToEncloseStringInQuotes
Top comments (0)