简体   繁体   中英

heroku environment variables return undefined

I tried to set some env. variables on Heroku and I did, I can see the variables in the app when opening the Heroku dashboard. But When I try to access the variables from my app it return undefined any idea?

componentDidMount() {
    console.log('this env' , process.env.backEndServer) // undefined
}

checking in the Heroku cli:

$ heroku config:get backEndServer // https://myserver.com

You're trying to access the environment variable on client side and this is not possible.

If you want to use environment variables on your client side application you need to set up Webpack to handle different environments.

In Webpack config files, you'll define your global variables for each environment using Webpack's Define plugin .

Also don't forget to add NODE_ENV config variable to your heroku app and set it to true. So you'll be sure that by accessing true. So you'll be sure that by accessing process.ENV.NODE_ENV will force runtime to use node.js` environment.

Now you can configure you're production environment as following:

/* in webpack.config-prod.js */
...,
plugins: [    
  new webpack.DefinePlugin({           
    NODE_ENV: JSON.stringify(process.env.NODE_ENV),      
    API_HOST: JSON.stringify(process.env.API_HOST)
  })
],
...

Now you can easily access you're environment variables in your client side app.

If you check the Heroku build log, it recommends that you specify a nodejs version. If you specify a node version in your package.json, it might fix the problem.

package.json

{
...
  "engines": {
   "node": "12.13.1"
   },
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM