Using API keys in a react app Using API keys in a react app reactjs reactjs

Using API keys in a react app


1. How to use variables in index.html?

Answer 1 : Please go through Adding Custom Environment Variables to find out how to add environment variables of the type that you have shown as an example.

2. Doesn't the API key still end up in the bundle?

Answer 2 : Even when you have your key (MY_KEY) as an environment variable in the script tag, it will get rendered on the page and will be visible. Generally, these are browser keys and are intended to be used on the client side. These can be restricted by providing Http Referer header in your request. More on the efficacy of securing these keys here. However API keys (like MY_OTHER_KEY) are not supposed to be used on the client side and should not be rendered in the script tag or stored in the client side JS.

3. Is there a canonic way of using API keys in a react app? Or is it up to the individual developer?

Answer 3: The canonical way to use a third party API key is for your client side app to send a request to your backend API. Your backend API then formats the request as per the third-party API, adds the key and makes the call to the third-party API. Once it receives the response, it can either unpack it and translate it into domain objects which your front-end app would understand or send the raw response back to the front-end app. In this way, the API key stays at the backend and is never sent to the client-side.