Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require('dotenv').config() in node.js

In my node.js application, I have a require('dotenv').config(); line that I need when developing locally in order to use environment variables. When I deploy to AWS however, I need to comment out this line, otherwise the application crashes. Currently I have 4 of these lines and it's a bit annoying to have to keep commenting/uncommenting them when I push/pull the application - is there any workaround for this that removes the need to have to keep removing the line when I deploy to AWS/including the line when I pull and work locally?

like image 846
user11508332 Avatar asked Mar 01 '20 23:03

user11508332


People also ask

What is require dotenv config ()?

DotEnv is a lightweight npm package that automatically loads environment variables from a . env file into the process. env object. To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv').

What is .env file in node JS?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.


Video Answer


1 Answers

Maybe you can check the value of NODE_ENV (I assume you deploy in production).

Something like:

if (process.env.NODE_ENV === 'development') {
  require('dotenv').config();
}

Or just if NODE_ENV is not production (useful if you have things like NODE_ENV === 'test'):

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
like image 62
pzaenger Avatar answered Oct 07 '22 02:10

pzaenger