Categories
dotenv express node.js nodemon

how to setup dotenv in development and production?

In my Express JS API server, I tried to use dotenv with a .env file for my environment setup.

I prefer to use the .env file for both development and production environment.

I am using nodemon for my development, currently if I include -r dotenv/config in package.json > start script:

    "scripts": {
"start": "nodemon --exec babel-node -r dotenv/config index.js"
}

the variables setup correctly in process.env everwhere in the app

However, if I use script to config dotenv in index.js like this:

import dotenv from 'dotenv'
// Environment variables
dotenv.config()

seems process.env only configed in index.js page, I cannot get process.env variables in my middleware logic?

I have put dotenv.config() executed at the very beginning before middleware executed

My questions are:

1. is my logic using dotenv.config() not a correct setup? why my middleware cannot get the same variables?

2. How to setup process.env variables read from .env file for both development and production? (I may use webpack to package my production version)

Thanks for any help.