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. 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.

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. (Optional) Set the public-facing name of your app to Friendly Chat and choose a Project support email from the dropdown menu.

Enable the Realtime Database

The web app uses the Firebase Realtime Database to save chat messages and receive new chat messages.

You'll need to enable Realtime Database:

  1. In the Firebase console's Develop section, click Database.
  2. Click Create database in the Realtime Database 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 user 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/5.5.8/firebase-app.js"></script>
<script src="/__/firebase/5.5.8/firebase-auth.js"></script>
<script src="/__/firebase/5.5.8/firebase-database.js"></script>
<script src="/__/firebase/5.5.8/firebase-storage.js"></script>
<script src="/__/firebase/5.5.8/firebase-messaging.js"></script>

During this codelab, we're going to use Firebase Auth, the Realtime Database, Cloud Storage, and Cloud Messaging, 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"
});

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 your app's downloaded files, 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.
  3. After signing-in, your profile pic and user name should display:

Import messages

To store the chat messages that are written by users, we'll use the Firebase Realtime Database.

To demonstrate how to read from the database, we'll start by adding a few test messages to our Realtime Database.

  1. In your project's Firebase console, click Database in the left nav. On this page, you'll see the data that is currently stored in your database (right now, it should be empty!).
  2. From the overflow menu, select Import JSON.
  3. Browse to the initial_messages.json file at the root of the directory, select the file, then click Import. This file's data will replace any data currently in your database.

  1. After importing the JSON file, your database should contain the following elements:
friendlychat-12345/
    messages/
        -K2ib4H77rj0LYewF7dP/
            text: "Hello"
            name: "anonymous"
        -K2ib5JHRbbL0NrztUfO/
            text: "How are you"
            name: "anonymous"
        -K2ib62mjHh34CAUbide/
            text: "I am fine"
            name: "anonymous"

These are a few sample chat messages to get us started with reading from the database.

Synchronize messages

To synchronize 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 listeners 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 message history and listens for upcoming ones.
function loadMessages() {
  // Loads the last 12 messages and listens for new ones.
  var callback = function(snap) {
    var data = snap.val();
    displayMessage(snap.key, data.name, data.text, data.profilePicUrl, data.imageUrl);
  };

  firebase.database().ref('/messages/').limitToLast(12).on('child_added', callback);
  firebase.database().ref('/messages/').limitToLast(12).on('child_changed', callback);
}

To listen to messages in the database, we use the .ref function to specify the path for the data that we want to listen to. In the code above, we're listening to the changes within the /messages/ path, which is where the chat messages are stored. We're also applying a limit by only listening to the last 12 messages using .limitToLast(12).

The .on function has two parameters: (1) the event type that we want to listen to and (2) the callback function (callback). In this case, we trigger our callback function when a new message is added (using the child_added event type) or when an existing message is modified (using the child_changed event type). There are a few other events that you can listen for, such as when a child has been deleted or moved. You can read more about this in the Realtime Database 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. After signing-in, the sample messages that we imported earlier into the database should be displayed in the FriendlyChat UI (see below).
  3. (Optional) You can try manually modifying or adding new messages directly in the Database section of your project's Firebase console.

Congratulations, you are reading real-time database entries in your app!

Implement sending messages

In this section, you'll add the functionality for users to send messages. A user clicking the SEND button will trigger the code snippet below. It pushes a message object with the contents of the message field to your Realtime Database under the /messages/ path. The push() method adds an automatically generated key to the pushed object's path. These keys are sequential to ensure that the new messages are added to the end of the list.

  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 in the Realtime Database.
