1

Is it true that keeping confidential API keys in a .env file doesn't completely hide the key in React because you are still able to see this key in the browser?

So what's the right way to store API keys in React? Do I need to retrieve them from the server?

For example:

const [key, setKey] = useState('');

const getApiKey = async () => {
    await axios.get("https://example.com/getApiKey").then((res) => { setKey(res) });
}

useEffect(() => {
    getApiKey();
}, []);

Do I put it in the state then use it like this?

<StaticGoogleMap
    className="google-map"
    size="300x300"
    apiKey={key}
/>

I thought this way the API key would be still visible to the users in the browser.

I would really appreciate it if someone could explain the right way of securely storing API keys on the frontend. Thanks!

David
  • 321
  • 10
  • 23
  • 1
    if you truly want to keep a secret, never send it to the browser - google map keys don't need to be hidden, since you create the keys to work on a particular domain anyway, so they are useless outside that domain - other secrets are best kept on the server - any API calls to 3rd parties should be made using your server after it has verified the request to do so comes from an allowed source – Jaromanda X Oct 13 '20 at 03:44
  • 2
    Tl;DR - if it's in the browser, it's not secure (or **secret** is the better word to use) - so, there's NO way to store keys on the front end – Jaromanda X Oct 13 '20 at 03:45
  • I see, thanks for the clarification. I used Stripe before and it also has two api keys. One for the server that I can store in a .env file and another one for the client. So I don't need to worry too much about the client keys since they can't be hidden? – David Oct 13 '20 at 03:55
  • @David yes so the "publishable" Stripe key can safely be used on the front end with no worries. You just can't use the "secret" one on the client side https://stripe.com/docs/keys – Jayce444 Oct 13 '20 at 04:04
  • Awesome. So I guess this is true for all cases where you have to work with two api keys. Thanks again! – David Oct 13 '20 at 04:06

1 Answers1

1

The method that I use is to put a configuration (i.e. config.js) file outside of the "components" directory which may look like:

export default {
    api: {
        USERNAME: 'xxxxx',
        PASSWORD: 'xxxxx'
    }
};

Then in your component:

import config from './path/to/config.js';

Then access your credentials in your component:

var username = config.api.USERNAME;
var password = config.api.PASSWORD
Jamie_D
  • 979
  • 6
  • 13
  • Thanks for your input. Is this approach going to hide the API key from users and in the browser? Or it's still visible somehow? – David Oct 13 '20 at 12:17
  • The html source or js should only have the configuration key for example: `config.api.KEY`. – Jamie_D Oct 13 '20 at 15:54
  • 2
    This will still show the api key in the network tab when making a request. – Michael Jun 28 '21 at 16:21