> Canonical URL: https://codingcat.dev/post/rxfire-in-reactjs-using-firebase-firestore-and-authentication

# RxFire in ReactJS using Firebase Firestore and Authentication

✏️ Blog PostMay 23, 2022[![](/logos/firebase/firebase-symbol.png)![](/logos/firebase/firebase-symbol.png)Firebase](/topic/firebase)

# RxFire in ReactJS using Firebase Firestore and Authentication

![](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/14c859eab1d212d8e8bfa6c43bcfe965cec07a11-1920x1080.png?w=1920&h=1080&q=82&fit=max&auto=format)[@CodingCatDev62.5K / 100K Subscribers Goal](https://www.youtube.com/@codingcatdev?sub_confirmation=1)[Subscribe on YouTube→](https://www.youtube.com/@codingcatdev?sub_confirmation=1)[Watch on YouTube App ↗](https://www.youtube.com/watch?v=hTzcRCAm5e0&list=UUnKZ8gEb78zXKMi1ns-IQ2g)[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)

[RxFire](https://github.com/firebase/firebase-js-sdk/tree/master/packages/rxfire) was created by [David East](https://twitter.com/_davideast), who is a Firebase Developer Advocate. Although [Firebase Blog](https://firebase.googleblog.com/2018/09/introducing-rxfire-easy-async-firebase.html) introduced RxFire in September, 2018 I thought it would be a good point of reference for beginners starting out with both [ReactJs](https://reactjs.org/) and [Firebase](https://www.firebase.com/).For those coming from an Angular background you might be familiar with [RxJS](https://github.com/ReactiveX/rxjs) and the [Angularfire2](https://github.com/angular/angularfire2) package. I know from my experience you *MUST* learn RxJS if you are going to use Angular on any size application. It can be one of the hardest parts to learn but there are several fantastic tutorials and sites dedicated to how RxJS works.Some of my favorites

New to React, Please checkout

## Example

In the example below it shows a quick preview of how the final React application will work. As you can see there are essentiall 4 steps that will occur.

- Sign In
- Add Cat Fact
- Show Added Cat Fact in List
- Sign Out

## Setup

You will need [NPM](https://nodejs.org/en/download/) which comes bundled with nodejs.Since we wil be the `create-react-app` cli you must install this first

You will also need to create your own Firebase project and initialize a Firestore database, please create this using strict mode.

## Final App Structure

![](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/d6b0c7c94d01ebb93dc32bd140c25a0d03e8f35e-820x946.png?w=820&q=82&fit=max&auto=format)

## Install dependencies

You will need both [rxfire](https://www.npmjs.com/package/rxfire) and [firebase](https://www.npmjs.com/package/firebase)

`npm i rxfire firebase`

## Create Firebase.js

Firebase.js will be our main Firebase file and will include the tools for our firebase application, including the instantiation of firebase. This file includes rxfire for both the auth and firestore helper functions.Firebase.js

Copied! 🐾

```
import 'firebase/auth';
import 'firebase/firestore';
import firebase from 'firebase/app';
import { authState } from 'rxfire/auth';
import { collectionData } from 'rxfire/firestore';
import { filter } from 'rxjs/operators';
const app = firebase.initializeApp({ /\* Place your configuration here \*/ });
const firestore = firebase.firestore(app); //Initialize firestore
const auth = firebase.auth(app); // Initialize firebase auth
const loggedIn$ = authState(auth).pipe(filter(user => !!user)); // Observable only return when user is logged in.
export { app, auth,firestore, collectionData, loggedIn$ };
export default firebase;
```

> You can skip the Instructions part of the lesson if you are already familiar with ReactJS.

## Simple Initial Component

### Remove App.js and replace

Remove the core of App.js to start as we will be using the pattern of `extends React.Component`. We will now start simple by adding our first React Component Called Instructions.

Copied! 🐾

```
import './App.css';
import React from 'react';
import Instructions from './components/Instructions';
class App extends React.Component {
	render() {
		return (

				{' '}

					{' '}
					{' '}
				{' '}

		);
	}
}
export default App;
```

### Create Instructions.js

This is a very simple React Component that takes no [props](https://reactjs.org/docs/components-and-props.html), it just returns straight `html.components/Instructions.js`

Copied! 🐾

```
import React from 'react';
class Instructions extends React.Component {
	render() {
		return (

				{' '}

					{' '}
					![rxfire for cats](https://res.cloudinary.com/ajonp/image/upload/q\_auto/ajonp-ajonp-com/17-rxfire-react-cats/RxFire\_3.webp){' '}

					{' '}

						{' '}
						In this example we will use RxFire to Observe the Cat Facts that we add to our Firestore
						Database.{' '}

 [{' '}
						https://github.com/AJONPLLC/rxfire-react-cats{' '}](https://github.com/AJONPLLC/rxfire-react-cats)
						{' '}

- {' '} Sign In {' '} Uses Google Auth for Firebase
- Found in App.js{' '}

{' '}

- {' '} Add Cat Fact {' '} This will use an API and Insert the facts into Firestore
- Found in components/AddCat.js{' '}

{' '}

- {' '} Firestore collection {' '} Observing catfacts for changes, heart eyes are your facts
- Found in components/ListCatFacts.js{' '}

{' '}

- {' '} Sign Out {' '} Observe that user is removed{' '}

{' '}
						{' '}

{' '}
				{' '}

		);
	}
}
export default Instructions;
```

## Update collection catfacts

### Create AddCat.js

The first button that we are going to add is simple enough it calls an API and pushes the data returned into a firestore collection as a new document. I always like to work from top down, so first lets import AddCat.js into our App.js.

`App.js`

Copied! 🐾

```
... import AddCat from './components/AddCat'; ...    ...
```

Now that it is in our App lets create the AddCat component. The only html that this passes back is `onClick={this.addCatFact}`. This is the JSX way of using onClick and passing a function. If you are new to ES6 arrow functions `addCatFact = () => {` is still just defining a function using a shortened syntax, it is becomming more standard these days.The `addCatFact` function calls an API that returns a single random cat fact from [https://cat-fact.herokuapp.com](https://cat-fact.herokuapp.com/). Because of CORS we have to pass it through a proxy, but you will see that we get a value back. We then use the javascript [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to create a new object by adding our `catFactDate` to the object. This allows us to later sort the facts in our list in descending

`order.components/AddCat.js`

Copied! 🐾
		);
	}
}
export default AddCat;
" aria-label="Copy code" title="Copy code to clipboard">

```
import React from 'react';
import { firestore } from '../Firebase';
class AddCat extends React.Component {
	addCatFact = () => {
		/\* The dreaded CORS, had to pass through a proxy \*/;
		fetch(
			`https://cors-anywhere.herokuapp.com/https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=1`
		)
			.then((blob) => blob.json())
			.then((value) => {
				console.log('fetched', value);
				firestore
					.collection('catfacts')
					.add({ ...value, catFactDate: new Date() })
					.then(
						() => {},
						(reason) => {
							alert('Must Be Logged In To Add, See Console');
							console.log('Failed Adding Cat Fact', reason);
						}
					);
			});
	};
	render() {
		return (

				{' '}
				2. Add Cat Fact{' '}

		);
	}
}
export default AddCat;
```

Now if you try this right now it should fail with this alert

![](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/14a50cf342f145d54b97001bb8f8d39732c0bf2c-942x296.jpg?w=942&q=82&fit=max&auto=format)

This is expected as our firestore.rules are set to strict mode, we will add those after we get through our authentication section next.You may also notice in the console (and on the screen fact jumps in and out) that firebase actually adds to our array, until failing on the backend. This is done on purpose as it gives us the fast UI that we expect while still maintaining the data integrity.

## Add Firebase Authentication

We need to store using state within our application, so we can define a state object with a field `user` we will then use this from firebase when a user is logged in. We will also import a new `SignIn` button that we can use to hide show Sign In / Sign Out depending on the current state.In the `SignIn` component we will for the first time start using props, we will pass the user state as well as a couple of our functions that are needed in the component to update our `user.App.js`

Copied! 🐾

```
... import { firestore, loggedIn$ } from './Firebase'; ...
state = { user: null }; componentDidMount() {
    /\* Observable from RxFire \*/
    loggedIn$.subscribe(user => { this.authHandler({ user });
    //Update state on load of app
    const { displayName, email, phoneNumber, photoURL } = user;
    firestore .collection('users') .doc(user.uid)
    .set({ displayName, email, phoneNumber, photoURL });
    }); }
    authHandler = async authData => {
        this.setUser(authData.user); };
        setUser = user => {
            this.setState({ user: user }); };
            ...

            ...
