Get to know Firebase for web

1. Overview

In this codelab, you'll learn some of the basics of Firebase to create interactive web applications. You'll build an event RSVP and guestbook chat app using several Firebase products.

screenshot of this step

What you'll learn

  • Authenticate users with Firebase Authentication and FirebaseUI.
  • Sync data using Cloud Firestore.
  • Write Firebase Security Rules to secure a database.

What you'll need

  • A browser of your choice, such as Chrome.
  • Access to stackblitz.com (no account or sign-in necessary).
  • A Google account, like a gmail account. We recommend the email account that you already use for your GitHub account. This allows you to use advanced features in StackBlitz.
  • The codelab's sample code. See the next step for how to get the code.

2. Get the starting code

In this codelab, you build an app using StackBlitz, an online editor that has several Firebase workflows integrated into it. Stackblitz requires no software installation or special StackBlitz account.

StackBlitz lets you share projects with others. Other people who have your StackBlitz project URL can see your code and fork your project, but they can't edit your StackBlitz project.

  1. Go to this URL for the starting code: https://stackblitz.com/edit/firebase-gtk-web-start
  2. At the top of the StackBlitz page, click Fork:

screenshot of this step

You now have a copy of the starting code as your own StackBlitz project, which has a unique name, along with a unique URL. All of your files and changes are saved in this StackBlitz project.

3. Edit event information

The starting materials for this codelab provide some structure for the web app, including some stylesheets and a couple of HTML containers for the app. Later in this codelab, you'll hook these containers up to Firebase.

To get started, let's get a bit more familiar with the StackBlitz interface.

  1. In StackBlitz, open the index.html file.
  2. Locate event-details-container and description-container, then try editing some event details.

As you edit the text, the automatic page reload in StackBlitz displays the new event details. Cool, yeah?

<!-- ... -->

<div id="app">
  <img src="..." />

  <section id="event-details-container">
     <h1>Firebase Meetup</h1>

     <p><i class="material-icons">calendar_today</i> October 30</p>
     <p><i class="material-icons">location_city</i> San Francisco</p>

  </section>

  <hr>

  <section id="firebaseui-auth-container"></section>

  <section id="description-container">
     <h2>What we'll be doing</h2>
     <p>Join us for a day full of Firebase Workshops and Pizza!</p>
  </section>
</div>

<!-- ... -->

The preview of your app should look something like this:

App preview

screenshot of this step

4. Create and set up a Firebase project

Displaying the event information is great for your guests, but just showing the events isn't very useful for anybody. Let's add some dynamic functionality to this app. For this, you'll need to hook Firebase up to your app. To get started with Firebase, you'll need to create and set up a Firebase project.

Create a Firebase project

  1. Sign in to Firebase.
  2. In the Firebase console, click Add Project (or Create a project), then name your Firebase project Firebase-Web-Codelab.

    screenshot of this step

  3. Click through the project creation options. Accept the Firebase terms if prompted. On the Google Analytics screen, click "Don't Enable", because you won't be using Analytics for this app.

To learn more about Firebase projects, see Understand Firebase projects.

Enable and set up Firebase products in the console

The app that you're building uses several Firebase products that are available for web apps:

  • Firebase Authentication and Firebase UI to easily allow your users to sign in to your app.
  • Cloud Firestore to save structured data on the cloud and get instant notification when data changes.
  • Firebase Security Rules to secure your database.

Some of these products need special configuration or need to be enabled using the Firebase console.

Enable email sign-in for Firebase Authentication

To allow users to sign in to the web app, you'll use the Email/Password sign-in method for this codelab:

  1. In the left-side panel of the Firebase console, click Build > Authentication. Then click Get Started. You're now in the Authentication dashboard, where you can see signed-up users, configure sign-in providers, and manage settings.

    screenshot of this step

  2. Select the Sign-in method tab (or click here to go directly to the tab).

    screenshot of this step

  3. Click Email/Password from the provider options, toggle the switch to Enable, and then click Save.

    screenshot of this step

Set up Cloud Firestore

The web app uses Cloud Firestore to save chat messages and receive new chat messages.

Here's how to set up Cloud Firestore:

  1. In the left-side panel of the Firebase console, click Build > Firestore Database. Then click Create database.
  2. Click Create database.

    screenshot of this step

  3. Select the Start in test mode option. Read the disclaimer about the security rules. Test mode ensures that you can freely write to the database during development. Click Next.

    screenshot of this step

  4. Select the location for your database (you can just use the default). Note, though, that this location can't be changed later.

    screenshot of this step

  5. Click Done.

5. Add and configure Firebase

Now that you have your Firebase project created and some services enabled, you need to tell the code that you want to use Firebase, as well as which Firebase project to use.

Add the Firebase libraries

For your app to use Firebase, you need to add the Firebase libraries to the app. There are multiple ways to do this, as described in the Firebase documentation. For example, you can add the libraries from Google's CDN, or you can install them locally using npm and then package them in your app if you're using Browserify.

StackBlitz provides automatic bundling, so you can add the Firebase libraries using import statements. You will be using the modular (v9) versions of the libraries, which help reduce the overall size of the webpage though a process called "tree shaking". You can learn more about the modular SDKs in the docs.

To build this app, you use the Firebase Authentication, FirebaseUI, and Cloud Firestore libraries. For this codelab, the following import statements are already included at the top of the index.js file, and we'll be importing more methods from each Firebase library as we go:

// Import stylesheets
import './style.css';

// Firebase App (the core Firebase SDK) is always required
import { initializeApp } from 'firebase/app';

// Add the Firebase products and methods that you want to use
import {} from 'firebase/auth';
import {} from 'firebase/firestore';

import * as firebaseui from 'firebaseui';

Add a Firebase web app to your Firebase project

  1. Back in the Firebase console, navigate to your project's overview page by clicking Project Overview in the top left.
  2. In the center of your project's overview page, click the web icon web app iconto create a new Firebase web app.

    screenshot of this step

  3. Register the app with the nickname Web App.
  4. For this codelab, do NOT check the box next to Also set up Firebase Hosting for this app. You'll use StackBlitz's preview pane for now.
  5. Click Register app.

    screenshot of this step

  6. Copy the Firebase configuration object to your clipboard.

    screenshot of this step

  7. Click Continue to console.Add the Firebase configuration object to your app:
  8. Back in StackBlitz, go to the index.js file.
  9. Locate the Add Firebase project configuration object here comment line, then paste your configuration snippet just below the comment.
  10. Add the initializeApp function call to set up Firebase using your unique Firebase project configuration.
    // ...
    // Add Firebase project configuration object here
    const firebaseConfig = {
      apiKey: "random-unique-string",
      authDomain: "your-projectId.firebaseapp.com",
      databaseURL: "https://your-projectId.firebaseio.com",
      projectId: "your-projectId",
      storageBucket: "your-projectId.appspot.com",
      messagingSenderId: "random-unique-string",
      appId: "random-unique-string",
    };
    
    // Initialize Firebase
    initializeApp(firebaseConfig);
    

6. Add user sign-in (RSVP)

Now that you've added Firebase to the app, you can set up an RSVP button that registers people using Firebase Authentication.

Authenticate your users with Email Sign-In and FirebaseUI

You'll need an RSVP button that prompts the user to sign in with their email address. You can do this by hooking up FirebaseUI to an RSVP button.FirebaseUI is a library which gives you a pre-built UI on top of Firebase Auth.

FirebaseUI requires a configuration (see the options in the documentation) that does two things:

  • Tells FirebaseUI that you want to use the Email/Password sign-in method.
  • Handles the callback for a successful sign-in and returns false to avoid a redirect. You don't want the page to refresh because you're building a single-page web app.

Add the code to initialize FirebaseUI Auth

  1. In StackBlitz, go to the index.js file.
  2. At the top, locate the firebase/auth import statement, then add getAuth and EmailAuthProvider, like so:
    // ...
    // Add the Firebase products and methods that you want to use
    import { getAuth, EmailAuthProvider } from 'firebase/auth';
    
    import {} from 'firebase/firestore';
    
  3. Save a reference to the auth object right after initializeApp, like so:
    initializeApp(firebaseConfig);
    auth = getAuth();
    
  4. Notice that the FirebaseUI configuration is already provided in the starting code. It's already setup to use the email auth provider.
  5. At the bottom of the main() function in index.js, add the FirebaseUI initialization statement, like so:
    async function main() {
      // ...
    
      // Initialize the FirebaseUI widget using Firebase
      const ui = new firebaseui.auth.AuthUI(auth);
    }
    main();
    
    

