DEV Community

Cover image for React & Firebase: Add Firebase to a React App
faraz ahmad
faraz ahmad

Posted on • Updated on

React & Firebase: Add Firebase to a React App

Note: With the release of v9 of the firebase library, this post is out of date.

I've been using React together with Firebase for several years now, and I've decided to share some things I've learned along the way. This is my first post in a series which I am titling "React & Firebase". If you are interested in more posts like this, please follow me and share this article. Thanks!

Getting started

All you need is a free Firebase account. To create a Firebase project, you'll need an email address that is powered by Google/Gmail.

Create a Firebase project

Register a web app for your Firebase project

  • Navigate to the Firebase project settings.
    Navigate to the Firebase project settings

  • Select the web platform under Your Apps section.
    Select the web platform under Your Apps section

  • Enter an app name to register your app. Note, we won't be going over Firebase Hosting in this lesson, so you don't have to enable it.

  • Once you finish the steps, you will be presented with your Firebase app's configuration. Copy the configuration values, we will need these when we are initializing Firebase in your React app.
    Copy the configuration values only
    You only need to copy the the configuration object, not the entire snippet, because we will be installing the Firebase client SDK from npm.

Add Firebase to your React app

Install the Firebase SDK via yarn.

yarn add firebase

Initialize your Firebase app

Using the config values you copied in the previous step, you can initialize your Firebase application.

Initialize Firebase in the index.js file.



import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import firebase from "firebase/app";

// Use your config values here.
firebase.initializeApp({
  apiKey: "AIzaSyDHE9fVBUM_mto-p_SkWnyKtOiRu8M5F98",
  authDomain: "react-firebase-farazamiruddin.firebaseapp.com",
  databaseURL: "https://react-firebase-farazamiruddin.firebaseio.com",
  projectId: "react-firebase-farazamiruddin",
  storageBucket: "react-firebase-farazamiruddin.appspot.com",
  messagingSenderId: "338564911587",
  appId: "1:338564911587:web:c34e6fee0ff41bbe7fd0d6"
});

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);


Enter fullscreen mode Exit fullscreen mode

Verify the application was initialized correctly

To verify, we can simple display some information about our Firebase app in the browser.

Add the following to the App.js file.



import React from "react";
import firebase from "firebase";

export default function App() {
  const firebaseApp = firebase.apps[0];
  return (
    <div>
      <h1>React & Firebase</h1>
      <h2>By @farazamiruddin</h2>
      <code>
        <pre>{JSON.stringify(firebaseApp.options, null, 2)}</pre>
      </code>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

When you initialize a Firebase app, the Firebase will append this app in the apps array. We are grabbing the first item in this array (since we only have one app) and printing out it's options to the browser. These options should match our config values we copied from the Firebase project settings page.

If you followed along, you should see this in your browser.
Displaying our Firebase app's options in the browser

Wrapping up

In this lesson, we went over how to add Firebase to a React app. If you liked this post, please follow me and share it online.

If you'd like to stay in touch, reach out to me on twitter.
@farazamiruddin

Till next time.

Top comments (13)

Collapse
 
adityamitra profile image
Aditya Mitra

I really like firebase. It would be great if they would allow us to perform cross-origin API requests in firebase functions.

Collapse
 
farazamiruddin profile image
faraz ahmad

I like it too! You can do cross-origin requests. You just need to use the cors npm package.

Here's an example I pulled from a function I wrote.

import * as functions from "firebase-functions";
import * as Cors from "cors";

const cors = Cors({ origin: true });

export const handleCrossOriginRequest = functions.https.onRequest((req, res) => {
  cors(req, res, async () => {
    // your logic here
  });
});

Hope this helps!

Collapse
 
adityamitra profile image
Aditya Mitra • Edited

Yeah, but you need to set the billing method first.
That's painful.

Thread Thread
 
farazamiruddin profile image
faraz ahmad

I see. What do you need cross-origin requests for if I may ask?

Collapse
 
alperguven profile image
Alper GΓΌven

I applied this and Firebase logged a warning to console immediately. It suggests that you should only import the part you use. So, for this example:
Rather than this >> import firebase from "firebase";
It suggests to use this >> import firebase from "firebase/app";

Collapse
 
farazamiruddin profile image
faraz ahmad

Thanks for the heads up! I updated the example.

Collapse
 
inoumen profile image
Ihor • Edited

That is not working in v. 9.0.1. So to make it work, use this:

On the first step, do

import { initializeApp } from 'firebase/app'; - instead of importing just 'firebase' as a default import

And to check is the app initialized, do

import { getApps } from 'firebase/app'; - instead of importing just 'firebase'
const firebaseApp = getApps()[0]; - instead of firebase.apps[0]

The rest remain the same.

Collapse
 
farazamiruddin profile image
faraz ahmad

Thank you! The API has changed a lot with the new release. Planning on making an update soon.

Collapse
 
betiol profile image
Nikollas Betiol

Cool article!
I wrote a post that teaches authentication with firebase on the backend
dev.to/betiol/how-to-handle-authen...

Collapse
 
farazamiruddin profile image
faraz ahmad

awesome! I was going to post something very similar next :)

Collapse
 
azaidi93 profile image
Ali Zaidi

Nice one πŸ‘ŒπŸ½

Collapse
 
dihanuberedt profile image
dihanuBeredt

I did it but there is an error:
TypeError: Cannot read property 'options' of undefined

Collapse
 
shkholikov profile image
Shakhzod Kholikov

Very nice and usable postπŸ’―