Steps to Setup Application
Step 1: Create a application using the following command:
npm init -y
cd foldername
Step 2: Use npm to install dotenv and express package.
npm i dotenv express
Step 3: Create a ‘.env’ file in the root directory and set your sensitive or Important variables.
_PORT = 8000
API_KEY = 'XXXXXX'
ACCESS_TOKEN = 'XXXXXXX'
Project Structure:
The Updated Dependences in your package.json file is:
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2"
}
Example: Below is an example of dotenv npm.
// app.js
const express = require('express')
const app = express();
const dotenv = require('dotenv')
// dot env config
dotenv.config()
const PORT = process.env._PORT;
const API_KEY = process.env.API_KEY
const ACCESS_TOKEN = process.env.ACCESS_TOKEN
// use these variable according to your nedd
// Server
app.listen(PORT, () => {
console.log(`Server is Running on PORT No. ${PORT}.`)
})
// .env
_PORT = 8000
API_KEY = 'XXXXXX'
ACCESS_TOKEN = 'XXXXXXX'
Start your application using the following command:
node app.js
Output
NPM dotenv
Dotenv is a popular npm (Node Package Manager) package used in NodeJS applications to manage environment variables. Environment variables are values that are set outside of an application’s code and are accessible to the application during runtime. These variables often contain sensitive information like API keys, database connection strings, or configuration settings.
Contact Us