Add an RSVP button to the HTML

  1. In StackBlitz, go to the index.html file.
  2. Add the HTML for an RSVP button inside the event-details-container as shown in the example below.

    Be careful to use the same id values as shown below because, for this codelab, there are already hooks for these specific IDs in the index.js file.

    Note that in the index.html file, there's a container with the ID firebaseui-auth-container. This is the ID that you'll pass to FirebaseUI to hold your login.
    <!-- ... -->
    
    <section id="event-details-container">
        <!-- ... -->
        <!-- ADD THE RSVP BUTTON HERE -->
        <button id="startRsvp">RSVP</button>
    </section>
    <hr>
    <section id="firebaseui-auth-container"></section>
    <!-- ... -->
    
    App preview

    screenshot of this step

  3. Set up a listener on the RSVP button and call the FirebaseUI start function. This tells FirebaseUI that you want to see the sign-in window.

    Add the following code to the bottom of the main() function in index.js:
    async function main() {
      // ...
    
      // Listen to RSVP button clicks
      startRsvpButton.addEventListener("click",
       () => {
            ui.start("#firebaseui-auth-container", uiConfig);
      });
    }
    main();
    

Test signing in to the app

  1. In StackBlitz's preview window, click the RSVP button to sign in to the app.
    • For this codelab, you can use any email address, even a fake email address, since you're not setting up an email verification step for this codelab.
    • If you see an error message stating auth/operation-not-allowed or The given sign-in provider is disabled for this Firebase project, check to make sure that you enabled Email/Password as a sign-in provider in the Firebase console.
    App preview

    screenshot of this step

  2. Go to the Authentication dashboard in the Firebase console. In the Users tab, you should see the account information that you entered to sign in to the app.

    screenshot of this step

Add authentication state to the UI

Next, make sure that the UI reflects the fact that you're signed in.

You'll use the Firebase Authentication state listener callback, which gets notified whenever the user's sign-in status changes. If there's currently a signed-in user, your app will switch the "RSVP" button to a "logout" button.

  1. In StackBlitz, go to the index.js file.
  2. At the top, locate the firebase/auth import statement, then add signOut and onAuthStateChanged, like so:
    // ...
    // Add the Firebase products and methods that you want to use
    import {
      getAuth,
      EmailAuthProvider,
      signOut,
      onAuthStateChanged
    } from 'firebase/auth';
    
    import {} from 'firebase/firestore';
    
  3. Add the following code at the bottom of the main() function:
    async function main() {
      // ...
    
      // Listen to the current Auth state
      onAuthStateChanged(auth, user => {
        if (user) {
          startRsvpButton.textContent = 'LOGOUT';
        } else {
          startRsvpButton.textContent = 'RSVP';
        }
      });
    }
    main();
    
  4. In the button listener, check whether there is a current user and log them out. To do this, replace the current startRsvpButton.addEventListener with the following:
    // ...
    // Called when the user clicks the RSVP button
    startRsvpButton.addEventListener('click', () => {
      if (auth.currentUser) {
        // User is signed in; allows user to sign out
        signOut(auth);
      } else {
        // No user is signed in; allows user to sign in
        ui.start('#firebaseui-auth-container', uiConfig);
      }
    });
    

Now, the button in your app should show LOGOUT, and it should switch back to RSVP when it's clicked.

App preview

screenshot of this step

7. Write messages to Cloud Firestore

Knowing that users are coming is great, but let's give the guests something else to do in the app. What if they could leave messages in a guestbook? They can share why they're excited to come or who they hope to meet.

To store the chat messages that users write in the app, you'll use Cloud Firestore.

Data model

Cloud Firestore is a NoSQL database, and data stored in the database is split into collections, documents, fields, and subcollections. You will store each message of the chat as a document in a top-level collection called guestbook.

Firestore data model graphic showing a guestbook collection with multiple message documents

Add messages to Firestore

In this section, you'll add the functionality for users to write new messages to the database. First, you add the HTML for the UI elements (message field and send button). Then, you add the code that hooks these elements up to the database.

To add the UI elements of a message field and a send button:

  1. In StackBlitz, go to the index.html file.
  2. Locate the guestbook-container, then add the following HTML to create a form with the message input field and the send button.
    <!-- ... -->
    
     <section id="guestbook-container">
       <h2>Discussion</h2>
    
       <form id="leave-message">
         <label>Leave a message: </label>
         <input type="text" id="message">
         <button type="submit">
           <i class="material-icons">send</i>
           <span>SEND</span>
         </button>
       </form>
    
     </section>
    
    <!-- ... -->
    

