ESP8266 NodeMCU with Firebase – Creating a Web App

This guide will teach you how to create a simple Firebase Web App to control and monitor your ESP8266 NodeMCU board. The Web App you’ll create can be accessed worldwide to control and monitor your ESP8266 from anywhere in the world. This Web App makes the bridge between the Firebase Realtime Database and the ESP8266.

ESP8266 NodeMCU with Firebase Creating a Web App Arduino IDE

Complete the following tutorial before proceeding:

Here are the major steps to complete this tutorial.

  1. Creating Firebase Project—we recommend using the Firebase project from this previous tutorial.
  2. Installing Required Software
  3. Setting Up a Firebase Web App Project (VS Code)
  4. Creating Firebase Web App

We have a similar tutorial for the ESP32 board: ESP32 with Firebase – Creating a Web App

Installing Required Software

To follow this project, you need to install the following software:

  1. Visual Studio Code
  2. Node.JS LTS version
  3. Install Node.js Extension Pack (VS Code)
  4. Install Firebase Tools

Installing VS Code

Follow the next instructions to install VS Code on your Operating System:

A) Installing VS Code on Windows (Visual Studio Code)

Go to https://code.visualstudio.com/ and download the stable build for your operating system (Windows).

Microsoft Visual Studio Code VS Code Download Page for Windows PC

Click on the installation wizard to start the installation and follow all the steps to complete the installation. Accept the agreement and press the Next button.

Microsoft Visual Studio Code VS Code Installation wizard

Select the following options and click Next.

Microsoft Visual Studio Code VS Code Installation wizard step 2

Press the Install button.

Microsoft Visual Studio Code VS Code Installation wizard step 3

Finally, click Finish to finish the installation.

Microsoft Visual Studio Code VS Code Installation wizard final step

Open VS Code, and you’ll be greeted by a Welcome tab with the released notes of the newest version.

Microsoft Visual Studio Code VS Code Installation wizard welcome screen on a Windows PC

That’s it. Visual Studio Code was successfully installed.

B) Installing VS Code on Mac OS X (Visual Studio Code)

Go to https://code.visualstudio.com/ and download the stable build for your operating system (Mac OS X).

Microsoft Visual Studio Code VS Code Download Page for Mac OS X

After downloading the Visual Studio Code application file, you’ll be prompted with the following message. Press the “Open” button.

Microsoft Visual Studio Code VS Code Downloading application file for Mac OS X

Or open your Downloads folder and open Visual Studio Code.

Microsoft Visual Studio Code VS Code Downloading application file for Mac OS X

After that, you’ll be greeted by a Welcome tab with the released notes of the newest version.

Microsoft Visual Studio Code VS Code Installation wizard welcome screen on Max OS X

That’s it. Visual Studio Code was successfully installed.

C) Installing VS Code on Linux Ubuntu (Visual Studio Code)

Go to https://code.visualstudio.com/ and download the stable build for your operating system (Linux Ubuntu).

Microsoft Visual Studio Code VS Code Download Page for Linux Ubuntu

Save the installation file:

Microsoft Visual Studio Code VS Code Save installation file for Linux Ubuntu

To install it, open a Terminal window, navigate to your Downloads folder and run the following command to install VS Code.

$ cd Downloads
~/Downloads $ sudo apt install ./code_1.49.1-1600299189_amd64.deb

When the installation is finished, VS Code should be available in your applications menu.

Microsoft Visual Studio Code VS Code Open application Linux Ubuntu

Open VS Code, and you’ll be greeted by a Welcome tab with the released notes of the newest version.

Microsoft Visual Studio Code VS Code Installation wizard welcome screen on Linux Ubuntu

That’s it. Visual Studio Code was successfully installed.

Installing Node.js

1) Go to nodejs.org and download the LTS version.

Download Node.js LTS version

2) Run the executable file and follow the installation process.

3) Enable to automatically install all the necessary tools.

Download and Install Node.js LTS version

4) When it’s done, click Finish.

Install NodeJS Finish Installation

5) A Terminal window will open to install the Additional Tools for Node.js. When it’s done, click any key to continue. When it’s finished, you can close the Terminal Window.

Install NodeJS Install Necessary Tools Terminal Window.

Installing Node.js Extension Pack (VS Code)

1) Open VS Code.

2) Click on the extensions tab and search for “node.js extension pack“.

3) Click on the Install button at the window at the right.

Install Node.js extension pack VS Code

