I have defined a config var "BASE_URL" in my Heroku app and I'm trying to access it in my React app as
process.env.BASE_URL
but it gives me undefined when I console.log it as it seems to be not existing. How can I access Heroku config vars in my React app?
If you use Create React App (or react-scripts), prepend the variable with REACT_APP_
, for instance, REACT_APP_BASE_URL
, and Create React App automatically uses its value during the build process, making it then accessible in the process.env.
Note that the value is determined at build time, based on the envs on the machine or process that does the building. If building is done by pushing to Heroku, as it is normally in Heroku React apps, then by the envs that were set in Heroku at the build time.
If you're not using Create React App, and using Webpack, you'll need to use Webpack EnvironmentPlugin to define the envs you need.
Note: You must not reveal any secrets, e.g. API keys or passwords, in this way. The actual contents of all these variables are appended to the production build files themselves and can be freely accessed by just reading the public-facing code files.
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