In this codelab, you'll learn how to use Firebase to easily create web applications by implementing and deploying a chat client using Firebase products and services.

What you'll learn:

What you'll need:

Clone the codelab's GitHub repository from the command line:

git clone https://github.com/firebase/friendlychat-web

Alternatively, if you do not have git installed, you can download the repo as a zip file.

Import the starter app

Using your IDE, open or import the πŸ“ web-start directory from the cloned repository. This πŸ“ web-start directory contains the starting code for the codelab which will be a fully functional chat web app.

Create a Firebase project

  1. Sign into Firebase.
  1. In the Firebase console, click Add Project, then name your Firebase project FriendlyChat.

Remember the Project ID for your Firebase project.

  1. Click Create Project.

The application that we're going to build uses Firebase products that are available for web apps:

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

Add a Firebase Web App to the project

  1. Click the web icon to create a new Firebase web app.
  2. Register the app with the nickname Friendly Chat, then check the box next to 'Also set up Firebase Hosting for this app'. Click Register app.
  3. Click through the remaining steps. You don't need to follow the instructions now; these will be covered in later steps of this codelab.

Enable Google sign-in for Firebase Auth

To allow users to sign into the web app with their Google accounts, we'll use the Google sign-in method.

You'll need to enable Google 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 Google Sign-in Provider, then click Save.
  4. Set the public-facing name of your app to Friendly Chat and choose a Project support email from the dropdown menu.

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.

  1. Select the Start in test mode option, then click Enable after reading the disclaimer about the security rules.

Test mode ensures that we can freely write to the database during development. We'll make our database more secure later on in this codelab.

Enable Cloud Storage

The web app uses Cloud Storage for Firebase to store, upload, and share pictures.

You'll need to enable Cloud Storage:

  1. In the Firebase console's Develop section, click Storage.
  2. Click Get Started.
  3. Read the disclaimer about security rules for your Firebase project, then click Got it.

With the default security rules, any authenticated user can write anything to Cloud Storage. We'll make our storage more secure later on in this codelab.

The Firebase command line interface (CLI) allows you to use Firebase Hosting to serve your web app locally as well as to deploy your web app to your Firebase project.

  1. Install the CLI by running the following npm command:
npm -g install firebase-tools
  1. Verify that the CLI has been installed correctly by running the following command:
firebase --version

Make sure the version of the Firebase CLI is v4.1.0 or later.

  1. Authorize the Firebase CLI by running the following command:
firebase login

We've set up the web app template to pull your app's configuration for Firebase Hosting from your app's local directory (the repository that you cloned earlier in the codelab). But to pull the configuration, we need to associate your app with your Firebase project.

  1. Make sure that your command line is accessing your app's local web-start directory.
  1. Associate your app with your Firebase project by running the following command:
firebase use --add
  1. When prompted, select your Project ID, then give your Firebase project an alias.

An alias is useful if you have multiple environments (production, staging, etc). However, for this codelab, let's just use the alias of default.

  1. Follow the remaining instructions in your command line.

Now that you have imported and configured your project, you are ready to run the web app for the first time.

  1. In a console from the web-start directory, run the following Firebase CLI command:
firebase serve --only hosting
  1. Your command line should display the following response:
βœ”  hosting: Local server: http://localhost:5000

We're using the Firebase Hosting emulator to serve our app locally. The web app should now be available from http://localhost:5000. All the files that are located under the public subdirectory are served.

  1. Using your browser, open your app at http://localhost:5000.

You should see your FriendlyChat app's not (yet!) functioning UI:

The app cannot do anything right now, but with your help it will soon! We've only laid out the UI for you so far.

Let's now build a real time chat!

Import the Firebase SDK

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

Since we're using Firebase Hosting to serve our app, we're going to import the local URLs that are in the file index.html (located in your web-start/public/ directory). For this codelab, we've already added the following lines for you at the bottom of the index.html file, but you can double check that they are there.

index.html

<script src="/__/firebase/6.0.4/firebase-app.js"></script>
<script src="/__/firebase/6.0.4/firebase-auth.js"></script>
<script src="/__/firebase/6.0.4/firebase-storage.js"></script>
<script src="/__/firebase/6.0.4/firebase-messaging.js"></script>
<script src="/__/firebase/6.0.4/firebase-firestore.js"></script>
<script src="/__/firebase/6.0.4/firebase-performance.js"></script>

