Node process.env.VARIABLE_NAME returning undefined
I got a problem just now , and I use this solved it in webpack config
const plugins = [
new webpack.NoEmitOnErrorsPlugin(),
// after compile global will defined `process.env` this Object
new webpack.DefinePlugin({
BUILD_AT : Date.now().toString(32),
DEBUG: process.env.NODE_ENV !== 'production',
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV || "development"),
'VARIABLE_NAME': JSON.stringify(process.env.VARIABLE_NAME)
}
})
]
nodemon.json
file is only for setting nodemon specific configuration
So for create custom environment variables we can use dotenv package
First , Install dotenv package
npm install dotenv --save
after that create .env file in root and include environment variables as bellows
MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret
Finally, inside your app.js
file insert following after your imports.
require('dotenv').config()
Then you can use environment varibale like this
process.env.MONGO_ATLAS_PW
process.env.JWT_KEY
process.env.VARIABLE_NAME
returns undefined
because the Node.js execution environment does not know the newly added VARIABLE_NAME
yet. To fix the issue, the Node.js execution environment (e.g. IDE) need to restart.
The following steps can be used to reproduce this issue:
- Open IDE such as WebStorm and write a simple Node.js program:
console.log(process.env.VARIABLE_NAME)
. It will printundefined
as expected, asVARIABLE_NAME
is not defined yet. Keep the IDE running, don't close it. - Open environment profile such as
.bash_profile
and addexport VARIABLE_NAME=mySensitiveInfo
in it. - Open system console and run
source .bash_profile
, so that the aboveexport
statement will be executed. From now on, whenever system console is opened,VARIABLE_NAME
environment variable exists. - In system console, execute the Node.js program in step 1, it will print
mySensitiveInfo
. - Switch to IDE and execute Node.js program, it will print
undefined
. - Restart the IDE and execute Node.js program, this time, it will print
mySensitiveInfo