accessing heroku config var in my React app

Viewed 11622

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?

4 Answers

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.

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

for react es6 use

import {} from 'dotenv/config'

Related