Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Firebase with React in Firebase Hosting

I'm developing a React app created with "create react app" (https://github.com/facebookincubator/create-react-app). It will be hosted in Firebase Hosting and I'll like to use implicit initialization as describe in documentation (https://firebase.google.com/docs/web/setup#sdk_imports_and_implicit_initialization), to deploy to multiple projects (I have a dev project and several production projects)

<script src="/__/firebase/init.js"></script>

I need to get the "firebase" object initialized in the script above in my React components. How should I import it in multiple React components files? I'm aware that this will be only available when I serve it with "firebase serve" during development and when I deploy it, so during development I'm trying to add

<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase.js"></script>
<script>
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
  };
  firebase.initializeApp(config);
</script>

code to my index.html file as describe in Firebase docs. However, when I try to import Firebase in ReactComponent it doesn't find it or complains about not initialize project (what I'm doing in the html tag)

How do I import Firebase initialized App and Firebase libraries from my html script tags??

like image 438
pablo Avatar asked Sep 15 '17 14:09

pablo


People also ask

Can I use React with Firebase?

To integrate Firebase into our React app, we need to first get the web configuration object and then use it to initialize Firebase in our react app. Copy the config to the clipboard; we'll need it later on to initialize Firebase. Then, click Continue to console to complete the process.

Can Firebase be used for hosting?

Firebase Hosting provides fast and secure hosting for your web app, static and dynamic content, and microservices.

Does Firebase hosting support node js?

Firebase Hosting supports a REST API for advanced developers to build custom workflows, like deploying through a JavaScript app. We also have a Node. js module which you can import into your Node. js apps to build advanced functionality.


1 Answers

As you are using create-react app and thus webpack, you should already be using nodejs firebase:

npm install --save firebase

To get the config on the fly when deployed, you have to access this url:

/__/firebase/init.json

So you need to make an async call to get the json object stored on this location, before you try to initiliaze firebase. So here is some sample code (using axios for the async call) to include in your index.js:

    import React from "react";
    import ReactDOM from "react-dom";
    import * as firebase from "firebase/app";
    import axios from "axios";

    const getFirebaseConfig = new Promise((resolve, reject) => {
      axios
        .get(`/__/firebase/init.json`)
        .then(res => {
          resolve(res.data);
        })
        .catch(err => reject(err));
    });

    getFirebaseConfig
      .then(result => {
        firebase.initializeApp(result);

        ReactDOM.render(
          <div>XXXXX</div>,
          document.getElementById("root")
        );
      })
      .catch(err => console.log(err));

Also in order to make this more streamlined (use dev firebase config with npm start, and get prod firebase configurations on the fly if deployed) you can do something like the below:

fbconfig.js:

if (process.env.NODE_ENV === "production") {
  module.exports = require("./prod");
} else {
  module.exports = require("./dev");
}

dev.js:

const firebaseConfig = {
  // your dev firebase configuration
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxxx",
  projectId: "xxxxxx",
  storageBucket: "xxxxx",
  messagingSenderId: "xxxxx"
};

const getFirebaseConfig = new Promise((resolve, reject) => {
  resolve(firebaseConfig);
});

export default getFirebaseConfig;

prod.js:

import axios from "axios";

const getFirebaseConfig = new Promise((resolve, reject) => {
  axios
    .get(`/__/firebase/init.json`)
    .then(res => {
      resolve(res.data);
    })
    .catch(err => reject(err));
});

export default getFirebaseConfig;

And finally in index.js:

import getFirebaseConfig from "./fbconfig";

getFirebaseConfig.then(result => {
  firebase.initializeApp(result);
  ...etc
)}
.catch(err => console.log(err));
like image 149
Fotis Nalbadis Avatar answered Sep 18 '22 06:09

Fotis Nalbadis