During this codelab, we're going to use Firebase Auth, Cloud Firestore, Cloud Storage, Cloud Messaging, and Performance Monitoring, so we're importing all of their libraries. In your future apps, make sure that you're only importing the parts of Firebase that you need in order to shorten the load time of your app.

Configure Firebase

We also need to configure the Firebase SDK to tell it which Firebase project that we're using. Since we're using Firebase Hosting, you can import a special script that will do this configuration for you. Again, for this codelab, we've already added the following line for you at the bottom of the public/index.html file, but double check that it is there.

index.html

<script src="/__/firebase/init.js"></script>

This script contains your Firebase project configuration based upon the Firebase project that you specified earlier when you ran firebase use --add.

Feel free to inspect the file init.js to see what your project configuration looks like. To do this, open http://localhost:5000/__/firebase/init.js in your browser. You should see something that looks like the following:

/__/firebase/init.js

if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
firebase.initializeApp({
  "apiKey": "qwertyuiop_asdfghjklzxcvbnm1234568_90",
  "databaseURL": "https://friendlychat-1234.firebaseio.com",
  "storageBucket": "friendlychat-1234.appspot.com",
  "authDomain": "friendlychat-1234.firebaseapp.com",
  "messagingSenderId": "1234567890",
  "projectId": "friendlychat-1234",
  "appId": "1:1234567890:web:123456abcdef"
});

The Firebase SDK should now be ready to use since it's imported and initialized in index.html. We're now going to implement user sign-in using Firebase Auth.

Authenticate your users with Google Sign-In

In the app, when a user clicks the Sign in with Google button, the signIn function is triggered (we already set that up for you!). For this codelab, we want to authorize Firebase to use Google as the Identity Provider. We'll use a popup, but several other methods are available from Firebase.

  1. In the web-start directory, in the subdirectory public/scripts/, open main.js.
  2. Find the function signIn.
  3. Replace the entire function with the following code.

main.js

// Signs-in Friendly Chat.
function signIn() {
  // Sign into Firebase using popup auth & Google as the identity provider.
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
}

The signOut function is triggered when the user clicks the Sign out button.

  1. Go back to the file public/scripts/main.js.
  2. Find the function signOut.
  3. Replace the entire function with the following code.

main.js

// Signs-out of Friendly Chat.
function signOut() {
  // Sign out of Firebase.
  firebase.auth().signOut();
}

Track the auth state

To update our UI accordingly, we need a way to check if the user is signed-in or signed-out. With Firebase Auth, you can register an observer on the authentication state which will be triggered each time the auth state changes.

  1. Go back to the file public/scripts/main.js.
  2. Find the function initFirebaseAuth.
  3. Replace the entire function with the following code.

main.js

// Initiate Firebase Auth.
function initFirebaseAuth() {
  // Listen to auth state changes.
  firebase.auth().onAuthStateChanged(authStateObserver);
}

The code above registers the function authStateObserver as the auth state observer. It will trigger each time the auth state changes, that is, when the user signs-in or signs-out. It's at this point that we'll update the UI to display or hide the sign-in button, the sign-out button, the signed-in user's profile picture, etc. -- all these UI parts have already been implemented.

Display the information of the signed-in user

We want to display the signed-in user's profile pic and user name in the top bar of our app. In Firebase, the signed-in user's data is always available in the firebase.auth().currentUser object. Earlier, we set up the authStateObserver function to trigger when the user signs-in so that our UI updates accordingly. It will call getProfilePicUrl and getUserName when triggered.

  1. Go back to the file public/scripts/main.js.
  2. Find the functions getProfilePicUrl and getUserName.
  3. Replace both functions with the following code.

main.js

// Returns the signed-in user's profile pic URL.
function getProfilePicUrl() {
  return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';
}

// Returns the signed-in user's display name.
function getUserName() {
  return firebase.auth().currentUser.displayName;
}

We display an error message if the user tries to send messages when the user isn't signed-in (you can try it, though!). So, we need to detect if the user is actually signed-in.

  1. Go back to the file public/scripts/main.js.
  2. Find the function isUserSignedIn.
  3. Replace the entire function with the following code.

main.js

// Returns true if a user is signed-in.
function isUserSignedIn() {
  return !!firebase.auth().currentUser;
}

