I have a React app that uses two third-party services. The app was started using react-create-app
.
Both of these services require a API key.
One key is supplied via a script tag, like this:
<script type="text/javascript" src="https://myapi?key=MY_KEY">
</script>
The other API key is used in a request. I store the actual key in a constant and use it to form the request. Like this:
const MY_OTHER_KEY = 'MY_OTHER_KEY'
let url = `http://myotherapi?key=${MY_OTHER_KEY}&q=${query}`
Google's best practice tips on handling API keys says:
Do not embed API keys directly in code
This brings me to my first question:
1. How to use variables in index.html
?
In my index.html
file, I have two tags that look like this:
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
Obviously, %PUBLIC_URL%
is a variable. How can I add a variable %MY_KEY%
as to avoid embedding the API key directly in my code?
To get something like this:
<script type="text/javascript" src="https://myapi?key=%MY_KEY%">
</script>
Related to this question, is it safe to have the API key stored in a constant, like I do for MY_OTHER_KEY
?
Google also says:
Do not store API keys in files inside your application's source tree
This brings me to my second question:
2. Doesn't the API key still end up in the bundle?
Say I do what Google says and I
... store them in environment variables or in files outside of your application's source tree
Say I store a key in a outside file. That file will, I assume, be read at some point and it's contents either copied in the bundle or referenced in some other way. In the end, won't the key still be visible in the bundle, except maybe harder to find? How does this help exactly?
3. Is there a canonic way of using API keys in a react app? Or is it up to the individual developer?
Self explanatory, I'm looking for the react way of solving this issue, if there is one.
Thank you for your help!