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

# RxFire in Svelte 3 using Firebase Firestore and Authentication

✏️ Blog PostMay 24, 2022[![](/logos/firebase/firebase-symbol.png)![](/logos/firebase/firebase-symbol.png)Firebase](/topic/firebase)[![](/logos/tags/svelte-symbol-light.svg)![](/logos/tags/svelte-symbol-dark.svg)Svelte](/topic/svelte)[#Security](/topic/security)[![](/logos/tags/html-symbol-light.svg)![](/logos/tags/html-symbol-dark.svg)HTML](/topic/html)[![](/logos/tags/angular-symbol-light.svg)![](/logos/tags/angular-symbol-dark.svg)Angular](/topic/angular)[![](/logos/tags/react-symbol-light.svg)![](/logos/tags/react-symbol-dark.svg)React](/topic/react)[![](/logos/tags/javascript-symbol-light.svg)![](/logos/tags/javascript-symbol-dark.svg)JavaScript](/topic/javascript)[![](/logos/tags/github-symbol-light.svg)![](/logos/tags/github-symbol-dark.svg)GitHub](/topic/github)

# RxFire in Svelte 3 using Firebase Firestore and Authentication

![](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/8f112a33677dfbfc7253c60d157baf363e13ebe6-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=ju80EzhnCE8&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 [Svelte 3](https://svelte.dev/) 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 Svelte 3, Please checkout

## Example

In the example below it shows a quick preview osf 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. Also [npx](https://github.com/zkat/npx) is the easiest using the template provided on git.

`npx degit sveltejs/template rxfire-svelte cd rxfire/svelte`

You will also need to create your own Firebase project and initialize a Firestore database, please create this using strict mode. [Example rules](https://github.com/AJONPLLC/rxfire-react-cats/blob/master/firestore.rules);

## Final App Structure

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

## Install dependencies

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

npm i rxfire firebase rxjs

## 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 Svelte 3.

## Simple Initial Component

### Remove App.svelte and replace it with the following

You can basically think of a .svelte file equal to an html file. There are a few things to note here, any styles are scoped to the current component by default, in order to get styles outside of this you can place them within something like `:global(div.flex-row)`. However (maybe best practice), I found it easier to move these from App.svelte over to `/public/global.css`;App.svelte

Copied! 🐾

```

    import Instructions from './components/Instructions.svelte';
    import SignIn from './components/Signin.svelte';
    import AddCat from './components/AddCat.svelte';
    import ListCatFacts from './components/ListCatFacts.svelte';
    import { loggedIn$ } from './Firebase.js'
    /\* Make something more observable \*/
    const user = loggedIn$;

    /\* :global(div.flex-row){ display: flex; justify-content: center; flex-flow: row wrap; } :global(div.flex-column){ display: flex; justify-content: center; flex-flow: column; } .max-800{ max-width: 800px; } \*/

```

### Create Instructions.svelte

This is a very simple Svelte Component that takes no [props](https://svelte.dev/tutorial/declaring-props), it just returns straight html.components/Instructions.svelte

Copied! 🐾

```

     ![rxfire for cats](https://res.cloudinary.com/ajonp/image/upload/w\_500/v1556553295/ajonp-ajonp-com/18-rxfire-svelte-cats/RxFire\_Svelt.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.svelte

- Add Cat Fact This will use an API and Insert the facts into Firestore

- Found in components/AddCat.svelte

- Firestore collection Observing catfacts for changes, heart eyes are your facts

- Found in components/ListCatFacts.svelte

- Sign Out Observe that user is removed

```

## Update collection catfacts

### Create AddCat.svelte

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.svelte into our App.svelte.

### Update App.svelte

App.svelte

Copied! 🐾

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

We will now pass our first prop to `AddCat`, this is done simple by declaring a variable and passing it, in our case we will use `const user = loggedIn$`. Is this necessary, probably not but I wanted to show passing a prop, we could ideally just grab this from `Firebase.js`.Take note on the child we can then access this prop by defining `export let user;`.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.We add a random cat fact to firestore and by adding our `catFactDate` to the object. This allows us to later sort the facts in our list in descending order.Things we need to pay special note to here are

- #if - [If blocks](https://svelte.dev/docs#If_blocks) just a standard if that you would expect
- $user - [Subscriptions](https://svelte.dev/docs#svelte_store) if you come from angular this is like the async pipe.
- `on:click={addCatFact - [Component Events](https://svelte.dev/docs#Component_events)` this is similar to the events normally found on html componens but here we are passing the function `addCatFact` by just surrounding with curlys.

Copied! 🐾 {/if}

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

```

    import { firestore } from '../Firebase';
    import catFacts from '../random.js';
    export let user;
    const addCatFact = async () => {
        try {
            /\* Gave up on the API working!!! \*/
            const value = catFacts\[Math.floor(Math.random() \* catFacts.length)\];
            await firestore.collection('catfacts').add({ ...value, catFactDate: new Date() });
        }
        catch (error) { console.error(error); }
    };

    {#if $user}  2. Add Cat Fact  {/if}
```

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

### Update App.svelte

In the `SignIn` component we will again use props, we will pass the user state.App.svelte

` ... import SignIn from './components/Signin.svelte'; ...  ...  ...`

Copied! 🐾

  {:else}
   {/if}

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

```

  import firebase, { app } from '../Firebase'; /\* this is like props \*/ export let user; const signIn = () => { const authProvider = new firebase.auth.GoogleAuthProvider(); app.auth().signInWithPopup(authProvider); }; const signOut = async () => { await firebase.auth().signOut(); };

  {#if $user}

#
    Welcome {$user.email}
    4. Sign Out

  {:else}
  1. Sign In {/if}

```

## Update AddCat to include user uid

### Pass user to AddCat

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

``

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

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! 🐾 {/if}

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

```
 {#if $user}  2. Add Cat Fact  {/if}
```

## 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 `{#each $catFacts as catFact}` then if you are the owner of the fact you get catheart eyes using a if block.

Copied! 🐾
  {/if}

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

```

  import { firestore } from "../Firebase";
  import catFacts from "../random.js";
  export let user;
  const addCatFact = async () => {
    try {
      /\* Gave up on the API working!!! \*/ const value =
        catFacts\[Math.floor(Math.random() \* catFacts.length)\];
      await firestore
        .collection("catfacts")
        .add({ ...value, catFactDate: new Date() });
    } catch (error) {
      console.error(error);
    }
  };

  {#if $user}
  2. Add Cat Fact
  {/if}

```

## Resources, Links & Official Documentation

- **Watch on YouTube: ** [RxFire in Svelte 3 using Firebase Firestore and Authentication Full Video](https://www.youtube.com/watch?v=ju80EzhnCE8) (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
- [**Svelte & SvelteKit Documentation:**](https://svelte.dev/docs) Runes, compiler internals, and full-stack SvelteKit routing
- [**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 ReactJS using Firebase Firestore and Authentication**](/post/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...
- [**What web frameworks does Firebase App Hosting support?: Web Architecture & Implementation Guide**](/post/firebase-2025-06-app-hosting-frameworks): Hands-on web engineering breakdown of "What web frameworks does Firebase App Hosting support?" (2025-06-05). Learn how to integrate Firebase, Google Cloud, Web ...
- [**Use Firestore to Build Hugo Content**](/post/use-firestore-to-build-hugo-content): Use a frontend app (Angular), to update a Firestore Backend, trigger Firebase Function, while maintaining git commits, and buld/deploy your Hugo site.

## Frequently Asked Questions (FAQ)

### What are the main takeaways from 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 an RxJS observable. With that observable in hand you can use any operators provided by RxJS to transform the stream as you like. Svelte 3 and RxFire using Firebase Firestore and Authentication: Svelte 3 - https://svelte.dev/ 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-svelte-3-using-firebase-firestore-and-authentication/ 🎥 YouTube: https:, hello and welcome back to AJ imperfect solutions I wanted to cover our Xfire ins felt three today this is very similar to our RX fire with react GS that was just published so I'm gonna put a card link up for that we're going to use npx to get started so in order to do that you can do NPM I - G and then NP X and it will install this dependency global and the command we're gonna be looking for is NP... Throughout this post, Alex Patterson breaks down real-world implementation details for Firebase, Svelte, Security so developers can apply these patterns directly in production.

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

When adopting Firebase and Svelte 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 Svelte 3 using Firebase Firestore and Authentication walkthrough and find related code resources?

You can watch the complete video session for [**RxFire in Svelte 3 using Firebase Firestore and Authentication**](https://www.youtube.com/watch?v=ju80EzhnCE8) 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 ReactJS using Firebase Firestore and Authentication**](/post/rxfire-in-reactjs-using-firebase-firestore-and-authentication).

## ✏️ Video Summary

Svelte 3 and RxFire using Firebase Firestore and Authentication: Svelte 3 - https://svelte.dev/

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-svelte-3-using-firebase-firestore-and-authentication/

🎥 YouTube: https: — hello and welcome back to AJ imperfect solutions I wanted to cover our Xfire ins felt three today this is very similar to our RX fire with react GS that was just published so I'm gonna put a card link up for that we're going to use npx to get started so in order to do that you can do NPM I - G and then NP X and it will install this dependency global and the command we're gonna be looking for is NP...

✏️ Visual Architecture Diagram

## how this post connects together.

Follow AJ through the pipeline topology from input contract to production output.

Let’s build it!✏️ Architecture Diagram: RxFire in Svelte 3 using Firebase Firestore and …DATAFLOW PIPELINEARCHITECTURE DIAGRAM[Diagram Walkthrough]Content-driven pipeline diagram for RxFire in Svelte 3 using Firebase Firestore and Authentication: RxFire -> Svelte 3 using Firebase  -> Edge Delivery & Telemetry.AAA Contrast Verified

## related deep dives.

[All Blog Posts&rarr;](/blog)[![The Odin Project 1: Web Development Foundations (HTML, CSS, Flexbox & JS Basics)](https://cdn.sanity.io/images/hfh83o0w/production/fce6fcae58667ff3143db133eb6b57fbd9ec471f-1376x768.png?w=1376&q=82&fit=max&auto=format)](/course/odin-web-development-foundations)November 4, 2026[![](/logos/tags/html-symbol-light.svg)![](/logos/tags/html-symbol-dark.svg)HTML](/topic/html)[![](/logos/tags/css-symbol-light.svg)![](/logos/tags/css-symbol-dark.svg)CSS](/topic/css)[![](/logos/tags/javascript-symbol-light.svg)![](/logos/tags/javascript-symbol-dark.svg)JavaScript](/topic/javascript)[+1](/course/odin-web-development-foundations)

### [The Odin Project 1: Web Development Foundations (HTML, CSS, Flexbox & JS Basics)](/course/odin-web-development-foundations)

Master the complete Odin Project Foundations path modernized for 2026: how the web works, semantic HTML5, CSS Box Model & Flexbox, and JavaScript DOM fundamentals.

[![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)[![The Five Layers of Agentic Context: Why Canon Only Turns When Someone Signs Off](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/d702615b4d3c30ea99dc40f10a576db4cd1c4c73-2752x1536.jpg?w=1920&q=82&fit=max&auto=format)](/post/the-five-layers-of-agentic-context-why-canon-only-turns-when-someone-signs-off)October 14, 2026[![](/logos/tags/html-symbol-light.svg)![](/logos/tags/html-symbol-dark.svg)HTML](/topic/html)[![](/logos/tags/mcp-symbol-light.svg)![](/logos/tags/mcp-symbol-dark.svg)MCP](/topic/mcp)[#AI & Agents](/topic/ai)[+3](/post/the-five-layers-of-agentic-context-why-canon-only-turns-when-someone-signs-off)

### [The Five Layers of Agentic Context: Why Canon Only Turns When Someone Signs Off](/post/the-five-layers-of-agentic-context-why-canon-only-turns-when-someone-signs-off)

A deep-dive review of Magnus Hillestad's Five Layers of Agentic Context on the Sanity blog, exploring why Situation, Records, Memory, Process, and Canon move at different speeds, plus a working interactive HTML/SVG Situation-to-Canon wheel you can drop into any webpage.

[![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)