App preview

screenshot of this step

A user clicking the SEND button will trigger the code snippet below. It adds the contents of the message input field to the guestbook collection of the database. Specifically, the addDoc method adds the message content to a new document (with an automatically generated ID) to the guestbook collection.

  1. In StackBlitz, go to the index.js file.
  2. At the top, locate the firebase/firestore import statement, then add getFirestore, addDoc, and collection, like so:
    // ...
    
    // Add the Firebase products and methods that you want to use
    import {
      getAuth,
      EmailAuthProvider,
      signOut,
      onAuthStateChanged
    } from 'firebase/auth';
    
    import {
      getFirestore,
      addDoc,
      collection
    } from 'firebase/firestore';
    
  3. Now we'll save a reference to the Firestore db object right after initializeApp:
    initializeApp(firebaseConfig);
    auth = getAuth();
    db = getFirestore();
    
  4. At the bottom of the main() function, add the following code.

    Note that auth.currentUser.uid is a reference to the auto-generated unique ID that Firebase Authentication gives for all logged-in users.
    async function main() {
      // ...
    
      // Listen to the form submission
      form.addEventListener('submit', async e => {
        // Prevent the default form redirect
        e.preventDefault();
        // Write a new message to the database collection "guestbook"
        addDoc(collection(db, 'guestbook'), {
          text: input.value,
          timestamp: Date.now(),
          name: auth.currentUser.displayName,
          userId: auth.currentUser.uid
        });
        // clear message input field
        input.value = '';
        // Return false to avoid redirect
        return false;
      });
    }
    main();
    

Show the guestbook only to signed-in users

You don't want just anybody to see the guests' chat. One thing that you can do to secure the chat is to allow only signed-in users to view the guestbook. That said, for your own apps, you'll want to also secure your database with Firebase Security Rules. (There's more information on security rules later in the codelab.)

  1. In StackBlitz, go to the index.js file.
  2. Edit the onAuthStateChanged listener to hide and show the guestbook.
    // ...
    
    // Listen to the current Auth state
    onAuthStateChanged(auth, user => {
      if (user) {
        startRsvpButton.textContent = 'LOGOUT';
        // Show guestbook to logged-in users
        guestbookContainer.style.display = 'block';
      } else {
        startRsvpButton.textContent = 'RSVP';
        // Hide guestbook for non-logged-in users
        guestbookContainer.style.display = 'none';
      }
    });
    

Test sending messages

  1. Make sure that you're signed in to the app.
  2. Enter a message such as "Hey there!", then click SEND.

This action writes the message to your Cloud Firestore database. However, you won't yet see the message in your actual web app because you still need to implement retrieving the data. You'll do that next.

But you can see the newly added message in the Firebase console.

In the Firebase console, in the Firestore Database dashboard, you should see the guestbook collection with your newly added message. If you keep sending messages, your guestbook collection will contain many documents, like this:

Firebase console

screenshot of this step

8. Read messages

Synchronize messages

It's lovely that guests can write messages to the database, but they can't see them in the app yet.

To display messages, you'll need to add listeners that trigger when data changes, then create a UI element that shows new messages.

You'll add code that listens for newly added messages from the app. First, add a section in the HTML to show messages:

  1. In StackBlitz, go to the index.html file.
  2. In guestbook-container, add a new section with the ID of guestbook.
    <!-- ... -->
    
      <section id="guestbook-container">
       <h2>Discussion</h2>
    
       <form><!-- ... --></form>
    
       <section id="guestbook"></section>
    
     </section>
    
    <!-- ... -->
    

Next, register the listener that listens for changes made to the data:

  1. In StackBlitz, go to the index.js file.
  2. At the top, locate the firebase/firestore import statement, then add query, orderBy, and onSnapshot, like so:
    // ...
    import {
      getFirestore,
      addDoc,
      collection,
      query,
      orderBy,
      onSnapshot
    } from 'firebase/firestore';
    
  3. At the bottom of the main() function, add the following code to loop through all the documents (guestbook messages) in the database. To learn more about what's happening in this code, read the information below the snippet.
    async function main() {
      // ...
    
      // Create query for messages
      const q = query(collection(db, 'guestbook'), orderBy('timestamp', 'desc'));
      onSnapshot(q, snaps => {
        // Reset page
        guestbook.innerHTML = '';
        // Loop through documents in database
        snaps.forEach(doc => {
          // Create an HTML entry for each document and add it to the chat
          const entry = document.createElement('p');
          entry.textContent = doc.data().name + ': ' + doc.data().text;
          guestbook.appendChild(entry);
        });
      });
    }
    main();
    

