I have a basic web application written in React that requires an API key to make requests. I want to be able to deploy my application on Firebase using Github Action Deploy (this I know how to do) and also be able to hide my API key. I have read many articles on hiding API keys in firebase but can't seem to figure out how to access them in react in a safe manner while also having the code base live on GitHub.
Asked
Active
Viewed 1,943 times
1
-
1You can't. The React app runs in your users' browsers, so it can't directly use your key without exposing it to the public. – jonrsharpe Sep 09 '21 at 21:28
-
If you're asking about Firebase's configuration data (which contains a key that is unfortunately named `apiKey`) see: https://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public – Frank van Puffelen Sep 09 '21 at 21:34
-
Is there a way to use dotenv and store the env variable in firebase? – Austin Maxwell Edger Sep 09 '21 at 21:50
-
Please read this question https://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public – Andres Gardiol Sep 10 '21 at 03:30
1 Answers
4
Well according to your comment, I think you want to store the API KEYS in the .env
file and then you want to export them in your React app.
For .env.local
file
- Create a
.env.local
file in your React source folder.
- Then put all of your API keys there, making sure that all of your API keys should start with
REACT_APP_
(Like this ).
REACT_APP_apiKey="<your api key here which you copied from firebase>"
REACT_APP_authDomain="<your api key here which you copied from firebase>"
REACT_APP_projectId="<your api key here which you copied from firebase>"
REACT_APP_storageBucket="<your api key here which you copied from firebase>"
REACT_APP_messagingSenderId="<your api key here which you copied from firebase>"
REACT_APP_appId="<your api key here which you copied from firebase>"
REACT_APP_measurementId="<your api key here which you copied from firebase>"
- And then you can get access to all these tokens in React by
process.env
. So yourfirebase.jsx
file (or whatever you named) may look like this .
const firebaseApp = firebase.initializeApp({
apiKey: process.env.REACT_APP_apiKey,
authDomain: process.env.REACT_APP_authDomain,
projectId: process.env.REACT_APP_projectId,
storageBucket: process.env.REACT_APP_storageBucket,
messagingSenderId: process.env.REACT_APP_messagingSenderId,
appId: process.env.REACT_APP_appId,
measurementId: process.env.REACT_APP_measurementId,
});
// NOTE THE USE OF `process.env.REACT_APP_...`
- You can prevent
.env.local
from uploading to remote by adding it to the.gitignore
file(which will be added by default to the.gitignore
file provided by React).
Hope it helps !

Aurora087
- 86
- 5