accessing heroku config var in my React app

First install dotenv using yarn/npm

yarn add dotenv

or

npm install dotenv

Then create a .env file in parent directory of src folder and then add your key in .env file prefixed REACT_APP_ like

REACT_APP_YOUR_API=15dw8...

Now in your app.js configure dotenv

require('dotenv').config()

Now you can access your environmental variables with prefix process.env.REACT_APP_ like

 process.env.REACT_APP_YOUR_API

you may need to restart the development server


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.


You have to use a module that loads environment variables. Then,

require('dotenv').config()
...
console.log(process.env.BASE_URL);

Check this post, pretty useful.