To listen to messages in the database, you've created a query on a specific collection by using the collection function. The code above listens to the changes in the guestbook collection, which is where the chat messages are stored. The messages are also ordered by date, using orderBy('timestamp', 'desc') to display the newest messages at the top.

The onSnapshot function takes two parameters: the query to use and a callback function. The callback function is triggered when there are any changes to documents that match the query. This could be if a message gets deleted, modified, or added. For more information, see the Cloud Firestore documentation.

Test synchronizing messages

Cloud Firestore automatically and instantly synchronizes data with clients subscribed to the database.

  • The messages that you created earlier in the database should be displayed in the app. Feel free to write new messages; they should appear instantly.
  • If you open your workspace in multiple windows or tabs, messages will sync in real time across tabs.
  • (Optional) You can try manually deleting, modifying, or adding new messages directly in the Database section of the Firebase console; any changes should appear in the UI.

Congratulations! You're reading Cloud Firestore documents in your app!

App preview

screenshot of this step

9. Set up basic security rules

You initially set up Cloud Firestore to use test mode, meaning that your database is open for reads and writes. However, you should only use test mode during very early stages of development. As a best practice, you should set up security rules for your database as you develop your app. Security should be integral to your app's structure and behavior.

Security Rules allow you to control access to documents and collections in your database. The flexible rules syntax allows you to create rules that match anything from all writes to the entire database to operations on a specific document.

You can write security rules for Cloud Firestore in the Firebase console:

  1. In the Firebase console's Build section, click Firestore Database, then select the Rules tab (or click here to go directly to the Rules tab).
  2. You should see the following default security rules, with a public-access time limit a couple of weeks from today.

screenshot of this step

Identify collections

First, identify the collections to which the app writes data.

  1. Delete the existing match /{document=**} clause, so your rules look like this:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
      }
    }
    
  2. In match /databases/{database}/documents, identify the collection that you want to secure:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /guestbook/{entry} {
         // You'll add rules here in the next step.
      }
    }
    

Add security rules

Because you used the Authentication UID as a field in each guestbook document, you can get the Authentication UID and verify that anyone attempting to write to the document has a matching Authentication UID.

  1. Add the read and write rules to your rule set as shown below:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /guestbook/{entry} {
          allow read: if request.auth.uid != null;
          allow create:
            if request.auth.uid == request.resource.data.userId;
        }
      }
    }
    
  2. Click Publish to deploy your new rules.Now, for the guestbook, only signed-in users can read messages (any message!), but you can only create a message using your user ID. We also don't allow messages to be edited or deleted.

Add validation rules

  1. Add data validation to make sure that all of the expected fields are present in the document:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /guestbook/{entry} {
          allow read: if request.auth.uid != null;
          allow create:
          if request.auth.uid == request.resource.data.userId
              && "name" in request.resource.data
              && "text" in request.resource.data
              && "timestamp" in request.resource.data;
        }
      }
    }
    
  2. Click Publish to deploy your new rules.

Reset listeners

Because your app now only allows authenticated users to log in, you should move the guestbook firestore query inside the Authentication listener. Otherwise, permission errors will occur and the app will be disconnected when the user logs out.

  1. In StackBlitz, go to the index.js file.
  2. Pull the guestbook collection onSnapshot listener into a new function called subscribeGuestbook. Also, assign the results of the onSnapshot function to the guestbookListener variable.

    The Firestore onSnapshot listener returns an unsubscribe function that you'll be able to use to cancel the snapshot listener later.
    // ...
    // Listen to guestbook updates
    function subscribeGuestbook() {
      const q = query(collection(db, 'guestbook'), orderBy('timestamp', 'desc'));
      guestbookListener = onSnapshot(q, snaps => {
        // Reset page
        guestbook.innerHTML = '';
        // Loop through documents in database
        snaps.forEach(doc => {
          // Create an HTML entry for each document and add it to the chat
          const entry = document.createElement('p');
          entry.textContent = doc.data().name + ': ' + doc.data().text;
          guestbook.appendChild(entry);
        });
      });
    }
    
  3. Add a new function underneath called unsubscribeGuestbook. Check whether the guestbookListener variable is not null, then call the function to cancel the listener.
    // ...
    // Unsubscribe from guestbook updates
    function unsubscribeGuestbook() {
      if (guestbookListener != null) {
        guestbookListener();
        guestbookListener = null;
      }
    }
    