4) Restart VS Code.

Installing Firebase Tools (VS Code)

1) Open VS Code. Close all opened projects, if any.

2) Open a new Terminal window. Go to Terminal > New Terminal.

3) Run the following command to change to the C:\ path (you can install it in any other path):

cd \

4) Run the following command to install firebase tools globally:

npm -g install firebase-tools
Install Firebase Tools Globally

5) Firebase tools will be installed, and you’ll get a similar message on the Terminal window.

Install Firebase Tools 2

6) Test if firebase was successfully installed with the following command:

firebase --version

In my case, I get the following error.

Install Firebase Tools 3 Version

As you can see in the error message, there’s an error message related to the firebase.ps1 file on the C: \Users\username\AppData\Roaming\npm path.

Go to that path and delete the firebase.ps1 file.

Delete Firebase Error File

Go back to VS Code, and rerun the following command.

firebase --version

This time, it should return the Firebase Tools version without any error.

Install Firebase Tools 4 Version

Setting Up a Firebase Web App Project (VS Code)

Before creating the Firebase Web App, you need to set up a Firebase Project on VS Code. These are the steps:

  1. Creating a Project Folder
  2. Firebase Login
  3. Initializing Web App Firebase Project

1) Creating a Project Folder

1) Create a folder on your computer where you want to save your Firebase project—for example, Firebase-Project.

2) Open VS Code. Go to File > Open Folder… and select the folder you’ve just created.

3) Go to Terminal > New Terminal. A new Terminal window should open on your project path.

Install Firebase Tools 2

2) Firebase Login

4) On the previous Terminal window, type the following:

firebase login

5) You’ll be asked to collect CLI usage and error reporting information. Enter “n” and press Enter to deny.

Login Firebase VS Code Terminal Window

6) After this, it will pop up a new window on your browser to login into your firebase account.

Login Firebase Account

7) Allow Firebase CLI to access your google account.

Login Firebase Account allow Firebase CLI

8) After this, Firebase CLI login should be successful. You can close the browser window.

Login Firebase Account allow Firebase CLI Login Successful

3) Initializing Web App Firebase Project

9) After successfully login in, run the following command to start a Firebase project directory in the current folder.

firebase init

10) You’ll be asked if you want to initialize a Firebase project in the current directory. Enter Y and hit Enter.

Login Firebase Account allow Firebase CLI firebase init

11) Then, use up and down arrows and the Space key to select the options. Select the following options:

  • RealTime Database: Configure security rules file for Realtime Database and (optionally) provision default instance.
  • Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys

The selected options will show up with a green asterisk. Then, hit Enter.

Login Firebase Account allow Firebase CLI configure directory

12) Select the option “Use an existing project”—it should be highlighted in blue—then, hit Enter.

Firebase Project Setup VS Code

13) After that, select the Firebase project for this directory—it should be the project created in this previous tutorial. In my case, it is called esp-firebase-demo. Then hit Enter.

14) Press Enter on the following question to select the default database security rules file: “What file should be used for Realtime Database Security Rules?

15) Then, select the hosting options as shown below:

  • What do you want to use as your public directory? Hit Enter to select public.
  • Configure as a single-page app (rewrite urls to /index.html)? No
  • Set up automatic builds and deploys with GitHub? No
Firebase initialization complete

16) The Firebase project should now be initialized successfully. Notice that VS code created some essential files under your project folder.

Firebase Project Files Created successfully

The index.html file contains some HTML text to build a web page. For now, leave the default HTML text. The idea is to replace that with your own HTML text to build a custom web page for your needs. We’ll do that later in this tutorial.

17) To check if everything went as expected, run the following command on the VS Code Terminal window.

firebase deploy

You should get a success message saying “Deploy completed“.

Now, you need to get your web app URL to access it.

4) Add Firebase To Your App

Leave VS Code opened. Meanwhile, you need to go to your Firebase account to add Firebase to your app.

18) Go to your Firebase console and select your project. Then, click on the web icon to add a web app to firebase (or the +Add app button).

Add App to Firebase project

19) Give your app a name. I simply called it test. Then, check the box next to Also set up Firebase Hosting for this App. Click Register app.

Add Firebase Project to Your App

20) Then, copy the firebaseConfig object because you’ll need it later.

Firebase Config Object

Click Next on the proceeding steps.

After this, you can also access the firebaseConfig object if you go to your Project settings in your Firebase console.

