user11508332
user11508332

Reputation: 667

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?

Upvotes: 11

Views: 51244

Answers (3)

5422m4n
5422m4n

Reputation: 950

IMO it is better to not have code that checks the NODE_ENV and loads things for certain cases.

I put that to a dedicated npm script like npm run dev where I would load the dotenv/config and set the path for the .env file if needed.

In your case the package.json could look like

  "scripts": {
    "dev": "node -r dotenv/config ./src/index.js"
  }

Bonus track: if you have the .env file in the parent folder of your package + enable remote debugger:

  "scripts": {
    "dev": "DOTENV_CONFIG_PATH=../.env node --inspect=0.0.0.0 -r dotenv/config ./src/index.js"
  }

Then you only run npm run dev and it works.

For production, I would then add a different npm script without debugger and dotenv/config loading.

Upvotes: 1

Usama
Usama

Reputation: 33

Also do take a look at a npm package named config. It gives us multiple files.json with default.json, development.json, local.json. In some cases, we just need to change some keys in development or any other env while we want something the same in all env like port, jwt secret, etc. Take a look at the link

https://www.npmjs.com/package/config

Upvotes: 0

pzaenger
pzaenger

Reputation: 11992

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();
}

Upvotes: 13

Related Questions