Monday, June 29, 2020

how to use environment variable in Node.js and Express Server development?

it is very convenient to use environment variable during the web development with express server and Node.js

here is the steps to configure the environment variable in the  project.

1. add a .env file to the project folder.

2. install the dotenv package
    npm i dotenv -S

3. add dotnet library to the file that will load the environment variable. in my case it is from a controller

dotenv = require('dotenv');
dotenv.config();

4. add required variables to the .env file

#test token
TOKEN=recipeT0k3n

# API
API_TOKEN=recipeAPIT0k3n

5. load the environment variable, it must be the same file in the step 3

const token=process.env.TOKEN || "recipeT0k3n",

or you can define it as global variable in the index.js or main.js with the following snippet of code

dotenv = require('dotenv');
dotenv.config();
export const token=process.env.TOKEN || "recipeT0k3n",


No comments:

Post a Comment