Finally, add the new functions to the onAuthStateChanged callback.

  1. Add subscribeGuestbook() at the bottom of if (user).
  2. Add unsubscribeGuestbook() at the bottom of the else statement.
    // ...
    // Listen to the current Auth state
    onAuthStateChanged(auth, user => {
      if (user) {
        startRsvpButton.textContent = 'LOGOUT';
        // Show guestbook to logged-in users
        guestbookContainer.style.display = 'block';
        // Subscribe to the guestbook collection
        subscribeGuestbook();
      } else {
        startRsvpButton.textContent = 'RSVP';
        // Hide guestbook for non-logged-in users
        guestbookContainer.style.display = 'none';
        // Unsubscribe from the guestbook collection
        unsubscribeGuestbook();
      }
    });
    

10. Bonus step: Practice what you've learned

Record an attendee's RSVP status

Right now, your app just allows people to start chatting if they're interested in the event. Also, the only way you know if someone's coming is if they post it in the chat. Let's get organized and let people know how many people are coming.

You'll add a toggle to register people who want to attend the event, then collect a count of how many people are coming.

  1. In StackBlitz, go to the index.html file.
  2. In guestbook-container, add a set of YES and NO buttons, like so:
    <!-- ... -->
      <section id="guestbook-container">
       <h2>Are you attending?</h2>
         <button id="rsvp-yes">YES</button>
         <button id="rsvp-no">NO</button>
    
       <h2>Discussion</h2>
    
       <!-- ... -->
    
     </section>
    <!-- ... -->
    

App preview

screenshot of this step

Next, register the listener for button clicks. If the user clicks YES, then use their Authentication UID to save the response to the database.

  1. In StackBlitz, go to the index.js file.
  2. At the top, locate the firebase/firestore import statement, then add doc, setDoc, and where, like so:
    // ...
    // Add the Firebase products and methods that you want to use
    import {
      getFirestore,
      addDoc,
      collection,
      query,
      orderBy,
      onSnapshot,
      doc,
      setDoc,
      where
    } from 'firebase/firestore';
    
  3. At the bottom of the main() function, add the following code to listen to the RSVP status:
    async function main() {
      // ...
    
      // Listen to RSVP responses
      rsvpYes.onclick = async () => {
      };
      rsvpNo.onclick = async () => {
      };
    }
    main();
    
    
  4. Next, create a new collection called attendees, then register a document reference if either RSVP button is clicked. Set that reference to true or false depending on which button is clicked.

    First, for rsvpYes:
    // ...
    // Listen to RSVP responses
    rsvpYes.onclick = async () => {
      // Get a reference to the user's document in the attendees collection
      const userRef = doc(db, 'attendees', auth.currentUser.uid);
    
      // If they RSVP'd yes, save a document with attendi()ng: true
      try {
        await setDoc(userRef, {
          attending: true
        });
      } catch (e) {
        console.error(e);
      }
    };
    
    Then, the same for rsvpNo, but with the value false:
    rsvpNo.onclick = async () => {
      // Get a reference to the user's document in the attendees collection
      const userRef = doc(db, 'attendees', auth.currentUser.uid);
    
      // If they RSVP'd yes, save a document with attending: true
      try {
        await setDoc(userRef, {
          attending: false
        });
      } catch (e) {
        console.error(e);
      }
    };
    

Update your Security Rules

Because you already have some rules set up, the new data that you're adding with the buttons is going to be rejected.

Allow additions to the attendees collection

You'll need to update the rules to allow adding to the attendees collection.

  1. For the attendees collection, since you used the Authentication UID as the document name, you can grab it and verify that the submitter's uid is the same as the document they are writing. You'll allow everyone to read the attendees list (since there is no private data there), but only the creator should be able to update it.
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        // ... //
        match /attendees/{userId} {
          allow read: if true;
          allow write: if request.auth.uid == userId;
        }
      }
    }
    
  2. Click Publish to deploy your new rules.

