accessing heroku config var 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.
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.
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