Get the final source code from here
Environment variables are injected from outside the application. These variables are varied in a different stage of the application. For example, a web app has separate database addresses for
So when you are developing an app, definitely you do not want to mess up with production database. In this criteria, managing environment variable comes handy.
To manage the environment variable, here we are going to use the following tools
Visual Studio Code (code editor)
dotenv (npm package)
DotENV (editor extension)
Light, Camera, Action
Install the editor for your suitable platform
Install Node.js in your machine
Make sure both
npmis installed in your system
Open Visual Studio Code and install the dotEnv extension.
To install dotENV extension in Visual Studio Code
Open the code editor
Open vs code extension panel (Crtl+Shift+X)
Search for dotENV
Install the extension
Create a directory,
manageEnvironment and enter the directory.
mkdir manageEnvironment cd manageEnvironment
Now in the root directory, create the project
npm init -y
Now open the directory in your code editor.
Create two files named
Your project directory should look like
├── ... ├── manageEnvironment │ ├── index.js │ ├── .env │ └── package.json ├── ...
Install the npm package dotenv from the root directory.
npm i dotenv
.env file with an environment variable and your
.env file should look like
And now invoke the
dotEnv and read the environment variable. Your
index.js file should be look like
const dotenv = require(“dotenv”); dotenv.config(); console.log(process.env.foo);
Now run your node app by
In your console, output should be looked like,
Always put the
.env file in
So create the
.gitIgnore file and add the
.gitIgnore file should be looked like,
So when your code is in
production phase, use the appropriate environment variable.
Stay tuned and if there is a confusing term or something, the response below. I will replay ASAP.