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

What you'll learn

What you'll need

In this codelab, you build and deploy 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:

You now have a copy of the starting code as your own StackBlitz project. Since you didn't sign in, your account is called @anonymous, but the project has a unique name, along with a unique URL. All of your files and changes are saved in this StackBlitz project.

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, and 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

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), and name your Firebase project Firebase-Web-Codelab.

  1. Click through the project creation options. Accept the Firebase terms if prompted. Skip setting up Google Analytics, because you won't be using Analytics for this app.

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

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

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 Firebase console, click Develop in the left panel.
  2. Click Authentication, and then click the Sign-in method tab (or click here to go directly to the Sign-in method tab).
  3. Click Email/Password in the Sign-in providers list, set the Enable switch to the on position, and then click Save.

Enable Cloud Firestore

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

Enable Cloud Firestore:

  1. In the Firebase console's Develop section, click Database.
  2. Under Cloud Firestore, click Create database.
  1. 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.
  1. Select the location for your database (You can just use the default). Note that this location can't be changed later.
  2. Click Done.

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.

To build this app, you use the Firebase Authentication, FirebaseUI, and Cloud Firestore libraries. For this codelab, the following lines are already included at the top of the index.js file:

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

// Firebase App (the core Firebase SDK) is always required
// and must be listed first
import * as firebase from "firebase/app";

// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";

import * as firebaseui from "firebaseui";

Add a Firebase web app to the 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 to create a new Firebase web app.

  1. Register the app with the nickname Web App.
  2. For this codelab, don't check the box next to Also set up Firebase Hosting for this app. You'll use StackBlitz's preview pane for now.
  3. Click Register app.
  1. Copy the Firebase configuration object to the clipboard.
  2. Click Continue to console.

Add the Firebase configuration object to your app:

  1. Back in StackBlitz, go to the index.js file.
  2. Locate the Add Firebase project configuration object here comment line, and paste your configuration snippet just below the comment.
  3. Add the initializeApp function call to set up Firebase using your unique Firebase project configuration.
// ...

// Add Firebase project configuration object here
var 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
firebase.initializeApp(firebaseConfig);

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:

  1. Tells FirebaseUI that you want to use the Email/Password sign-in method.
  2. 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.

First, add the code to initialize FirebaseUI:

  1. In StackBlitz, go to the index.js file. Notice that the FirebaseUI configuration is already provided.
  2. At the bottom of index.js, add the FirebaseUI initialization statement, like so:
// ...
// Initialize the FirebaseUI widget using Firebase
const ui = new firebaseui.auth.AuthUI(firebase.auth());

Next, 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

  1. 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 index.js:
// ... 
// At the bottom

// Listen to RSVP button clicks
startRsvpButton.addEventListener("click",
 () => {
      ui.start("#firebaseui-auth-container", uiConfig);
});

Test signing in to the app

  1. In StackBlitz's preview window, click the RSVP button to sign in to the app.
  1. 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.

App preview

Add authentication state to the UI

Now 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 is currently a user, you'll switch the RSVP button to a logout button.

  1. In StackBlitz, go to the index.js file.
  2. Add the following code at the bottom:
// ...
// Listen to the current Auth state
firebase.auth().onAuthStateChanged((user)=> {
  if (user) {
    startRsvpButton.textContent = "LOGOUT"
  }
  else {
    startRsvpButton.textContent = "RSVP"
  }
});
  1. 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 (firebase.auth().currentUser) {
      // User is signed in; allows user to sign out
      firebase.auth().signOut();
    } else {
      // No user is signed in; allows user to sign in
      ui.start("#firebaseui-auth-container", uiConfig);
    }
});

Now the button should show LOGOUT, and switch back to RSVP when it is clicked.

App preview

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.

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), and 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, do the following:

  1. In StackBlitz, go to the index.html file.
  2. Locate the guestbook-container, and 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

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 add 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 bottom of the file, add the following code.

Note that firebase.auth().currentUser.uid is a reference to the auto-generated unique ID that Firebase Authentication gives for all logged-in users.

// ..
// Listen to the form submission
form.addEventListener("submit", (e) => {
 // Prevent the default form redirect
 e.preventDefault();
 // Write a new message to the database collection "guestbook"
 firebase.firestore().collection("guestbook").add({
   text: input.value,
   timestamp: Date.now(),
   name: firebase.auth().currentUser.displayName,
   userId: firebase.auth().currentUser.uid
 })
 // clear message input field
 input.value = ""; 
 // Return false to avoid redirect
 return false;
});

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
firebase.auth().onAuthStateChanged((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!", and 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 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

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 and 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 bottom of the file, add the following code to loop through all the documents (guestbook messages) in the database:
// ...
// Create query for messages
firebase.firestore().collection("guestbook")
.orderBy("timestamp","desc")
.onSnapshot((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);
 });
});

