0

When deploying a ReactJS + NodeJS application, what do you do about environment variables used on the React-side? Running NPM BUILD folds any secret API keys into the final code, making it visible to anyone who inspects the source code. Moving the .evn information to a .env file located server-side before using the npm build command doesn't solve the issue. I've tried to search around but I can't find any actual solutions.

Thanks!

  • You simply cannot protect client-side credentials – Phil Jul 25 '22 at 23:10
  • Does this answer your question? [How do I hide API key in create-react-app?](https://stackoverflow.com/questions/48699820/how-do-i-hide-api-key-in-create-react-app) – Phil Jul 25 '22 at 23:11

2 Answers2

0

You cannot make secret keys invisible on the client side. Even receiving it as an environment variable from the server, the keys will be incorporated into the build and will be publicly accessible.

So that your React app is not vulnerable, (correcting: not the only way) a possibility is to save keys and secrets in the backend. That is, the backend is the only one with access to keys and secrets. Client makes requests without storing sensitive data.

  • _"the only way"_... the [Authorization Code Flow with Proof Key for Code Exchange (PKCE)](https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-proof-key-for-code-exchange-pkce) was designed specifically to handle these cases – Phil Jul 25 '22 at 23:28
  • Thanks for the correction, Phil. Never should have put "the only way", I was excited – Ricardo de Carvalho Jul 26 '22 at 00:17
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 27 '22 at 07:01
0

Thanks folks, all extremely helpful! I'll be moving the secret keys to the server side and changing the way my code works to compensate the adjustment. The other issue was Google Maps API, which can't be moved in the code but can be restricted to specific IP or URL use in the Google Cloud Platform.

https://cloud.google.com/blog/products/maps-platform/google-maps-platform-best-practices-restricting-api-keys