In this codelab, you'll learn some of the basics of Firebase to easily create interactive web applications. We'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, we'll be building and deploying our app using Stackblitz, an online editor that's integrated several Firebase workflows. It 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 cannot edit your project.

  1. Go to the following URL for the starting code: https://stackblitz.com/edit/wtm-start.
  2. In the top left, 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 your files and changes are saved in this Stackblitz project.

For this codelab, we've already provided some structure for the web app. For the HTML, we've added some stylesheets and created a couple HTML containers for the app. Later in this codelab, we'll hook up these containers to Firebase.

To get started, let's get a bit more familiar with the Stackblitz interface. Let's try editing some of the existing event details:

  1. In Stackblitz, open your index.html file.
  2. Locate the event-details-container, then try out editing some event details.

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

index.html

<!-- ... -->

<div id="app">
  <section id="event-details-container">
    <h1>Women Techmakers Workshop</h1>
    <p>Join Kiana and Rachel for our workshop at the WTM Summit!</p>
    <h3>When</h3>
    <p>June 30</p>
    <h3>Where</h3>
    <p>Warsaw</p>
  </section>

<!-- ... -->

Your preview should look something like this:

App preview

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

Create a Firebase project

  1. Sign into Firebase.

If you happen to already have a GitHub account, we recommend signing into Firebase with the same email account that you use for your GitHub account. This will allow you to use advanced features offered by Stackblitz.

  1. In the Firebase console, click Add Project, then name your Firebase project WTM19-Workshop.

Remember the Project ID for your Firebase project.

  1. Click Create Project.

The app that we'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 Auth

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

You'll need to enable Email/Password sign-in:

  1. In the Firebase console, locate the Develop section in the left nav.
  2. Click Authentication, then click the Sign-in method tab (or click here to go directly there).
  3. Enable the Email/Password Sign-in Provider, then click Save.

Firebase console

Enable Cloud Firestore

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

You'll need to enable Cloud Firestore:

  1. In the Firebase console's Develop section, click Database.
  2. Click Create database in the Cloud Firestore pane.

Firebase console

  1. Select the Start in test mode option. Read the disclaimer about the security rules. Test mode ensures that we can freely write to the database during development.

Firebase console

  1. Select the location for your database. Note that this location cannot be changed later.
  2. Click Done.

Firebase console

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

Add the Firebase libraries

We need to add the Firebase libraries into the app. There are multiple ways to do this (as described in our documentation). For instance, you can add the libraries from our CDN. Or you can install them locally using npm, then package them in your app if you're using Browserify.

Stackblitz provides automatic bundling, so we can add the Firebase libraries using import statements.

To build this app, we're going to use the Firebase Auth, FirebaseUI, and Cloud Firestore libraries. For this codelab, we've already added the following lines for you at the top of the index.js file, but you can double-check that they are there.

index.js

// 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. In the Firebase console, click the web icon at the top to create a new Firebase web app.
  2. Register the app with the nickname WTM19 Workshop App.
  3. For this codelab, don't check the box next to 'Also set up Firebase Hosting for this app' (we're going to use Stackblitz's preview pane for now).
  4. Click Register app.
  5. Copy the Firebase configuration object to your clipboard.
  6. Click through the remaining steps. You don't need to follow the instructions now; these will be covered in later steps of this codelab.

Firebase console

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

index.js

// ...

// 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 we've added Firebase to the app, we can set up an RSVP button that will register people using Firebase Auth.

Authenticate your users with Email Sign-In and FirebaseUI

We'll need an RSVP button that prompts the user to sign in with their email. We can do this by hooking up FirebaseUI to an RSVP button.

First, let's initialize FirebaseUI:

  1. In Stackblitz, go to your index.js file.
  2. You'll notice that we already provided the config (see all the options in the docs), which does two things:
  1. At the bottom of index.js, add the FirebaseUI initialization statement, like so:

index.js

// ...
// Initialize the FirebaseUI widget using Firebase
var ui = new firebaseui.auth.AuthUI(firebase.auth());

Next, let's add an RSVP button to our HTML:

  1. In Stackblitz, go to your index.html file.
  2. Add the HTML for an RSVP button as shown in the example below.

Be careful to use the same id as shown below because, for this codelab, we've already added hooks for this specific ID in the index.js file.

Note that in the index.html file, we have a container with the ID firebaseui-auth-container. This is the ID we'll pass to FirebaseUI to hold our login.

index.html

<!-- ... -->

<div id="app">
  <section id="event-details-container">
    <!-- ... -->
    <!-- Add the RSVP button here -->
    <button id="startRsvp">
      RSVP
    </button>
  </section>

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

<!-- ... -->

App preview

  1. Finally, we'll set up a listener on the RSVP button and call the FirebaseUI start function. This will tell FirebaseUI that we want to see the sign-in window.

index.js

// ...
// 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 into the app.
  1. Go to the Firebase console, then to the Authentication dashboard. In the Users tab, you should see the account info that you entered to sign into the app.

