0

I deployed a React app on Heroku which had an API key in an .env file. Now that the app is deployed I don't know how to reinstate that variable.

REACT_APP_API_KEY = blahblahblah

In Heroku I thought would just add the same variable in 'Config Vars' but it's not working. In my app the .env file is located in the same directory as the src/ directory. The file that uses that API key is located in the src/ directory.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Jeff S
  • 109
  • 2
  • 13

1 Answers1

0

In Heroku I thought would just add the same variable in 'Config Vars' but it's not working

For back-end code, this is the right approach.

But front-end code isn't running in that environment and therefore has no access to those environment variables. It runs in your users' browsers.

Compile that value into your application at build time. Depending on your toolchain this might already be happening, but if you set the config var after build it won't have been included. Rebuild your application and see if that works.

If it doesn't, please edit your question and add information about how you are building your application.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • Thank you Chris. Pardon my ignorance but I'm relatively new to this. It sounds as though you telling me that I should have included the .env file with my private key when I pushed to Heroku? I thought that is what I shouldn't do? Here is the code. This was a tutorial I followed. https://github.com/jeffsarlo/weather-app-react – Jeff S Feb 18 '20 at 19:09
  • @JeffS, no, you were right not to commit your `.env` file. That's for local development only, and should be ignored by your version control system. Populate the environment variables you require using [`heroku config`](https://devcenter.heroku.com/articles/config-vars), then rebuild. I'll update my answer to clarify. – ChrisGPT was on strike Feb 18 '20 at 20:04
  • @JeffS, actually, looking back at your question (specifically the part I quote in my answer) it looks like you are already setting Heroku Config Vars. Were those in place _before_ you built your application, or after? – ChrisGPT was on strike Feb 18 '20 at 20:06
  • They were set after. I built the app, pushed it to Heroku, then set the Config Vars. Curious, how would I have set these before before pushing the app? – Jeff S Feb 20 '20 at 03:09
  • 1
    It depends what you mean by "push". I'm pretty sure you can add config vars to an app after you create it, before the first deployment. Anyway, now that they're set, and if your build process compiles environment variables into the build artifact, the next time you deploy they should get captured when Heroku builds your application. – ChrisGPT was on strike Feb 20 '20 at 13:37