Note: Although Node.js is a requirement for running and testing our app during development, the final application will not be dependent on Node.js.

Create a Firebase project

In the Firebase console, click Add project, then name the Firebase project FriendlyEats.

Remember the Project ID for your Firebase project.

Click Create project.

Important: Your Firebase project will be named FriendlyEats, but Firebase will automatically assign it a unique Project ID in the form friendlyeats-1234. This unique identifier is how your project is actually identified (including in the CLI), whereas FriendlyEats is simply a display name.

The application that we're going to build uses a few Firebase services available on the web:

Firebase Authentication to easily identify your users

Cloud Firestore to save structured data on the Cloud and get instant notification when the data is updated

Firebase Hosting to host and serve your static assets

For this specific codelab, we've already configured Firebase Hosting. However, for Firebase Auth and Cloud Firestore, we'll walk you through the configuration and enabling of the services using the Firebase console.

Enable Anonymous Auth

Although authentication isn't the focus of this codelab, it's important to have some form of authentication in our app. We'll use Anonymous login - meaning that the user will be silently signed in without being prompted.

The sample code should have been cloned into the 📁friendlyeats-web directory, make sure your command line are ran from this directory from now on:

cd friendlyeats-web

Import the starter app

Using your IDE (WebStorm, Atom, Sublime, Visual Studio Code...) open or import the 📁friendlyeats-web directory. This directory contains the starting code for the codelab which consists of a not-yet functional restaurant recommendation app. We'll make it functional throughout this codelab so you will need to edit code in that directory soon.

Verify that the CLI has been installed correctly by running the following command:

firebase --version

Make sure the version of the Firebase CLI is v7.4.0 or later.

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 and files. But to do this, we need to associate your app with your Firebase project.

Make sure that your command line is accessing your app's local directory.

Associate your app with your Firebase project by running the following command:

You should see your copy of FriendlyEats which has been connected to your Firebase project.

The app has automatically connected to your Firebase project and silently signed you in as an anonymous user.

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 restaurants as a document in a top-level collection called restaurants.

Later, we'll store each reviews in a subcollection called ratings in each restaurants.

Tip: To learn more about the Firestore data model, read about documents and collections in the documentation.

Add restaurants to Firestore

The main model object in our app is a restaurant. Let's write some code that adds a restaurant document to the restaurants collection.

The code above adds a new document to the restaurants collection. The document data comes from a plain JavaScript object. We do this by first getting a reference to a Cloud Firestore collection restaurants then add'ing the data.

Let's add restaurants!

Go back to your FriendlyEats app in your browser and refresh it.

Click Add Mock Data.

The app will automatically generate a random set of restaurants objects, then call your addRestaurant function. 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).

If you navigate to the Cloud Firestore tab in the Firebase console, though, you should now see new documents in the restaurants collection!

Congratulations, you have just written data to Cloud Firestore from a web app!

In the next section, you'll learn how to retrieve data from Cloud Firestore and display it in your app.

In this section, you'll learn how to retrieve data from Cloud Firestore and display it in your app. The two key steps are creating a query and adding a snapshot listener. This listener will be notified of all existing data that matches the query and will receive updates in real time.

First, let's construct the query that will serve the default, unfiltered list of restaurants.

In the code above, we construct a query which will retrieve up to 50 restaurants from the top-level collection named restaurants, which are ordered by the average rating (currently all zero). After we declared this query, we pass it to the getDocumentsInQuery() method which is responsible for loading and rendering the data.

In the code above, query.onSnapshot will trigger its callback every time there's a change to the result of the query.

The first time, the callback is triggered with the entire result set of the query -- meaning the whole restaurants collection from Cloud Firestore. It then passes all the individual documents to the renderer.display function.

When a document is deleted, change.type equals to removed. So in this case, we'll call a function that removes the restaurant from the UI.

Now that we've implemented both methods, refresh the app and verify that the restaurants we saw earlier in the Firebase console are now visible in the app. If you completed this section successfully, then your app is now reading and writing data with Cloud Firestore!