App preview

Firebase console

Add Auth state to the UI

Now let's make sure the UI reflects the fact that we're signed in.

  1. In Stackblitz, go to your index.js file.
  2. We'll use the Firebase Auth state listener callback, which gets notified whenever the user's sign-in status changes. If there is currently a user, we'll switch the RSVP button to a logout button.
  3. Add the following code at the bottom:

index.js

// ...
// Listen to the current Auth state
firebase.auth().onAuthStateChanged((user)=> {
  if (user) {
    startRsvpButton.innerText = "logout"
  }
  else {
    startRsvpButton.innerText = "RSVP"
  }
});
  1. Then, in our button listener, let's log out the current user instead.

index.js

// ...
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);
    }
});
  1. Now our button should show Logout, and switch to RSVP when we click it.

App preview

Knowing that our users are coming is great for us, but let's give our guests something else to do in our app. What if they could leave messages in a guestbook? They can share why they're excited to come or maybe what they'll bring along.

To store the chat messages that users write in the app, we'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. We 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. We need to first add the HTML for the UI elements (message field and send button), then we'll add the code that hooks up these elements to our database.

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

  1. In Stackblitz, go to your 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.

index.html

<!-- ... -->

  <section id="guestbook-container">
    <h2>Guestbook</h2>
      <form>
        <label>Leave a message: </label>
        <input type="text">
        <button type="submit">SEND</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 your 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 your index.js file.
  2. To the bottom of the file, add the following code:

index.js

// 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
  })
  input.value = "";  // clears message input field
  // Return false to avoid redirect.
  return false;
});

Show the guestbook only to signed-in users

We don't want just anybody to see our guests' chat. One thing we can do to secure our chat is to make sure that only signed-in users can view the guestbook. That said, for your own apps, you'll want to also secure your database with security rules.

  1. In Stackblitz, go to your index.js file.
  2. Edit your onAuthStateChanged listener to hide and show the guestbook.

index.js

// ...
// Listen to the current Auth state
firebase.auth().onAuthStateChanged((user)=> {
  if (user) {
    startRsvpButton.innerText = "logout"

   // Show guestbook to logged-in users
    guestbookContainer.style.display = "block"
  }
  else {
    startRsvpButton.innerText = "RSVP"

   // Hide guestbook for non-logged-in users
    guestbookContainer.style.display = "none"
  }
});

Test sending messages

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

This will write the message to your Cloud Firestore database. However, you won't yet see the message in your actual web app because we still need to implement retrieving the data (we'll do that next).

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

In the Firebase console's Develop section, click Database (or click here, then select your project). You should see the guestbook collection with your newly added message:

Firebase console

Synchronize messages

Lovely that our guests can write messages to our database, but they can't see them yet!

To display messages in the app, we'll need to add listeners that trigger when data changes and then create a UI element that shows new messages.

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

  1. In Stackblitz, go to your index.html file.
  2. Inside guestbook-container, add a section with the id logbook

index.html

<!-- ... -->

  <section id="guestbook-container">
    <h2>Guestbook</h2>
      <form><!-- ... --></form>
      <section id="logbook"></section>
  </section> 

<!-- ... -->

Next, we'll register the listener that listens for changes made to the data.

  1. In Stackblitz, go to your 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.

index.js

// ...

// Create query for messages
firebase.firestore().collection("guestbook")
.orderBy("timestamp","desc")
.onSnapshot((snaps) => {
  // Reset page
  logbook.innerHTML = "";
  // Loop through documents in database
  snaps.forEach((doc) => {
    // Create an HTML entry for each document and add it to the chat
    let entry = document.createElement("p");
    entry.textContent = doc.data().name + ": " + doc.data().text;
    logbook.appendChild(entry);
  });
});

To listen to messages in the database, we create a query on a specific collection by using the .collection function. In the code above, we're listening to the changes within the guestbook collection, which is where the chat messages are stored. We're also ordering the messages 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 will be triggered when there are any changes to documents that match the query. This could be if a message gets deleted, or modified, or added. You can read more about this in the Cloud Firestore documentation.

Test syncing messages

Cloud Firestore automatically and instantly syncs 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 reflect in the UI.

Congratulations, you are reading Cloud Firestore documents in your app!

App preview

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 CLI in your command line or terminal. But for this codelab, we're using Stackblitz, and they've integrated the Firebase CLI into the Stackblitz workspace!

We can use Stackblitz's Firebase integration to tell Stackblitz to which Firebase project we'd like to deploy assets:

  1. In the Stackblitz workspace, click the Firebase icon in the left-nav.

Stackblitz

  1. Click Sign in to Google.
  1. From the list of Firebase projects, select your wtm19-workshop project.

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

  1. In the Stackblitz workspace, click Deploy in the left-nav.

Yep, that's it, one step!

Stackblitz

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 deploys, the functionality to roll back to previous versions of your app, and the workflow to set up a custom domain.

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.