Add validation rules

  1. Add some data validation rules to make sure that all of the expected fields are present in the document:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        // ... //
        match /attendees/{userId} {
          allow read: if true;
          allow write: if request.auth.uid == userId
              && "attending" in request.resource.data;
    
        }
      }
    }
    
  2. Don't forget to click Publish to deploy your rules!

(Optional) You can now view the results of clicking the buttons. Go to your Cloud Firestore dashboard in the Firebase console.

Read RSVP status

Now that you've recorded the responses, let's see who's coming and reflect it in the UI.

  1. In StackBlitz, go to the index.html file.
  2. In description-container, add a new element with the ID of number-attending.
    <!-- ... -->
    
     <section id="description-container">
         <!-- ... -->
         <p id="number-attending"></p>
     </section>
    
    <!-- ... -->
    

Next, register the listener for the attendees collection and count the number of YES responses:

  1. In StackBlitz, go to the index.js file.
  2. At the bottom of the main() function, add the following code to listen to the RSVP status and count YES clicks.
    async function main() {
      // ...
    
      // Listen for attendee list
      const attendingQuery = query(
        collection(db, 'attendees'),
        where('attending', '==', true)
      );
      const unsubscribe = onSnapshot(attendingQuery, snap => {
        const newAttendeeCount = snap.docs.length;
        numberAttending.innerHTML = newAttendeeCount + ' people going';
      });
    }
    main();
    

Finally, let's highlight the button corresponding to the current status.

  1. Create a function that checks whether the current Authentication UID has an entry in the attendees collection, then set the button class to clicked.
    // ...
    // Listen for attendee list
    function subscribeCurrentRSVP(user) {
      const ref = doc(db, 'attendees', user.uid);
      rsvpListener = onSnapshot(ref, doc => {
        if (doc && doc.data()) {
          const attendingResponse = doc.data().attending;
    
          // Update css classes for buttons
          if (attendingResponse) {
            rsvpYes.className = 'clicked';
            rsvpNo.className = '';
          } else {
            rsvpYes.className = '';
            rsvpNo.className = 'clicked';
          }
        }
      });
    }
    
  2. Also, let's make a function to unsubscribe. This will be used when the user logs out.
    // ...
    function unsubscribeCurrentRSVP() {
      if (rsvpListener != null) {
        rsvpListener();
        rsvpListener = null;
      }
      rsvpYes.className = '';
      rsvpNo.className = '';
    }
    
  3. Call the functions from the Authentication listener.
    // ...
    // Listen to the current Auth state
      // Listen to the current Auth state
      onAuthStateChanged(auth, user => {
        if (user) {
          startRsvpButton.textContent = 'LOGOUT';
          // Show guestbook to logged-in users
          guestbookContainer.style.display = 'block';
    
          // Subscribe to the guestbook collection
          subscribeGuestbook();
          // Subscribe to the user's RSVP
          subscribeCurrentRSVP(user);
        } else {
          startRsvpButton.textContent = 'RSVP';
          // Hide guestbook for non-logged-in users
          guestbookContainer.style.display = 'none'
          ;
          // Unsubscribe from the guestbook collection
          unsubscribeGuestbook();
          // Unsubscribe from the guestbook collection
          unsubscribeCurrentRSVP();
        }
      });
    
  4. Try logging in as multiple users and see the count increase with each additional YES button click.

App preview

screenshot of this step

11. Congratulations!

You've used Firebase to build an interactive, real-time web application!

What we've covered

  • Firebase Authentication
  • FirebaseUI
  • Cloud Firestore
  • Firebase Security Rules

Next steps

  • Want to learn more the Firebase Developer Workflow? Check out the Firebase emulator codelab to learn about how to test and run your app completely locally.
  • Want to learn more about other Firebase products? Maybe you want to store image files that users upload? Or send notifications to your users? Check out the Firebase web codelab for a codelab that goes into more depth on many more Firebase products for web.
  • Want to learn more about Cloud Firestore? Maybe you want to learn about subcollections and transactions? Head over to the Cloud Firestore web codelab for a codelab that goes into more depth on Cloud Firestore. Or check out this YouTube series to get to know Cloud Firestore!

Learn more

How did it go?

We would love your feedback! Please fill out a (very) short form here.