As your list of restaurants changes, this listener will keep updating automatically. Try going to the Firebase console and manually deleting a restaurant or changing its name - you'll see the changes show up on your site immediately!

Note: It's also possible to fetch documents from Cloud Firestore once, rather than listening for real time updates using the Query.get() method.

So far, we've shown how to use onSnapshot to retrieve updates in real time; however, that's not always what we want. Sometimes it makes more sense to only fetch the data once.

We'll want to implement a method that's triggered when a user clicks into a specific restaurant in your app.

After you've implemented this method, you'll be able to view pages for each restaurant. Just click on a restaurant in the list and you should see the restaurant's details page:

For now, you can't add ratings as we still need to implement adding ratings later on in the codelab.

Currently, our app displays a list of restaurants, but there's no way for the user to filter based on their needs. In this section, you'll use Cloud Firestore's advanced querying to enable filtering.

Here's an example of a simple query to fetch all Dim Sum restaurants:

var filteredQuery = query.where('category', '==', 'Dim Sum')

As its name implies, the where() method will make our query download only members of the collection whose fields meet the restrictions we set. In this case, it'll only download restaurants where category is Dim Sum.

In our app, the user can chain multiple filters to create specific queries, like "Pizza in San Francisco" or "Seafood in Los Angeles ordered by Popularity".

We'll create a method that builds up a query which will filter our restaurants based on multiple criteria selected by our users.

The code above adds multiple where filters and a single orderBy clause to build a compound query based on user input. Our query will now only return restaurants that match the user's requirements.

Refresh your FriendlyEats app in your browser, then verify that you can filter by price, city, and category. While testing, you'll see errors in the JavaScript Console of your browser that look like this:

The query requires an index. You can create it here: https://console.firebase.google.com/project/.../database/firestore/indexes?create_index=...

These errors are because Cloud Firestore requires indexes for most compound queries. Requiring indexes on queries keeps Cloud Firestore fast at scale.

Opening the link from the error message will automatically open the index creation UI in the Firebase console with the correct parameters filled in. In the next section, we'll write and deploy the indexes needed for this application.

If we don't want to explore every path in our app and follow each of the index creation links, we can easily deploy many indexes at once using the Firebase CLI.

In this section, we'll add the ability for users to submit reviews to restaurants. So far, all of our writes have been atomic and relatively simple. If any of them errored, we'd likely just prompt the user to retry them or our app would retry the write automatically.

Our app will have many users who want to add a rating for a restaurant, so we'll need to coordinate multiple reads and writes. First the review itself has to be submitted, then the restaurant's rating count and average rating need to be updated. If one of these fails but not the other, we're left in an inconsistent state where the data in one part of our database doesn't match the data in another.

Fortunately, Cloud Firestore provides transaction functionality that allows us to perform multiple reads and writes in a single atomic operation, ensuring that our data remains consistent.

In the block above, we trigger a transaction to update the numeric values of averageRating and ratingCount in the restaurant document. At the same time, we add the new rating to the ratings subcollection.

Note: Adding ratings is a good example for using a transaction for this particular codelab. However, in a production app you should perform the average rating calculation on a trusted server to avoid manipulation by users. A good way to do this is to write the rating document directly from the client, then use Cloud Functions to update the new restaurant average rating.

Warning: When a transaction fails on the server, the callback is also re-executed repeatedly. Never place logic that modifies app state inside the transaction callback.

At the beginning of this codelab, we set our app's security rules to completely open the database to any read or write. In a real application, we'd want to set much more fine-grained rules to prevent undesirable data access or modification.

These rules restrict access to ensure that clients only make safe changes. For example:

Updates to a restaurant document can only change the ratings, not the name or any other immutable data.

Ratings can only be created if the user ID matches the signed-in user, which prevents spoofing.

Alternatively to using the Firebase console, you can use the Firebase CLI to deploy rules to your Firebase project. The firestore.rules file in your working directory already contains the rules from above. To deploy these rules from your local filesystem (rather than using the Firebase console), you'd run the following command:

In this codelab, you learned how to perform basic and advanced reads and writes with Cloud Firestore, as well as how to secure data access with security rules. You can find the full solution in the quickstarts-js repository.