Test signing-in to the app

  1. If your app is still being served, refresh your app in the browser. Otherwise, run firebase serve on the command line to start serving the app from http://localhost:5000, then open it in your browser.
  2. Sign into the app using the sign-in button and your Google account. If you see an error message stating auth/operation-not-allowed, check to make sure that you enabled Google Sign-in as an auth provider in the Firebase console
  3. After signing-in, your profile pic and user name should display:

In this section, we'll write some data to Cloud Firestore so that we can populate the app's UI. This can be done manually via the Firebase console, but we'll do it in the app itself to demonstrate a basic Cloud Firestore write.

Data Model

Firestore data is split into collections, documents, fields, and subcollections. We will store each messages of the chat as a document in a top-level collection called messages.

Add messages to Firestore

To store the chat messages that are written by users, we'll use Cloud Firestore.

In this section, you'll add the functionality for users to write new messages to Cloud Firestore. A user clicking the SEND button will trigger the code snippet below. It adds a message object with the contents of the message fields to your Firestore instance in the messages collection. The add() method adds a new document with an automatically generated ID to the collection.

  1. Go back to the file public/scripts/main.js.
  2. Find the function saveMessage.
  3. Replace the entire function with the following code.

main.js

// Saves a new message on the Cloud Firestore.
function saveMessage(messageText) {
  // Add a new message entry to the Firebase database.
  return firebase.firestore().collection('messages').add({
    name: getUserName(),
    text: messageText,
    profilePicUrl: getProfilePicUrl(),
    timestamp: firebase.firestore.FieldValue.serverTimestamp()
  }).catch(function(error) {
    console.error('Error writing new message to Firebase Database', error);
  });
}

Test sending messages

  1. If your app is still being served, refresh your app in the browser. Otherwise, run firebase serve on the command line to start serving the app from http://localhost:5000, then open it in your browser.
  2. After signing-in, enter a message such as "Hey there!", then click SEND. This will write the message into Firestore. However, you won't yet see the data in your actual web app because we still need to implement retrieving the data (the next section of the codelab).
  3. You can see the newly added message in your Firebase Console. Open your Firebase Console. Under the Develop section click on Database (or click here and select your project) and you should see the messages collection with your newly added message:

Synchronize messages

To read messages on 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. In this code, we'll register the listener that listen for changes made to the data. We'll only display the last 12 messages of the chat to avoid displaying a very long history upon loading.

  1. Go back to the file public/scripts/main.js.
  2. Find the function loadMessages.
  3. Replace the entire function with the following code.

main.js

// Loads chat messages history and listens for upcoming ones.
function loadMessages() {
  // Create the query to load the last 12 messages and listen for new ones.
  var query = firebase.firestore()
                  .collection('messages')
                  .orderBy('timestamp', 'desc')
                  .limit(12);
  
  // Start listening to the query.
  query.onSnapshot(function(snapshot) {
    snapshot.docChanges().forEach(function(change) {
      if (change.type === 'removed') {
        deleteMessage(change.doc.id);
      } else {
        var message = change.doc.data();
        displayMessage(change.doc.id, message.timestamp, message.name,
                       message.text, message.profilePicUrl, message.imageUrl);
      }
    });
  });
}

To listen to messages in the database, we create a query on a collection by using the .collection function to specify in which collection is the data we want to listen to. In the code above, we're listening to the changes within the messages collection, which is where the chat messages are stored. We're also applying a limit by only listening to the last 12 messages using .limit(12) and ordering the messages by date using .orderBy('timestamp', 'desc') to get the 12 newest messages.

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

  1. If your app is still being served, refresh your app in the browser. Otherwise, run firebase serve on the command line to start serving the app from http://localhost:5000, then open it in your browser.
  2. The messages that you created earlier into the database should be displayed in the FriendlyChat UI (see below). Feel free to write new messages, they should appear instantly.
  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!

We'll now add a feature that shares images.

While the Cloud Firestore is good for storing structured data, Cloud Storage is better suited for storing files. Cloud Storage for Firebase is a file/blob storage service, and we'll use it to store any images that a user shares using our app.

Save images to Cloud Storage