function saveMessage(messageText) {
  // Adds a new message entry to the Realtime Database.
  return firebase.database().ref('/messages/').push({
    name: getUserName(),
    text: messageText,
    profilePicUrl: getProfilePicUrl()
  }).catch(function(error) {
    console.error('Error writing new message to Realtime 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, then click SEND.
  3. The new message should be visible in the app's UI (as well as in your project's Firebase console) with your profile pic and user name:

We'll now add a feature that shares images.

While the Realtime Database 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 method first saves the image in Cloud Storage.
function saveImageMessage(file) {
  // 1 - Add a chat message placeholder (a loading icon) that will ultimately get updated with the shared image.
  firebase.database().ref('/messages/').push({
    name: getUserName(),
    imageUrl: LOADING_IMAGE_URL,
    profilePicUrl: getProfilePicUrl()
  }).then(function(messageRef) {
    // 2 - Upload the image to Cloud Storage.
    var filePath = firebase.auth().currentUser.uid + '/' + messageRef.key + '/' + file.name;
    return firebase.storage().ref(filePath).put(file).then(function(fileSnapshot) {
      // 3 - Generate a public URL for the image 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 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. In the public directory of your app's downloaded files, 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. In the public directory of your app's downloaded files, create a new file named firebase-messaging-sw.js.
  2. Add the following content to that new file.

firebase-messaging-sw.js

importScripts('/__/firebase/5.5.7/firebase-app.js');
importScripts('/__/firebase/5.5.7/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 the Realtime Database.

  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 Realtime Database.
function saveMessagingDeviceToken() {
  firebase.messaging().getToken().then(function(currentToken) {
    if (currentToken) {
      console.log('Got FCM device token:', currentToken);
      // Save the device token to the Realtime Database.
      firebase.database().ref('/fcmTokens').child(currentToken)
          .set(firebase.auth().currentUser.uid);
    } else {
      // Need to request permissions to show notifications.
      requestNotificationsPermissions();
    }
  }).catch(function(error){
    console.error('Unable to get messaging device 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

The Firebase Realtime Database 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 default security rules so that we didn't restrict access to the database. 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 database. This means any user can read and write to any path in your database.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

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

database-rules.json

{
  "rules": {
    "messages": {
      ".read": true,
      // Users can only write messages if they are authenticated.
      ".write": "auth !== null",
      "$messageId": {
        // The name has to be the real display name.
        ".validate": "newData.child('name').val() === auth.token.name",
        "text": {
          // The text has to be less than 300 char.
          ".validate": "newData.isString() && newData.val().length < 300"
        }
      }
    },
    "fcmTokens": {
      // User can write their tokens to the database but not read the list of tokens.
      ".read": false,
      ".write": true
    }
  }
}

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 your downloaded files, open database-rules.json.
  2. Replace the default rules that are already in the file with the rules shown above.
  3. From your downloaded files, open firebase.json.
  4. Add the database.rules attribute pointing to the database-rules.json, as shown below. (The hosting attribute should already be in the file.)

firebase.json

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

i  deploying database
i  database: checking rules syntax...
βœ”  database: rules syntax for database friendlychat-1234 is valid
i  database: releasing rules...
βœ”  database: rules for database friendlychat-1234 released successfully

βœ”  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 your downloaded files, open storage.rules.
  2. Replace the default rules that are already in the file with the rules shown above.
  3. From your downloaded files, 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 "Realtime Database Security Rules" step.
  "database": {
    "rules": "database-rules.json"
  },
  // Add this!
  "storage": {
    "rules": "storage.rules"
  },
  "hosting": {
    "public": "./",
    "ignore": [
      "firebase.json",
      "database-rules.json",
      "storage.rules",
      "functions"
    ]
  }
}
  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

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 "Realtime Database Security Rules" step.
  "database": {
    "rules": "database-rules.json"
  },
  // If you went through the "Storage Security Rules" step.
  "storage": {
    "rules": "storage.rules"
  },
  "hosting": {
    "public": "./",
    "ignore": [
      "firebase.json",
      "database-rules.json",
      "storage.rules",
      "functions"
    ]
  }
}

These settings tell the CLI that we want to deploy all files in the current directory ( "public": "./" ) with the exception of the files listed in the ignore array.

  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 database, storage, hosting
i  database: checking rules syntax...
βœ”  database: rules syntax for database friendlychat-1234 is valid
i  storage: checking storage.rules for compilation errors...
βœ”  storage: rules file storage.rules compiled successfully
i  storage: uploading rules storage.rules...
i  hosting: preparing ./ directory for upload...
βœ”  hosting: 14 files uploaded successfully
i  database: releasing rules...
βœ”  database: rules for database friendlychat-1234 released successfully
βœ”  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
Hosting URL: https://friendlychat-12345.firebaseapp.com
  1. Visit your web app that's now fully hosted using Firebase Hosting at your very own Firebase subdomain: https://<firebase-project-id>.firebaseapp.com. Alternatively, you can run firebase open hosting:site in the command line.

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: