1

Using an .env file I'm adding my API keys to grab remote data. However I need to create an API object with them like this:

const myAPIObject = new fancyAPI({
    url: process.env.REACT_APP_FANCYAPI_URL,
    consumerKey: process.env.REACT_APP_FANCYAPI_CONSUMERKEY,
    consumerSecret: process.env.REACT_APP_FANCYAPI_CONSUMERSECRET
})

I do this in a dedicated file in my /src folder. When I compile, and check the minified code in the browser for the key literals, they are there. How do I do this properly?

1
  • You would not be able to hide source code ( and hence the keys ) on the browser. You might want to look at the option of having a server which makes all these API calls for you and just returns the response Commented Sep 21, 2018 at 10:51

1 Answer 1

2

Basically, this is a big problem in JavaScript and anything you try to do will lead to this problem. The only way to avoid this is not to do it.

Forget trying to communicate with your own back-end using API keys from a client-side JavaScript application. Minified, obfuscated, or not your keys are exposed to anyone who knows how to use the developer tools. That’s why you should avoid this at all costs and rely on sessions.

As for any functionality in your application that requires you to communicate with a third party API you don’t control, the answer is to make a simple CSRF secured AJAX call to your own back-end and then let your server-side application make the API call on behalf of your front-end then return the response back to your client-side app

(http://billpatrianakos.me/blog/2016/02/15/securing-api-keys-in-a-javascript-single-page-app/)

As you are well aware, the client scripts are static in so far as they are built and then do not change after that. So any variables injected into them will stay there and be visible to people looking for them.

So the solution to your problem seems to be to actually implement a server application that can hide the secret keys and deal with the client based on some other mechanism that does not require the client to expose keys to the whole wide world.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.