For this codelab, we've already added for you a button that triggers a file picker dialog. After selecting a file, the saveImageMessage function is called, and you can get a reference to the selected file. The saveImageMessage function accomplishes the following:

  1. Creates a "placeholder" chat message into the chat feed, so that users see a "Loading" animation while we upload the image.
  2. Uploads the image file to Cloud Storage to the path: /<uid>/<messageId>/<file_name>
  3. Generates a publicly readable URL for the image file.
  4. Updates the chat message with the newly uploaded image file's URL in lieu of the temporary loading image.

Now you'll actually add this functionality:

  1. Go back to the file public/scripts/main.js.
  2. Find the function saveImageMessage.
  3. Replace the entire function with the following code.

main.js

// Saves a new message containing an image in Firebase.
// This first saves the image in Firebase storage.
function saveImageMessage(file) {
  // 1 - We add a message with a loading icon that will get updated with the shared image.
  firebase.firestore().collection('messages').add({
    name: getUserName(),
    imageUrl: LOADING_IMAGE_URL,
    profilePicUrl: getProfilePicUrl(),
    timestamp: firebase.firestore.FieldValue.serverTimestamp()
  }).then(function(messageRef) {
    // 2 - Upload the image to Cloud Storage.
    var filePath = firebase.auth().currentUser.uid + '/' + messageRef.id + '/' + file.name;
    return firebase.storage().ref(filePath).put(file).then(function(fileSnapshot) {
      // 3 - Generate a public URL for the file.
      return fileSnapshot.ref.getDownloadURL().then((url) => {
        // 4 - Update the chat message placeholder with the image's URL.
        return messageRef.update({
          imageUrl: url,
          storageUri: fileSnapshot.metadata.fullPath
        });
      });
    });
  }).catch(function(error) {
    console.error('There was an error uploading a file to Cloud Storage:', error);
  });
}

Test sending images

  1. If your app is still being served, refresh your app in the browser. Otherwise, run firebase serve --only hosting on the command line to start serving the app from http://localhost:5000, then open it in your browser.
  2. After signing-in, click the image upload button , then select an image file using the file picker. If you're looking for an image, feel free to use this nice pic of a coffee cup.
  3. A new message should display in the app's UI along with your selected image:

If you try adding an image while not signed-in, you should see a Toast telling you that you must sign-in to add images.

We'll now add support for browser notifications. The app will notify users when new messages are posted in the chat. Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages and notifications at no cost.

Whitelist the GCM Sender ID

