Austin Maxwell Edger
Austin Maxwell Edger

Reputation: 65

How to hide API keys when using React, firebase, and Github Action Deploy

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.

Upvotes: 1

Views: 2788

Answers (1)

Aurora087
Aurora087

Reputation: 96

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

  1. Create a .env.local file in your React source folder.

React Folder

  1. 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>"

  1. And then you can get access to all these tokens in React by process.env. So your firebase.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_...`
  1. 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). .gitignore file

Hope it helps 🙌!

Upvotes: 4

Related Questions