To listen to messages in the database, create 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 one parameter: 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.

  1. 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.
  2. If you open your workspace in multiple windows or tabs, messages will sync in real time across tabs.
  3. (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 are reading Cloud Firestore documents in your app!

App preview

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 Develop section, click Database, and then select the Rules tab (or click here to go directly to the Rules tab).
  2. You should see the following default security rules, along with a warning about the rules being public.

Identify collections

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

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.

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 write:
        if request.auth.uid == request.resource.data.userId;
    }
  }
}

Now, for the guestbook, only signed-in users can read messages (any message!), but only a message's author can edit a message.

Add validation rules

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 write:
      if request.auth.uid == request.resource.data.userId
          && "name" in request.resource.data
          && "text" in request.resource.data
          && "timestamp" in request.resource.data;
    }
  }
}

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. 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(){
   // Create query for messages
 guestbookListener = firebase.firestore().collection("guestbook")
 .orderBy("timestamp","desc")
 .onSnapshot((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);
   });
 });
};
  1. Add a new function underneath called unsubscribeGuestbook. Check whether the guestbookListener variable is not null, and then call the function to cancel the listener.
// ...
// Unsubscribe from guestbook updates
function unsubscribeGuestbook(){
 if (guestbookListener != null)
 {
   guestbookListener();
   guestbookListener = null;
 }
};
  1. Finally, add the new functions to the onAuthStateChanged callback (use the following two steps).
  2. Add subscribeGuestbook() at the bottom of if (user).
  3. Add unsubscribeGuestbook() at the bottom of the else statement.
// ...
firebase.auth().onAuthStateChanged((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();
}
});

Firebase offers a hosting service to serve your web app's assets. You can deploy your files and hosting configuration to Firebase Hosting using the Firebase command-line interface (CLI). But for this codelab, you're using StackBlitz, which has integrated the Firebase CLI into its workspace!

You can use StackBlitz's Firebase integration to tell StackBlitz to which Firebase project you'd like to deploy assets:

  1. If you haven't already signed in with GitHub in StackBlitz, click Sign in in the top right, and then enter your GitHub account credentials.

  1. There should now be a Firebase icon in the left panel.

  2. Click Sign in to Google.
    Sign in using the same email address that you used to sign in to Firebase.
  3. From the list of Firebase projects, select your Firebase-Web-Codelab project.

Deploying to Firebase Hosting with StackBlitz is literally a one-click operation:

  1. In the StackBlitz workspace, click Deploy on the left side of the page. Yep, that's it. One step!

Visit the documentation to learn more about how Firebase Hosting works.

Go to your project's Firebase console Hosting section to view useful hosting information and tools, including the history of your deployments, the functionality to roll back to previous versions of your app, and the workflow to set up a custom domain.

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

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 bottom of the file, add the following code to listen to the RSVP status:
// ...

// Listen to RSVP responses
rsvpYes.onclick = () => {
}
rsvpNo.onclick = () => {
}
  1. Create a new collection called attendees, then register a document reference if either RSVP button is clicked.
  2. Set that reference to true or false depending on which button is clicked.

First, for rsvpYes:

// ...

// Listen to RSVP responses
rsvpYes.onclick = () => {
 // Get a reference to the user's document in the attendees collection
 const userDoc = firebase.firestore().collection('attendees').doc(firebase.auth().currentUser.uid);

 // If they RSVP'd yes, save a document with attending: true
 userDoc.set({
   attending: true
 }).catch(console.error)
}

Then, the same for rsvpNo, but with the value false:

rsvpNo.onclick = () => {
 // Get a reference to the user's document in the attendees collection
 const userDoc = firebase.firestore().collection('attendees').doc(firebase.auth().currentUser.uid);

 // If they RSVP'd no, save a document with attending: false
 userDoc.set({
   attending: false
 }).catch(console.error)
}

Add rules

Because you already have some rules set up, the new data that you're adding with the buttons is going to be rejected. You'll need to update the rules to allow adding to the attendees collection.

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;
    }
  }
}

Add validation rules

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 /attendees/{userId} {
      allow read: if true;
      allow write: if request.auth.uid == userId
          && "attending" in request.resource.data;

    }
  }
}

(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 file, add the following code to listen to the RSVP status and count YES clicks.
// ...
// Listen for attendee list
firebase.firestore()
.collection('attendees')
.where("attending", "==", true)
.onSnapshot(snap => {
 const newAttendeeCount = snap.docs.length;

 numberAttending.innerHTML = newAttendeeCount+' people going'; 
})
  1. Finally, let's highlight the button corresponding to the current status. Check whether the current Authentication UID has an entry in the attendees collection, and then set the class to clicked.
// ...
// Listen for attendee list
function subscribeCurrentRSVP(user){
 rsvpListener = firebase.firestore()
 .collection('attendees')
 .doc(user.uid)
 .onSnapshot((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";
     }
   }
 });
}
  1. 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="";
}
  1. Call the functions from the Authentication listener.
// ...

// Listen to the current Auth state
firebase.auth().onAuthStateChanged((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 guestbook collection
  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();

}
});
  1. Try logging in as multiple users and see the count increase with each additional YES button click.

App preview

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

What we've covered

Next steps

Learn more

How did it go?

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