In the web app manifest, you need to specify the gcm_sender_id, which is a hard-coded value indicating that FCM is authorized to send messages to this app.

  1. From the web-start directory, in the public directory, open manifest.json.
  2. Add the browser sender ID value in the gcm_sender_id attribute exactly as shown below (do not change the value from what's shown below).

manifest.json

{
  "name": "Friendly Chat",
  "short_name": "Friendly Chat",
  "start_url": "/index.html",
  "display": "standalone",
  "orientation": "portrait",
  "gcm_sender_id": "103953800507"
}

Add the FCM service worker

The web app needs a Service Worker that will receive and display web notifications.

  1. From the web-start directory, in the public directory, create a new file named firebase-messaging-sw.js.
  2. Add the following content to that new file.

firebase-messaging-sw.js

importScripts('/__/firebase/6.0.4/firebase-app.js');
importScripts('/__/firebase/6.0.4/firebase-messaging.js');
importScripts('/__/firebase/init.js');

firebase.messaging();

The service worker simply needs to load and initialize the Firebase Cloud Messaging SDK, which will take care of displaying notifications.

Get FCM device tokens

When notifications have been enabled on a device or browser, you'll be given a device token. This device token is what we use to send a notification to a particular device or particular browser.

When the user signs-in, we call the saveMessagingDeviceToken function. That's where we'll get the FCM device token from the browser and save it to CloudFirestore.

  1. Go back to the file public/scripts/main.js.
  2. Find the function saveMessagingDeviceToken.
  3. Replace the entire function with the following code.

main.js

// Saves the messaging device token to the datastore.
function saveMessagingDeviceToken() {
  firebase.messaging().getToken().then(function(currentToken) {
    if (currentToken) {
      console.log('Got FCM device token:', currentToken);
      // Saving the Device Token to the datastore.
      firebase.firestore().collection('fcmTokens').doc(currentToken)
          .set({uid: firebase.auth().currentUser.uid});
    } else {
      // Need to request permissions to show notifications.
      requestNotificationsPermissions();
    }
  }).catch(function(error){
    console.error('Unable to get messaging token.', error);
  });
}

However, this code won't work initially. For your app to be able to retrieve the device token, the user needs to grant your app permission to show notifications (next step of the codelab).

Request permissions to show notifications

When the user has not yet granted your app permission to show notifications, you won't be given a device token. In this case, we call the firebase.messaging().requestPermission() method which will display a browser dialog asking for this permission (in supported browsers).

  1. Go back to the file public/scripts/main.js.
  2. Find the function requestNotificationsPermissions.
  3. Replace the entire function with the following code.

main.js

// Requests permission to show notifications.
function requestNotificationsPermissions() {
  console.log('Requesting notifications permission...');
  firebase.messaging().requestPermission().then(function() {
    // Notification permission granted.
    saveMessagingDeviceToken();
  }).catch(function(error) {
    console.error('Unable to get permission to notify.', error);
  });
}

Get your device token

  1. If your app is still being served, refresh your app in the browser. Otherwise, run firebase serve on the command line to start serving the app from http://localhost:5000, then open it in your browser.
  2. After signing-in, the notifications permission dialog should be displayed:
  3. Click Allow.
  4. Open the JavaScript console of your browser. You should see the following message:
    Got FCM device token: cWL6w:APA91bHP...4jDPL_A-wPP06GJp1OuekTaTZI5K2Tu
  5. Copy your device token. You'll need it for the next stage of the codelab.

Send a notification to your device

Now that you have your device token, you can send a notification.

  1. In addition to the device token, you'll also need your Firebase app's Server Key. To obtain this key, go to Firebase Console > Project Settings > Cloud Messaging, then copy the Server Key.

To send a notification, you'll need to send the following HTTP request:

POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=YOUR_SERVER_KEY

{
  "notification": {
    "title": "New chat message!",
    "body": "There is a new message in FriendlyChat",
    "icon": "/images/profile_placeholder.png",
    "click_action": "http://localhost:5000"
  },
  "to":"YOUR_DEVICE_TOKEN"
}
  1. In the command line, run the following cURL command.
curl -H "Content-Type: application/json" \
     -H "Authorization: key=YOUR_SERVER_KEY" \
     -d '{
           "notification": {
             "title": "New chat message!",
             "body": "There is a new message in FriendlyChat",
             "icon": "/images/profile_placeholder.png",
             "click_action": "http://localhost:5000"
           },
           "to": "YOUR_DEVICE_TOKEN"
         }' \
     https://fcm.googleapis.com/fcm/send

Note that the notification will only appear if the FriendlyChat app is in the background. You must navigate away or display another tab for the notification to be displayed. When the app is in the foreground, there is a way to catch the messages sent by FCM.

If your app is in the background, a notification should appear in your browser, for example:

View database security rules

Cloud Firestore uses a specific rules language to define access rights, security, and data validations.

When setting up the Firebase project at the beginning of this codelab, we chose to use "Test mode" default security rules so that we didn't restrict access to the datastore. In the Firebase console, in the Database section's Rules tab, you can view and modify these rules.

Right now, you should see the default rules which do not restrict access to the datastore. This means any user can read and write to any collections in your datastore.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

We'll update the rules to restrict things a bit by using the following rules:

firestore.rules

service cloud.firestore {
  match /databases/{database}/documents {
    // Messages:
    //   - Anyone can read.
    //   - Authenticated users can add and edit messages.
    //   - Validation: Check name is same as auth token and text length below 300 char or that imageUrl is a URL.
    //   - Deletes are not allowed.
    match /messages/{messageId} {
      allow read;
      allow create, update: if request.auth != null
                    && request.resource.data.name == request.auth.token.name
                    && (request.resource.data.text is string
                      && request.resource.data.text.size() <= 300
                      || request.resource.data.imageUrl is string
                      && request.resource.data.imageUrl.matches('https?://.*'));
      allow delete: if false;
    }
    // FCM Tokens:
    //   - Anyone can write their token.
    //   - Reading list of tokens is not allowed.
    match /fcmTokens/{token} {
      allow read: if false;
      allow write;
    }
  }
}

Update database security rules

There are two ways to edit your database security rules, either in the Firebase console or from a local rules file deployed using the Firebase CLI.

