Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Eric Cheng Avatar asked Apr 22 '20 06:04

Eric Cheng


1 Answers

You might have other import statements before the dotenv.config() line, those modules will not have access to configured environments variables

Instead of

import dotenv from 'dotenv'
dotenv.config()

you can use

import 'dotenv/config'

or use the following command to start your application, similar to how you have the development environment setup. If you have your transpiled output in build directory:

node --require dotenv/config build/index.js

reference:

https://www.npmjs.com/package/dotenv#how-do-i-use-dotenv-with-import-

like image 192
thammada.ts Avatar answered Oct 17 '22 20:10

thammada.ts