DEV Community

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

React & Firebase: Add Firebase to a React App

faraz ahmad on June 04, 2020

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...
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๐Ÿ’ฏ