To update security rules in the Firebase console:

  1. Go to the Database section from the left nav, then click the Rules tab.
  2. Replace the default rules that are already in the console with the rules shown above.
  3. Click Publish.

To update security rules from a local file:

  1. From the web-start directory, open firestore.rules.
  2. Replace the default rules that are already in the file with the rules shown above.
  3. From the web-start directory, open firebase.json.
  4. Add the firestore.rules attribute pointing to firestore.rules, as shown below. (The hosting attribute should already be in the file.)

firebase.json

{
  // Add this!
  "firestore": {
    "rules": "firestore.rules"
  },
  "hosting": {
    "public": "./public"
  }
}
  1. Deploy the security rules using the Firebase CLI by running the following command:
firebase deploy --only firestore
  1. Your command line should display the following response:
=== Deploying to 'friendlychat-1234'...

i  deploying firestore
i  firestore: checking firestore.rules for compilation errors...
βœ”  firestore: rules file firestore.rules compiled successfully
i  firestore: uploading rules firestore.rules...
βœ”  firestore: released rules firestore.rules to cloud.firestore

βœ”  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

View Cloud Storage security rules

Cloud Storage for Firebase uses a specific rules language to define access rights, security, and data validations.

When setting up the Firebase project at the beginning of this codelab, we chose to use the default Cloud Storage security rule that only allows authenticated users to use Cloud Storage. In the Firebase console, in the Storage section's Rules tab, you can view and modify rules. You should see the default rule which allows any signed-in user to read and write any files in your Storage bucket.

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

We'll update the rules to:

This can be implemented using the following rules:

storage.rules

// Returns true if the uploaded file is an image and its size is below the given number of MB.
function isImageBelowMaxSize(maxSizeMB) {
  return request.resource.size < maxSizeMB * 1024 * 1024
      && request.resource.contentType.matches('image/.*');
}

service firebase.storage {
  match /b/{bucket}/o {
    match /{userId}/{messageId}/{fileName} {
      allow write: if request.auth != null && request.auth.uid == userId && isImageBelowMaxSize(5);
      allow read;
    }
  }
}

Update Cloud Storage security rules

There are two ways to edit your storage security rules, either in the Firebase console or from a local rules file deployed using the Firebase CLI.

To update security rules in the Firebase console:

  1. Go to the Storage section from the left nav, then click the Rules tab.
  2. Replace the default rule that is already in the console with the rules shown above.
  3. Click Publish.

To update security rules from a local file:

  1. From the web-start directory, open storage.rules.
  2. Replace the default rules that are already in the file with the rules shown above.
  3. From the web-start directory, open firebase.json.
  4. Add the storage.rules attribute pointing to the storage.rules file, as shown below. (The hosting and database attribute should already be in the file.)

firebase.json

{
  // If you went through the "Cloud Firestore Security Rules" step.
  "firestore": {
    "rules": "firestore.rules"
  },
  // Add this!
  "storage": {
    "rules": "storage.rules"
  },
  "hosting": {
    "public": "./public"
  }
}
  1. Deploy the security rules using the Firebase CLI by running the following command:
firebase deploy --only storage
  1. Your command line should display the following response:
=== Deploying to 'friendlychat-1234'...

i  deploying storage
i  storage: checking storage.rules for compilation errors...
βœ”  storage: rules file storage.rules compiled successfully
i  storage: uploading rules storage.rules...
βœ”  storage: released rules storage.rules to firebase.storage/friendlychat-1234.appspot.com

βœ”  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview

You can use the Performance Monitoring SDK to collect real-world performance data from your app, then review and analyze that data in the Firebase console. Performance Monitoring helps you to understand where and when the performance of your app can be improved so that you can use that information to fix performance issues.

There are various ways to integrate with the Firebase Performance Monitoring JavaScript SDK. In this codelab, we enabled Performance Monitoring from Hosting URLs. Refer to the documentation to see other methods of enabling the SDK.

Automatic Traces

Since we included firebase-performance.js and init.js in an earlier step of the codelab, Performance Monitoring will automatically collect page load and network request metrics for you when users visit your deployed site!

Visit the documentation to learn more about automatic page load traces.

Measure first input delay (optional)

First input delay is useful since the browser responding to a user interaction gives your users their first impressions about the responsiveness of your app.

