Friday, September 2, 2022

Node.JS env - Environment Variable Setup - Using dotnev package

  

What are .env or Environment Variables?

Nowadays, all most every application relies on third-party sources for data for doing several tasks like AuthenticationAPI CredentialsURLs, etc. which we can't share with any other person.

In that scenario, Environment Variables or dotenv(.env) variables come into the picture which helps us to secure such things. 

Environment Variables or .env variables are the variables that we set outside of a program, often through a cloud provider or operating system.

It allows us to manage the configuration of our application separately from our codebase which makes it easier for our application to be deployed in different environments.

In NodeJS, these variables are a great way to secure and configure those things that don't change often, like URLs, authentication keys, passwords, etc.

Following are the benefits of using Environment Variable(s):
  • Security: API or other secret keys should not be put in plain text into the code directly which is visible to the end user.
  • Flexibility: We can conditionally load the environment variables according to need like "if the server is in development then do XYZ else do ABC"
  • Adoption: Different services may support such environment variables too like Azure, AWS, Heroku, Jenkins, etc.

Using dotenv module

In the current scenario, we are going to use dotenv module of npm.

Following are the steps about it:
Step 1: Create a Folder Name say dotnev_demo. You can give whatever name you would like to your folder. Get inside your created folder and then run the init command.
    • mkdir dotenv_demo
    • cd doten_demo
    • npm init -y
After doing this step, your project structure will look like this
|_dotenv_demo
|__package.json

The "package.json"  file may consist of all the project settings and other npm package dependencies. If you open that file it should look like this 

{
  "name": "dotenv_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Step 2: Install npm modules, for setting up the server as well as dotenv module.

For this purpose, I'm using the following command

npm install express dotenv --save

npm install nodemon --save-dev

After installing these modules, your "package.json" file will look like this

{
  "name": "dotenv_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.1",
    "express": "^4.18.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.19"
  }
}

Step 3: Setting up the server file i.e., "index.js".

const express = require('express');
const PORT = process.env.PORT || 3000;

const app = express();

app.listen(PORT, () => {
    console.log(`Server is running at ${PORT} port`);
});

Setting up the server file After setup the server. Let's configure the "dotenv" module.

Step 4: Before configuration. Let's first set up the env file. Create the ".env" file at the root directory of your application and your desired variables into it.

// envVariableName: envVariableValueURL=https://jatinnpminstall.blogspot.com/


Add configuration to your "index.js" or app file. After configuration your file will look like this.

const express = require('express');
const PORT = process.env.PORT || 3000;

const app = express();

require('dotenv').config();

app.get('/', (req, res) => {
    res.send(process.env.URL);
});

app.listen(PORT, () => {
    console.log(`Server is running at ${PORT} port`);
});


CONGRATULATIONS.....You've successfully set up your environment variables.

Note: For security purposes, we add the ".env" file to our ".gitignore" file so that Git ignores it and it never uploads on any version controlling system.


ScreenShots



You can also visit my GitHub repository env_config_blog for that code in case you got any type of issue.


No comments:

Post a Comment