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.
Clone the codelab's GitHub repository from the command line:
git clone https://github.com/firebase/codelab-friendlychat-web
Alternatively, if you do not have git installed, you can download the repository as a ZIP file.
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.
The application that we are going to build uses the whole set of Firebase products available on the web:
Some of these products need special configuration or need to be enabled using the Firebase console:
To allow users to sign in to the web app with their Google accounts, we'll use the Google sign-in method.
You'll need to enable Google sign-in:
The web app uses Cloud Firestore to save chat messages and receive new chat messages.
You'll need to enable Cloud Firestore:
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.
The web app uses Cloud Storage for Firebase to store, upload, and share pictures.
You'll need to enable Cloud Storage:
With the default security rules, any authenticated user can write anything to Cloud Storage. We'll make our storage more secure later 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.
npm -g install firebase-tools
firebase --version
Make sure that the version of the Firebase CLI is v4.1.0 or later.
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.
web-start
directory.firebase use --add
An alias is useful if you have multiple environments (production, staging, etc). However, for this codelab, let's just use the alias of default
.
Now that you have imported and configured your project, you are ready to run the web app for the first time.
web-start
directory, run the following Firebase CLI command:firebase serve --only hosting
✔ 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.
You should see your FriendlyChat app's UI, which is not (yet!) functioning:
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 realtime chat!
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.
<script src="/__/firebase/6.4.0/firebase-app.js"></script>
<script src="/__/firebase/6.4.0/firebase-auth.js"></script>
<script src="/__/firebase/6.4.0/firebase-storage.js"></script>
<script src="/__/firebase/6.4.0/firebase-messaging.js"></script>
<script src="/__/firebase/6.4.0/firebase-firestore.js"></script>
<script src="/__/firebase/6.4.0/firebase-performance.js"></script>
During this codelab, we're going to use Firebase Authentication, 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, to shorten the load time of your app.
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.
<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:
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 Authentication.
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.
web-start
directory, in the subdirectory public/scripts/
, open main.js
.signIn
.// 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.
public/scripts/main.js
.signOut
.// Signs-out of Friendly Chat.
function signOut() {
// Sign out of Firebase.
firebase.auth().signOut();
}
To update our UI accordingly, we need a way to check if the user is signed in or signed out. With Firebase Authentication, you can register an observer on the authentication state that will be triggered each time the authentication state changes.
public/scripts/main.js
.initFirebaseAuth
.// Initiate Firebase Auth.
function initFirebaseAuth() {
// Listen to auth state changes.
firebase.auth().onAuthStateChanged(authStateObserver);
}
The code above registers the function authStateObserver
as the authentication state observer. It will trigger each time the authentication state changes (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, and so on. All of these UI parts have already been implemented.
We want to display the signed-in user's profile picture 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.
public/scripts/main.js
.getProfilePicUrl
and getUserName
. // 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.
public/scripts/main.js
.isUserSignedIn
.// Returns true if a user is signed-in.
function isUserSignedIn() {
return !!firebase.auth().currentUser;
}
firebase serve --only hosting
on the command line to start serving the app from http://localhost:5000, and then open it in your browser.auth/operation-not-allowed
, check to make sure that you enabled Google Sign-in as an authentication provider in the Firebase consoleIn this section, we'll write some data to Cloud Firestore so that we can populate the app's UI. This can be done manually with the Firebase console, but we'll do it in the app itself to demonstrate a basic Cloud Firestore write.
Cloud Firestore data 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 messages
.
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 your database. 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 Cloud Firestore instance in the messages
collection. The add()
method adds a new document with an automatically generated ID to the collection.
public/scripts/main.js
.saveMessage
.// Saves a new message to your Cloud Firestore database.
function saveMessage(messageText) {
// Add a new message entry to the 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 database', error);
});
}
firebase serve --only hosting
on the command line to start serving the app from http://localhost:5000, and then open it in your browser.To read 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. In this code, we'll register the listener that listens 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.
public/scripts/main.js
.loadMessages
.// 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 which collection the data that we want to listen to is in. 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, modified, or added. You can read more about this in the Cloud Firestore documentation.
firebase serve --only hosting
on the command line to start serving the app from http://localhost:5000, and then open it in your browser.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.
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:
/<uid>/<messageId>/<file_name>
Now you'll add the functionality to sned an image:
public/scripts/main.js
.saveImageMessage
.// 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);
});
}
firebase serve --only hosting
on the command line to start serving the app from http://localhost:5000, and then open it in your browser.If you try adding an image while not signed in, you should see a Toast notification 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.
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.
web-start
directory, in the public
directory, open manifest.json
.gcm_sender_id
attribute exactly as shown below. Do not change the value from what's shown below.{
"name": "Friendly Chat",
"short_name": "Friendly Chat",
"start_url": "/index.html",
"display": "standalone",
"orientation": "portrait",
"gcm_sender_id": "103953800507"
}
The web app needs a service worker that will receive and display web notifications.
web-start
directory, in the public
directory, create a new file named 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.
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 Cloud Firestore.
public/scripts/main.js
.saveMessagingDeviceToken
.// 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).
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).
public/scripts/main.js
.requestNotificationsPermissions
.// 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);
});
}
firebase serve --only hosting
on the command line to start serving the app from http://localhost:5000, and then open it in your browser.Got FCM device token: cWL6w:APA91bHP...4jDPL_A-wPP06GJp1OuekTaTZI5K2Tu
Now that you have your device token, you can send a notification.
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"
}
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, as in this example:
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 that 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 by using the following 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;
}
}
}
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:
To update security rules from a local file:
web-start
directory, open firestore.rules
.web-start
directory, open firebase.json
.firestore.rules
attribute pointing to firestore.rules
, as shown below. (The hosting
attribute should already be in the file.){
// Add this!
"firestore": {
"rules": "firestore.rules"
},
"hosting": {
"public": "./public"
}
}
firebase deploy --only firestore
=== 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
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 do the following:
This can be implemented using the following 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;
}
}
}
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:
To update security rules from a local file:
web-start
directory, open storage.rules
.web-start
directory, open firebase.json
.storage.rules
attribute pointing to the storage.rules
file, as shown below. (The hosting
and database
attribute should already be in the file.){
// If you went through the "Cloud Firestore Security Rules" step.
"firestore": {
"rules": "firestore.rules"
},
// Add this!
"storage": {
"rules": "storage.rules"
},
"hosting": {
"public": "./public"
}
}
firebase deploy --only storage
=== 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 and 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.
Since we included firebase-performance.js
and init.js
in an earlier step of the codelab, we just need to add one line to tell Performance Monitoring to automatically collect page load and network request metrics for you when users visit your deployed site!
public/scripts/main.js
, add the following line below the existing TODO
to initialize Performance Monitoring.// TODO: Initialize Firebase Performance Monitoring.
firebase.performance();
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.
public/index.html
.script
tag on the following line.<!-- 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.
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 and web apps. 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:
{
// 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"
).
web-start
directory.firebase deploy --except functions
=== 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
https://<firebase-projectId>.firebaseapp.com
https://<firebase-projectId>.web.app
.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!