First input delay starts when the user first interacts with an element on the page, like clicking a button or hyperlink. It stops immediately after the browser is able to respond to the input, meaning that the browser isn't busy loading or parsing your page's content.

If you'd like to measure first input delay, you'll need to include the following code directly.

  1. Open public/index.html.
  2. Uncomment the script tag on the following line.

index.html

<!-- TODO: Enable First Input Delay polyfill library. -->
<script type="text/javascript">!function(n,e){var t,o,i,c=[],f={passive:!0,capture:!0},r=new Date,a="pointerup",u="pointercancel";function p(n,c){t||(t=c,o=n,i=new Date,w(e),s())}function s(){o>=0&&o<i-r&&(c.forEach(function(n){n(o,t)}),c=[])}function l(t){if(t.cancelable){var o=(t.timeStamp>1e12?new Date:performance.now())-t.timeStamp;"pointerdown"==t.type?function(t,o){function i(){p(t,o),r()}function c(){r()}function r(){e(a,i,f),e(u,c,f)}n(a,i,f),n(u,c,f)}(o,t):p(o,t)}}function w(n){["click","mousedown","keydown","touchstart","pointerdown"].forEach(function(e){n(e,l,f)})}w(n),self.perfMetrics=self.perfMetrics||{},self.perfMetrics.onFirstInputDelay=function(n){c.push(n),s()}}(addEventListener,removeEventListener);</script>

To read more about the first input delay polyfill, take a look at the documentation.

View performance data

Since you haven't deployed your site yet (you'll deploy it in the next step), here's a screenshot showing the metrics about page load performance that you'll see in the Firebase console within 12 hours of users interacting with your deployed site:

When you integrate the Performance Monitoring SDK into your app, you don't need to write any other code before your app starts automatically monitoring several critical aspects of performance. For web apps, the SDK logs aspects like first contentful paint, ability for users to interact with your app, and more.

You can also set up custom traces, metrics, and attributes to measure specific aspects of your app. Visit the documentation to learn more about custom traces and metrics and custom attributes.

Firebase offers a hosting service to serve your assets/web app. You can deploy your files to Firebase Hosting using the Firebase CLI. Before deploying, you need to specify in your firebase.json file which local files should be deployed. For this codelab, we've already done this for you because this step was required to serve our files during this codelab. The hosting settings are specified under the hosting attribute:

firebase.json

{
  // If you went through the "Cloud Firestore Security Rules" step.
  "firestore": {
    "rules": "firestore.rules"
  },
  // If you went through the "Storage Security Rules" step.
  "storage": {
    "rules": "storage.rules"
  },
  "hosting": {
    "public": "./public"
  }
}

These settings tell the CLI that we want to deploy all files in the ./public directory ( "public": "./public" ).

  1. Make sure that your command line is accessing your app's local web-start directory.
  2. Deploy your files to your Firebase project by running the following command:
firebase deploy --except functions
  1. The console should display the following:
=== Deploying to 'friendlychat-1234'...

i  deploying firestore, storage, hosting
i  storage: checking storage.rules for compilation errors...
βœ”  storage: rules file storage.rules compiled successfully
i  firestore: checking firestore.rules for compilation errors...
βœ”  firestore: rules file firestore.rules compiled successfully
i  storage: uploading rules storage.rules...
i  firestore: uploading rules firestore.rules...
i  hosting[friendlychat-1234]: beginning deploy...
i  hosting[friendlychat-1234]: found 8 files in ./public
βœ”  hosting[friendlychat-1234]: file upload complete
βœ”  storage: released rules storage.rules to firebase.storage/friendlychat-1234.appspot.com
βœ”  firestore: released rules firestore.rules to cloud.firestore
i  hosting[friendlychat-1234]: finalizing version...
βœ”  hosting[friendlychat-1234]: version finalized
i  hosting[friendlychat-1234]: releasing new version...
βœ”  hosting[friendlychat-1234]: release complete

βœ”  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-1234/overview
Hosting URL: https://friendlychat-1234.firebaseapp.com
  1. Visit your web app that's now fully hosted using Firebase Hosting at two of your very own Firebase subdomains:

Alternatively, you can run firebase open hosting:site in the command line.

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 a real-time chat web application!

What we've covered:

Next steps:

Learn more: