Start codelab

Codelab Flow

What you will learn

L Last updated on 18/07/18 F Firebase F Realtime Database

In this codelab, we're going to learn how to add firebase to your web app and serve web content from the Firebase Realtime database.

Get the souce code

We are going to configure this site to get its content served from firebase realtime database. If you have Github Desktop, simply Fork and clone it.

Unpack the downloaded zip file. This will unpack a root folder add-firebase, which contains two folders; work ; where we're going to work from and final ; the final code.

Create firebase-config.js

Create an empty javascript file called firebase-config.js in the work folder.

Create your firebase project project in the firebase console here. Click project overview and select firebase web platform by clicking the CODE icon.

Copy your project's firebase configuration code snippet as shown below and paste into the firebase-config.js file in the work folder. This code allows us to add Firebase to our web app.


  // Set the configuration for your app
  // TODO: Replace with your project's config object
  var config = {
  apiKey: "apiKey",
  authDomain: "projectId.firebaseapp.com",
  databaseURL: "https://databaseName.firebaseio.com",
  storageBucket: "bucket.appspot.com"
  };
  firebase.initializeApp(config);
  // Get a reference to the database service
  var database = firebase.database();

Now let's us add the code that will allow us to retrieve our web app content from Firebase Realtime database. Copy and add the code snippet below to the firebase-config.js file.

In this code, we are getting a reference to the row of our database called "app-content". We also create a javaScript object for the HTML element that has id="id_name" as shown in the example below;

a) Here is our html code for our web app header with an id "app_name"

<h2 id="app_name"></h2>

b) So we create a javaScript object for the HTML element that has id="app_name" as shown below in our firebase-config.js


// create a javaScript object for the HTML element that has id="app_name" 
document.getElementById('app_name').innerHTML = app_name;
Copy and add the code snippet now to our firebase-config.js file. Save. Read through the comments
   
    // get a reference to the row of our database called "app-content"
      var meetupRef = firebase.database().ref('app-content').orderByKey();
        meetupRef.once('value')
          .then(function(snapshot) {
            snapshot.forEach(function(childSnapshot) {
              var key = childSnapshot.key;
              // childData will be the actual contents of the child
              var childData = childSnapshot.val();
              // retrieve data (content) from firebase realtime database
              var app_name = childSnapshot.val().app_name;
              var app_desc = childSnapshot.val().app_desc;
              var btn_1 = childSnapshot.val().btn_1;
              var recent_work_title = childSnapshot.val().recent_work_title;
              var work_title_1 = childSnapshot.val().work_title_1;
              var work_desc_1 = childSnapshot.val().work_desc_1;
              var work_title_2 = childSnapshot.val().work_title_2;
              var work_desc_2 = childSnapshot.val().work_desc_2;
              var btn_2 = childSnapshot.val().btn_2;
              // create a javaScript object for the HTML element that has id="app_name" 
              document.getElementById('app_name').innerHTML = app_name;
              // create a javaScript object for the HTML element that has id="app_desc"
              document.getElementById('app_desc').innerHTML = app_desc;
              // create a javaScript object for the HTML element that has id="btn_1"
              document.getElementById('btn_1').innerHTML = btn_1;
              // create a javaScript object for the HTML element that has id="recent_work_title"
              document.getElementById('recent_work_title').innerHTML = recent_work_title;
              // create a javaScript object for the HTML element that has id="work_title_1"
              document.getElementById('work_title_1').innerHTML = work_title_1;
              // create a javaScript object for the HTML element that has id="work_desc_1"
              document.getElementById('work_desc_1').innerHTML = work_desc_1;
              // create a javaScript object for the HTML element that has id="work_title_2"
              document.getElementById('work_title_2').innerHTML = work_title_2;
              // create a javaScript object for the HTML element that has id="work_desc_2"
              document.getElementById('work_desc_2').innerHTML = work_desc_2;
              // create a javaScript object for the HTML element that has id="btn_2"
              document.getElementById('btn_2').innerHTML = btn_2;
      
              });
        });
    

Create app-content.json (web content)

Now we are going to create the web app content that will be stored in the Firebase Realtime database. Create a new folder and name it data. In this folder, create a new json file called app-content.json and copy the code snippet below to it.

This is the default Firebase data format built for this web app. We are going to use it as it is. After deploying oour web app with Firebase, you will play around with it by changing the app content.
Add web app data that will be served from the Firebase Realtime database.

{
  "app-content" : {
    "data" : {
        "app_name": "PWA Fire Firebase Codelab",
        "app_desc": "The content on this web app is served by Firebase Realtime database. It's so magical! All you need to do is update your realtime database with Firebase. No more redeployments over and over again. No more thoughts for Wordpress again.",
        "btn_1": "Learn More",
        "recent_work_title": "Your Recent Work",
        "work_title_1": "Add Your Work Title",
        "work_desc_1": "Maybe a little more description here? Add some!",
        "work_title_2": "Add Your Work Title",
        "work_desc_2": "Maybe a little more description here? Add some!",
        "btn_2": "Read More"
        }
      }
  }

Now let's create a new file called database.rules.json; copy the code snippet below. We are going to allow read-only rights from our realtime database.

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

Add firebase-config.js

Copy and paste the snippet below at the bottom of your HTML, before other script tags.


 <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase.js"></script>
 <script src="firebase-config.js"></script>

Firebase Hosting

1. Install the Firebase tools via npm (run this in your command line).The Firebase Command Line Interface (CLI) will allow you to serve the web app locally and deploy.

npm -g install firebase-tools

2. To verify that the CLI has been installed correctly, open a console and run:

firebase --version

3. If you haven't recently signed in to the Firebase tools, update your credentials:

firebase login

4. Make sure you are in the work folder then Initialize your app to use Firebase. Select your Project ID and follow the instructions.

When prompted, you can choose any Alias, such as add-firebase for instance. Select Firebase Hosting and database as the Firebase CLI feature. Provide the default directory as /.

Reply YES; Y if prompted to use database.rules.json as the default database rules. Do not replace. To the other prompts, reply NO; N

firebase init

5. Finally, deploy the app to Firebase:

firebase deploy

6. Celebrate. You're done! Your app will be deployed to the domain:

https://YOUR-FIREBASE-APP.firebaseapp.com

7. Visit your web app on your phone now. You should see "Blank" sections ! Don't worry! We have one final step to go! Further reading: Firebase Hosting Guide.

Create Firebase Realtime Database

Now let us upload our web app content to Firebase Realtime database. First step is to go to the Firebase console here and select your project.

Click database in the left menu and select Realtime Database as our database type. Select the default database rules.

An empty database is created taking your app's name. To ADD our web app content, click the THREE vertical dots and select Import JSON and select the app-content.json to import our app data! Refresh your web app and see magic!

Mr. PWA Fire's Son Dance Mr. PWA Fire's Son Dance

What's next?

You got any bug? report it here for support. You want to contribute? Create your feature here.

Support

Donate a Star and Contribute in any way. Be sure to follow us on Twitter.

License

Copyright PWA Fire, 2018. Licensed under an MIT License.

FORK ON GITHUB