Reputation: 129
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.
create-react-app
to scaffold my project .env
file in the root of my projectREACT_APP_GOOGLE_MAPS_API_KEY = api key
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)"https://maps.googleapis.com/maps/api/js?key=GM_API_KEY&callback=initMap"
Map.js
file I added a console.log(GM_API_KEY);
to ensure it was working.App.js
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.
Upvotes: 6
Views: 5412
Reputation: 181
Try to define the constant that holds the api key in a lifecycle hook like componentWillMount (though this method is now unsafe) to ensure that the variable is available when the component mounts:
componentWillMount() {
const GM_API_KEY = ${process.env.REACT_APP_GOOGLE_MAPS_API_KEY};
}
Then
https://maps.googleapis.com/maps/api/js?key=${GM_API_KEY}&callback=initMap
Upvotes: 3
Reputation: 1582
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
Upvotes: 5