Novice Guide to Securing API and Firebase Key in Create-React-App and Deploying it on Heroku

Recently I was trying to build a small Pixabay-Image-Finder app using create-react-app just to practice ReactJs soon I decided to integrate firebase to it to add more functionality and learn firebase alongside ReactJs.

My main concern was to protect the API key by preventing it from pushing on to the Github. I wasted lots of time looking for an answer on StackOverflow. Actually, you can find the answer from StackOverflow but since I am a bit new with create-react-app counter comment has just confused me. But anyway I solved it and strangely the solution is very simple.

Solution:-

  1. Just create a .env file into the root of the folder and add all your API key as below example. Make sure you don’t skip REACT_APP at the start of each key. This help CRA to automatically pick it up and add it to the Webpack DefinePlugin:-
REACT_APP_PIXABAY_API_KEY=10318573-0d69a875d
REACT_APP_FIREBASE_API_KEY=AIzaSyCtCoIacYToIDZLE
REACT_APP_FIREBASE_AUTH_DOMAIN=finder.firebaseapp.com
REACT_APP_FIREBASE_DATABASE_URL=https://pixafinder.firebaseio.com
REACT_APP_FIREBASE_PROJECT_ID=pixafinder
REACT_APP_FIREBASE_STORAGE_BUCKET=pixafinder.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=4532345391321

2. Make sure you add .env file in .gitignore to prevent it from pushing on to the GitHub.

3. To use the key just use it like below snippet. This is my firebase.js file.

import * as firebase from 'firebase';

const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID
};
firebase.initializeApp(config);

const database = firebase.database();

export default database;

Now we are done with the development part. To actually use these key in Production like when the project is deployed to Heroku. Simply add the Key: Value pairs of the .env file as Heroku environment variables. To add environment variable you can use Heroku CLI or add directly from there Website(go to setting/Reveal Config Variables).