21) Copy the authDomain. In my case, it is:

esp-firebase-demo.firebaseapp.com

This is the URL that allows you to access your web app.

Paste the domain into your browser. You should see the following web page. This web page is built with the files placed in the public folder of your firebase project.

You can access that web page from anywhere in the world.

Firebase Hosting complete

Congratulations, you’ve set up your Firebase App project correctly. Now, let’s change the files in the public folder to show your own web page instead of that one.


Creating Firebase Web App

Now that you’ve created a Firebase project app successfully on VS Code, follow the next steps to customize the app to display the values saved on the Realtime Database.

index.html

Copy the following to your index.html file. This HTML file creates a simple web page that displays the readings saved on the Realtime Database created on this previous project.

<!-- Complete Project Details at: https://RandomNerdTutorials.com/ -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP Firebase App</title>

    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>

    <!-- TODO: Add SDKs for Firebase products that you want to use
        https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="https://www.gstatic.com/firebasejs/8.8.1/firebase-database.js"></script>

    <script>
    // REPLACE WITH YOUR web app's Firebase configuration
    var firebaseConfig = {
        apiKey: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        authDomain: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        databaseURL: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        projectId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        storageBucket: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        messagingSenderId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
        appId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    var database = firebase.database();
</script>
<script src="app.js" defer></script>

</head>
<body>
    <h1>ESP32 Firebase Web App Example</h1>
    <p>Reading int: <span id="reading-int"></span></p>
    <p>Reading float: <span id="reading-float"></span></p>
</body>
</html>

View raw code

You need to modify the code with your own firebaseConfig object (from step 20).

Let’s take a quick look at the HTML file.

In the <head> of the HTML file, we must add all the required metadata.

The title of the web page is ESP Firebase App, but you can change it in the following line.

<title>ESP Firebase App</title>

You must add the following line to be able to use Firebase with your app.

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

You must also add any Firebase products you want to use. In this example, we’re using the Realtime Database.

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

Then, replace the firebaseConfig object with the one you’ve gotten from step 20.

var firebaseConfig = {
    apiKey: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    authDomain: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    databaseURL: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    projectId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    storageBucket: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    messagingSenderId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION",
    appId: "REPLACE_WITH_YOUR_Firebase_CONFIGURATION"
};

Finally, Firebase is initialized and we create a global variable called database that refers to our Firebase Realtime Database.

firebase.initializeApp(firebaseConfig);
var database = firebase.database();

We also reference the app.js file that we’ll create next to include JavaScript functions that will allow us to update the HTML page with the database values.

<script src="app.js" defer></script>

We’re done with the metadata. Now, let’s go to the HTML parts that are visible to the user—go between the <body> and </body> tags.

We create a heading with the following text: ESP Firebase Web App Example, but you can change it to whatever you want.

<h1>ESP Firebase Web App Example</h1>

Then, we add two paragraphs to display the float and int values saved on the database. We create <span> tags with specific ids, so that we can refer to those HTML elements using JavaScript and insert the database values.

<p>Reading int: <span id="reading-int"></span></p>
<p>Reading float: <span id="reading-float"></span></p>

After making the necessary changes, you can save the HTML file.

app.js

Inside the public folder, create a file called app.js. You can do this on VS Code by selecting the public folder and then, clicking on the +file icon. This JavaScript file is responsible for updating the values on the web page any time there’s a change on the database.

Copy the following to your app.js file.

// Complete Project Details at: https://RandomNerdTutorials.com/

// Database Paths
var dataFloatPath = 'test/float';
var dataIntPath = 'test/int';

// Get a database reference 
const databaseFloat = database.ref(dataFloatPath);
const databaseInt = database.ref(dataIntPath);

// Variables to save database current values
var floatReading;
var intReading;

// Attach an asynchronous callback to read the data
databaseFloat.on('value', (snapshot) => {
  floatReading = snapshot.val();
  console.log(floatReading);
  document.getElementById("reading-float").innerHTML = floatReading;
}, (errorObject) => {
  console.log('The read failed: ' + errorObject.name);
});

databaseInt.on('value', (snapshot) => {
  intReading = snapshot.val();
  console.log(intReading);
  document.getElementById("reading-int").innerHTML = intReading;
}, (errorObject) => {
  console.log('The read failed: ' + errorObject.name);
});

View raw code

The following snippet is responsible for listening to changes on the test/float database path.

databaseFloat.on('value', (snapshot) => {
  floatReading = snapshot.val();
  console.log(floatReading);
  document.getElementById("reading-float").innerHTML = floatReading;
}, (errorObject) => {
  console.log('The read failed: ' + errorObject.name);
});

Whenever you insert a new value on that database path, we update the value on the HTML element with the reading-float id.

document.getElementById("reading-float").innerHTML = floatReading;

We follow a similar procedure to update the readings on the test/int database path.

databaseInt.on('value', (snapshot) => {
  intReading = snapshot.val();
  console.log(intReading);
  document.getElementById("reading-int").innerHTML = intReading;
}, (errorObject) => {
  console.log('The read failed: ' + errorObject.name);
});

Save the JavaScript file.

Deploy your App

After saving the HTML and JavaScript files, deploy your app on VS Code by running the following command.

firebase deploy

ESP8266 Arduino Sketch

Upload the following code to your ESP8266. This is the same code used in this previous project to write to the database. This code simply writes to the database every 15 seconds.

Don’t forget to insert your network credentials, database URL, and Firebase Project API Key.

/*
  Rui Santos
  Complete project details at our blog.
    - ESP32: https://RandomNerdTutorials.com/esp32-firebase-realtime-database/
    - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Based in the RTDB Basic Example by Firebase-ESP-Client library by mobizt
  https://github.com/mobizt/Firebase-ESP-Client/blob/main/examples/RTDB/Basic/Basic.ino
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Insert Firebase project API Key
#define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL" 

//Define Firebase Data object
FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
int count = 0;
bool signupOK = false;

void setup(){
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  /* Assign the api key (required) */
  config.api_key = API_KEY;

  /* Assign the RTDB URL (required) */
  config.database_url = DATABASE_URL;

  /* Sign up */
  if (Firebase.signUp(&config, &auth, "", "")){
    Serial.println("ok");
    signupOK = true;
  }
  else{
    Serial.printf("%s\n", config.signer.signupError.message.c_str());
  }

  /* Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
  
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop(){
  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();
    // Write an Int number on the database path test/int
    if (Firebase.RTDB.setInt(&fbdo, "test/int", count)){
      Serial.println("PASSED");
      Serial.println("PATH: " + fbdo.dataPath());
      Serial.println("TYPE: " + fbdo.dataType());
    }
    else {
      Serial.println("FAILED");
      Serial.println("REASON: " + fbdo.errorReason());
    }
    count++;
    
    // Write an Float number on the database path test/float
    if (Firebase.RTDB.setFloat(&fbdo, "test/float", 0.01 + random(0,100))){
      Serial.println("PASSED");
      Serial.println("PATH: " + fbdo.dataPath());
      Serial.println("TYPE: " + fbdo.dataType());
    }
    else {
      Serial.println("FAILED");
      Serial.println("REASON: " + fbdo.errorReason());
    }
  }
}

View raw code

Demonstration

The ESP8266 should be sending new readings every 15 seconds to the database.

ESP32 ESP8266 Store value firebase database Serial Monitor Success

Go to your App URL. You’ll see the readings being updated every 15 seconds. The App updates the web page any time the ESP8266 writes a new value.

ESP8266 NodeMCU Store value firebase database Demonstration

In your Firebase Console, you can go to your project page, and check that new values are being written into the database every 15 seconds.

ESP8266 NodeMCU Store value firebase database Demonstration

Congratulations! You’ve created a Firebase Web App to interface with the ESP8266.

Wrapping Up

In this tutorial, you learned how to create a Firebase Web App to interface with the ESP8266. You’ve learned how to use Firebase Hosting services and the Realtime Database.

We’ve built a simple example to get you started with Firebase. It simply displays some random numbers on a web page. The idea is to replace those numbers with sensor readings or GPIO states. Additionally, you may also add buttons, or sliders to the web page to control the ESP8266 GPIOs. The possibilities are endless.

The example has some limitations but allows you to understand Firebase Web Apps potential for the ESP8266. For example, at this point, anyone can write and read data from your database because we haven’t set any database rules (it is in test mode). Additionally, we didn’t protect it with any kind of authentication. Nonetheless, we hope you find this tutorial useful. And if you want to learn more you can also check the Firebase documentation.

If there is enough interest in this subject, we may create more Firebase tutorials with the ESP8266. Let us know in the comments below if this is a subject that you are interested in.

We hope you find this tutorial useful.

Learn more about the ESP8266 with our resources:

Thanks for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.