Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding API Key in React

I'd like to start by saying I followed all of the suggestions here How do I hide API key in create-react-app? but none of them worked. I've searched for over an hour trying to find an answer but nothing. Below is my explanation.

  1. I used create-react-app to scaffold my project
  2. I'm using Google Maps and have not used any other API's yet
  3. I created a .env file in the root of my project
  4. In that file I added REACT_APP_GOOGLE_MAPS_API_KEY = api key
  5. In my component file Map.js I added const GM_API_KEY = ${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}; (the tick marks are around this variable in my file but they won't show up here)
  6. In my url for the map, I added the key like so "https://maps.googleapis.com/maps/api/js?key=GM_API_KEY&callback=initMap"
  7. Also, at the top of my Map.js file I added a console.log(GM_API_KEY); to ensure it was working.
  8. I exported my Map component and then imported it in my App.js
  9. I restarted my server

When the page loads, my key is output in the console, but I still get an error from Google saying my API key is invalid. Also, if I manually console.log(GM_API_KEY) after the page has loaded I get a reference error saying that GM_API_KEY is undefined

If anyone has any suggestions or can provide any help I would greatly appreciate it! Thank you for taking time to check out my question.

like image 754
Jonathan Sexton Avatar asked Oct 05 '18 15:10

Jonathan Sexton


1 Answers

What I do with sensitive data is not even saving them in .env I open the terminal inside the root of my project and run export API_KEY=sdf54vvetvf... and then inside your app you can access it through process.env.API_KEY note you need to add it manually each time you close the terminal from that session

like image 86
obiwankenoobi Avatar answered Sep 19 '22 21:09

obiwankenoobi