In this tutorial, we will implement a .env into our NodeJS app to store environment variables inside of it. Here I will introduce how you can use environment variables and for what you should use them. Let's Go.
dotenv
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
init npm in our directory
npm init -y
Install express (for the server) and dotenv
npm install express dotenv
Install nodemon to start the server in watch mode. Watch mode => Restarting the server on file change
npm install -D nodemon
Create a file called ".env" in the root directory and insert a variable using NAME=VALUE.
We want to put in out PORT variable to define the port on which our server will start on that is PORT=3001.
In a real-world application, you want to store your API key and any kind of sensitive data like passwords here.
Importing Express
const express = require('express');
Initialize the app
const app = express();
Configure dotenv
This will load the variables we created in the .env file into the process.env so we can use it using process.env.VARIABLE_NAME
require('dotenv').congif();
Getting the port from the .env file and set 3000 as a fallback.
const port = process.env.PORT || 3000;
Starting the server using the port :
app.listen(port, () => console.log(
server on :${ port }));
nodemon index.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter 'rs'
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Now, this should be console logged. If we wouldn't run require('dotenv').config();
in the index.js then the log should be 'server on:3000' because then our fallback value would be applied for the port variable.
server on:3001
Originally here => https://rahulism.tech/article/what-is-env-file/
๐ SIMPLE