```

`SignIn.js`

Copied! 🐾
      );
    } else {
      return (

          {" "}
          Welcome {this.props.user.email} {" "}
          {" "}

      );
    }
  }
}
export default SignIn;

" aria-label="Copy code" title="Copy code to clipboard">

```
import React from "react";
import firebase, { app } from "../Firebase";
class SignIn extends React.Component {
  signIn = () => {
    const authProvider = new firebase.auth.GoogleAuthProvider();
    app.auth().signInWithPopup(authProvider).then(this.props.authHandler);
  };
  signOut = async () => {
    await firebase.auth().signOut();
    this.props.setUser(null);
  };
  render() {
    if (!this.props.user) {
      return (

          {" "}
          1. Sign In{" "}

      );
    } else {
      return (

          {" "}
          Welcome {this.props.user.email} {" "}

            {" "}
            4. Sign Out{" "}
          {" "}

      );
    }
  }
}
export default SignIn;
```

## Update AddCat to include user uid

### Pass user to AddCat

Update our main app to pass the user prop.App.js

Now we can use this to include with our data going to firestore. AddCat.js

Copied! 🐾

```
... .add({ ...value, uid: this.props.user.uid, catFactDate: new Date() }) ...
```

As well as whether or not to show the Add Cat Fact button, we check to see if the user exists. This button should only show when a user is signed in.

Copied! 🐾 ); return addCatButton; }

" aria-label="Copy code" title="Copy code to clipboard">

```
render() { let addCatButton = null; if (this.props.user) addCatButton = (  2. Add Cat Fact  ); return addCatButton; }
```

## Update firestore.rules

Copied! 🐾

```
service cloud.firestore {
    match /databases/{database}/documents {
    // LockDown All
    match /{document=\*\*} {
        allow read: if false; allow write: if false;
        }
        // User
        match /users/{userId} {
            allow read: if false;
            allow write: if request.resource.id == request.auth.uid;
        }
        // CatFacts
        match /catfacts/{catFactId} {
            allow read: if true;
            allow write: if request.auth.uid != null && request.resource.data.uid == request.auth.uid;
        }
    }
}
```

## Create List of Cat Facts

### Create ListCatFacts

This is probably the most important part of `RxFire` it will return an Observable that you can subscribe to for all changes to a collection by using the function `collectionData` which takes the collection as paramater as well as an option id to create, in our case we pass `catFactsRef.orderBy('catFactDate', 'desc')` and `'catFactId'`.Now we can just use a map to iterate on each catFact, whenever the Observable updates the current `catFact` state the array is updated and we can show the full list update using `{this.state.catfacts.map(catFact => {`.ListCatFacts.js

Copied! 🐾

```
import React from 'react'; import { collectionData, firestore } from '../Firebase'; class ListCatFacts extends React.Compo
```

## Resources, Links & Official Documentation

- **Watch on YouTube: ** [RxFire in ReactJS using Firebase Firestore and Authentication Full Video](https://www.youtube.com/watch?v=hTzcRCAm5e0) (plus [Subscribe to CodingCat.dev](https://www.youtube.com/@CodingCatDev?sub_confirmation=1))
- **🎥 YouTube: ** [https://link.ajonp.com/youtube](https://link.ajonp.com/youtube)
- **🌎 Site: ** [https://link.ajonp.com/😺](https://link.ajonp.com/😺)
- **📦 GitHub: ** [https://link.ajonp.com/github](https://link.ajonp.com/github)
- **🎓Lessons: ** [https://link.ajonp.com/lessons](https://link.ajonp.com/lessons)
- **🗞AJ’s Week in Web: ** [https://link.ajonp.com/week-in-web](https://link.ajonp.com/week-in-web)
- **💬 Slack: ** [https://link.ajonp.com/slack](https://link.ajonp.com/slack)
- **🐦 Twitter: ** [https://link.ajonp.com/twitter](https://link.ajonp.com/twitter)
- **💬 Slack: ** [https://bit.ly/ajonp-slack-invite](https://bit.ly/ajonp-slack-invite)
- **🐦 Twitter: ** [https://bit.ly/ajonp-twitter](https://bit.ly/ajonp-twitter)
- [**Firebase Documentation:**](https://firebase.google.com/docs) Firestore, Data Connect, Authentication, App Check, and Cloud Functions
- [**React Official Reference:**](https://react.dev/reference/react) Hooks, Server Components, and UI state patterns
- [**OWASP Top 10 & Application Security Guides:**](https://owasp.org/www-project-top-ten/) Vulnerability mitigation, authentication hardening, and CVE defense

## Related CodingCat.dev Tutorials & Podcast Episodes

- [**RxFire in Svelte 3 using Firebase Firestore and Authentication**](/post/rxfire-in-svelte-3-using-firebase-firestore-and-authentication): Introduction to Svelte3, Firebase, and RxFire. RxFire provides a set of observable creation methods. You simply call a function with some parameters to receive ...
- [**Zero-flicker Firestore SSR with React in Firebase: Web Architecture & Implementation Guide**](/post/firebase-2026-06-firestore-serialization-react): Hands-on web engineering breakdown of "Zero-flicker Firestore SSR with React" (2026-06-24). Learn how to integrate Firebase, Google Cloud, Web Dev, Next.js in p...
- [**Live text search with Firestore pipelines and React in Firebase: Web Architecture & Implementation Guide**](/post/firebase-2026-05-react-firestore-search): Hands-on web engineering breakdown of "Live text search with Firestore pipelines and React" (2026-05-28). Learn how to integrate Firebase, Google Cloud, Web Dev...

## Frequently Asked Questions (FAQ)

### What are the main takeaways from RxFire in ReactJS using Firebase Firestore and Authentication?

Introduction to Create React App, Firebase, and RxFire. RxFire provides a set of observable creation methods. You simply call a function with some parameters to receive an RxJS observable. With that observable in hand you can use any operators provided by RxJS to transform the stream as you like. RxFire in ReactJS using Firebase Firestore and Authentication: Original RxFire Blog: https://firebase.googleblog.com/2018/09/introducing-rxfire-easy-async-firebase.html
NPM: https://www.npmjs.com/package/rxfire 🎓Lesson: https://ajonp.com/lessons/rxfire-in-reactjs-using-firebase-firestore-and-authentication/ 🎥 YouTube: https://link.ajonp.com/youtube
🌎 Site:, today's lesson will be creating a react app and then implementing firebase using firestore and firebase authentication we'll also use our Xfire for an observable to pass the data from fire store and consume that within our application one assumption that I'm making in this video is that you're already familiar with firebase and how to use it in JavaScript so I'll add a card up here in YouTube so t... Throughout this post, Alex Patterson breaks down real-world implementation details for Firebase, React, Security so developers can apply these patterns directly in production.

### How do you implement Firebase best practices in production?

When adopting Firebase and React in a production stack, start by validating your configuration against the [**Firebase Documentation**](https://firebase.google.com/docs) (Firestore, Data Connect, Authentication, App Check, and Cloud Functions). Focus on incremental adoption, automated testing, and observability so your team can measure performance and developer velocity improvements at each stage.

### Where can I watch the full RxFire in ReactJS using Firebase Firestore and Authentication walkthrough and find related code resources?

You can watch the complete video session for [**RxFire in ReactJS using Firebase Firestore and Authentication**](https://www.youtube.com/watch?v=hTzcRCAm5e0) on the [**CodingCat.dev YouTube channel**](https://www.youtube.com/@CodingCatDev?sub_confirmation=1). For a deeper dive into Firebase, check out our related guide: [**RxFire in Svelte 3 using Firebase Firestore and Authentication**](/post/rxfire-in-svelte-3-using-firebase-firestore-and-authentication).

## ✏️ Video Summary

RxFire in ReactJS using Firebase Firestore and Authentication: Original RxFire Blog: https://firebase.googleblog.com/2018/09/introducing-rxfire-easy-async-firebase.html
NPM: https://www.npmjs.com/package/rxfire

🎓Lesson: https://ajonp.com/lessons/rxfire-in-reactjs-using-firebase-firestore-and-authentication/

🎥 YouTube: https://link.ajonp.com/youtube
🌎 Site: — today's lesson will be creating a react app and then implementing firebase using firestore and firebase authentication we'll also use our Xfire for an observable to pass the data from fire store and consume that within our application one assumption that I'm making in this video is that you're already familiar with firebase and how to use it in JavaScript so I'll add a card up here in YouTube so t...

✏️ Visual Architecture Diagram

## how this post connects together.

Follow AJ from first principles to production-ready architecture.

Let’s build it!✏️ Visual Diagram: RxFire in ReactJS using Firebase Firestore and A…✓ Good PatternVISUAL DIAGRAM[Diagram Walkthrough]Step-by-step diagram breakdown for RxFire in ReactJS using Firebase Firestore and Authentication: start with RxFire in ReactJS usin, implement Hands-On Implementation, and ship to production.AAA Contrast Verified

## related deep dives.

[All Blog Posts&rarr;](/blog)[![Triple-layer security for Firebase web apps: Web Architecture & Implementation Guide](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/9ab8cfe36d4309e12a606c5516554897a01000e0-1200x630.svg?w=1200&q=82&fit=max&auto=format)](/post/firebase-2026-07-three-layer-security)July 31, 2026[![](/logos/firebase/firebase-symbol.png)![](/logos/firebase/firebase-symbol.png)Firebase](/topic/firebase)

### [Triple-layer security for Firebase web apps: Web Architecture & Implementation Guide](/post/firebase-2026-07-three-layer-security)

Alex Patterson's hands-on web engineering breakdown of "Triple-layer security for Firebase web apps" (2026-07-30). Learn how to wire up Firebase, Google Cloud, Web Dev, TypeScript in production web apps.

[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)[![Authentication made easy: Building a secure e-commerce shopping cart with Firebase: Web Architecture & Implementation Guide](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/501fecb50b0a3d09664436db091b57ec1f9aba5f-1200x630.svg?w=1200&q=82&fit=max&auto=format)](/post/firebase-2026-09-secure-shopping-cart-firebase)September 2, 2026[![](/logos/firebase/firebase-symbol.png)![](/logos/firebase/firebase-symbol.png)Firebase](/topic/firebase)

### [Authentication made easy: Building a secure e-commerce shopping cart with Firebase: Web Architecture & Implementation Guide](/post/firebase-2026-09-secure-shopping-cart-firebase)

Alex Patterson's hands-on web engineering breakdown of "Authentication made easy: Building a secure e-commerce shopping cart with Firebase" (2026-09-01). Learn how to wire up Firebase, Google Cloud, Web Dev, TypeScript in production web apps.

[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)