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

12,481

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();
}
Share:
12,481
user11508332
Author by

user11508332

Updated on June 25, 2022

Comments

  • user11508332
    user11508332 almost 2 years

    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?

  • user11508332
    user11508332 about 4 years
    Is NODE_ENV something that's already supposed to be defined in AWS/development? I've used a console.log statement to see that it's undefined in development - I could just use different values for these in prod/development but then wouldn't any variable do the trick?
  • pzaenger
    pzaenger about 4 years
    Read NODE_ENV variable in Node.js and Setting NODE_ENV="production" to get an idea about NODE_ENV. Do you use any tool/library for development, like nodemon? In production, like AWS, NODE_ENV should be production.
  • user11508332
    user11508332 about 4 years
    but is NODE_ENV necessary, can't I just use any variable that has different values in prod/development?
  • pzaenger
    pzaenger about 4 years
    It is not necessary, it is more a convenient way. It is also a value of the user environment.
  • pzaenger
    pzaenger about 4 years
    In that case you can also check dotenv-defaults :)