1

I'm trying to understand how I can hide API keys and still run my Heroku projects in the browser. I understand how I can add an environment variable within a .env file and then add the .env file to the .gitignore file which successfully hides the file containing the key from GitHub. However, when I try to push the latest commit from the remote repo in order to get the latest version of the project with Heroku, the hosted project does not work because it does not see the key that it needs to use.

Once I figure out how to get the hosted Heroku project to work with the latest GitHub commit that hides the key, I would like to figure out how to configure the key to only work with the domain of my project and not work with any other domain address since I know that it's still possible to find the key within the source code if it's not hidden using a backend server. I haven't gotten around to learning about backend so I would want to learn how to make the key only work with my domain. Thank you for any responses.

albert_anthony6
  • 594
  • 2
  • 9
  • 30

1 Answers1

4

What you can do is set the API key as a config var in the settings section of your heroku dashboard by going to your heroku app, clicking on Settings and then scrolling down the config vars.

Alternatively, you can do this through the heroku cli with heroku config:set. Check out the heroku docs here on both of these options

Update: To access the config var, you use the same syntax as other environmental variables.

For example, if you set a configuration variable called API_KEY with the value being ABCDEFG, the way you'd access it in your code (with react):

var myKey = process.env.API_KEY;
Zedkay22
  • 434
  • 5
  • 13
  • Thanks for your input. I will try this when I get the chance. – albert_anthony6 Apr 18 '20 at 23:54
  • 1
    No problem. Updated the answer to show how to access the env var in react as well ^ – Zedkay22 Apr 18 '20 at 23:59
  • Hey so I just got around to trying it. I've added the env var in the heroku dashboard and the key wasn't working when I used process.env.API_KEY and committed the new code. Later on I also tried making a .env file and typing `API_KEY="the_key"` and then using process.env.API_KEY to call that variable in localhost but still it returns undefined. – albert_anthony6 Apr 19 '20 at 01:32