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.
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-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With