Environment variables are keyâvalue pairs that store configuration settings outside your code. They help applications run in different environments without modifying the program.
- Store values like API keys, paths, and ports
- Keep sensitive data out of source code
- Make apps flexible across environments
Setting Environment Variable in Node.js
We can set our own environment variable in Node.js using the following simple steps:
Step 1: Create a .env file to store all environment variables in one place. Make sure not to commit this file to source control.
NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************
Step 2: Create a .gitignore file in your project root and add .env to it. This ensures that your environment variables are not tracked or pushed to the repository.
.env
Reading Environment Variable
Once the environment variables are set in the .env file, you can read and use them in your Node.js application with a few simple steps.
Step 1: Install the dotenv package in your project if it is not already installed.
npm install dotenvStep 2: Add the following line at the top of your main file. This loads the variables from the .env file into process.env.
require('dotenv').config();Step 3: Access the required environment variable using process.env. For example, to read the port number, use:
console.log(process.env.PORT);Output:
8626