ESP8266 NodeMCU: Getting Started with Firebase (Realtime Database)

Get started quickly with Firebase using the ESP8266 NodeMCU board. Firebase is Google’s mobile application development platform that includes many services to manage data from IOS, Android, or web applications. You’ll create a Firebase project with a realtime database (RTDB), and you’ll learn how to store and read values from the database with your ESP8266 board.

ESP8266 NodeMCU: Getting Started with Firebase (Realtime Database)

Updated 21 April 2025

In a later tutorial, you’ll learn how to create a Firebase web app that you can access from anywhere to monitor and control your ESP8266 using firebase’s realtime database.

We have a similar tutorial for the ESP32 board: Getting Started with Firebase (Realtime Database)

What is Firebase?

Firebase Logo

Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. It has many services used to manage data from any android, IOS, or web application.

The following paragraph clearly explains the advantages of using Firebase:

Firebase is a toolset to “build, improve, and grow your app”, and the tools it gives you cover a large portion of the services that developers would normally have to build themselves but don’t really want to build because they’d rather be focusing on the app experience itself. This includes things like analytics, authentication, databases, configuration, file storage, push messaging, and the list goes on. The services are hosted in the cloud and scale with little to no effort on the part of the developer.”

This paragraph was taken from this article, and we recommend that you read it if you want to better understand what Firebase is and what it allows you to do.

You can use the ESP8266 to connect and interact with your Firebase project, and you can create applications to control the ESP8266 via Firebase from anywhere in the world.

In this tutorial, we’ll create a Firebase project with a Realtime Database and use the ESP8266 to store and retrieve data. Once connected to the internet, the ESP8266 can access the database from anywhere in the world.

ESP8266 Firebase Project Introduction realtime database

You can have two ESP8266 boards in different networks, with one board storing data and the other board reading the most recent data, for example.

ESP8266 Getting Started Realltime Database Firebase

In a later tutorial, we’ll create a web app using Firebase that will control the ESP8266 to display sensor readings or control outputs from anywhere in the world.

Project Overview

In this tutorial, you’ll learn how to create a Firebase project with a realtime database and store and read data from the database using the ESP8266.

To follow this project, first, you need to set up a Firebase project and create a realtime database for that project. Then, you’ll program the ESP8266 to store and read data from the database. This tutorial is divided into three sections.

  1. Create a Firebase Project
  2. ESP8266: Store data to the Firebase Realtime Database
  3. ESP8266: Read data from the Firebase Realtime Database

Let’s get started!


Set Up a Firebase Account and Create a New Project

1.Create a New Project

Follow the next instructions to create a new project on Firebase.

  1. Go to Firebase and sign in using a Google Account.
  2. Go to the Firebase Console and create a new project.
  3. Give a name to your project, for example: ESP-Project, and click Continue.
    Set Up Firebase Project for ESP32 and ESP8266 Step 1
  4. Next, enable or disable AI assistance for your project. This is optional.
    Set Up Firebase Project for ESP32 and ESP8266 - Enable AI assistant
  5. Disable the option Enable Google Analytics for this project, as it is not needed. Then, click Create project.
    Disable Google Analytics for firebase project
  6. It will take a few seconds to set up your project. Click Continue when it’s ready.
    Firebase Project for ESP32 Ready

  7. You’ll be redirected to your Project console page.
    Firebase console project

2. Set Authentication Methods

You need to set authentication methods for your app.

“Most apps need to know the identity of a user. In other words, it takes care of logging in and identifying the users (in this case, the ESP8266). Knowing a user’s identity allows an app to securely save user data in the cloud …” To learn more about the authentication methods, you can read the documentation.

  1. On the left sidebar, click on Build > Authentication and then on Get started.
    Firebase project set authentication
  2. There are several authentication methods like email and password, Google Account, Facebook account, and others.
    SFirebase authentication methods
  3. Select Email/Password and enable that authentication method. Then, click Save.
    Enable Email Password Sign in Firebase
  4. Then, at the top, click on the Users tab. Then, click on Add user.
    Firebase Create a new user
  5. Create a new user with an email and password. The email can be your personal email. Create a password for that user (you need to remember the password later). Finally, click on Add user.
    Firebase add user email and password
  6. The User will show up on the list of users. You can see information about the user, like when it was created, the last time it signed in, and its user UID.
    Firebase User Created

3. Creating a Realtime Database

Next, you need to create a Realtime Database for your project. Follow the next steps to create the database.

  1. On the left sidebar click on Build > Realtime Database and then, click on Create Database.
    Firebase Project Create Database
  2. Select your database location. It should be the closest to your location.
    Firebase Realtime Database Set up location
  3. Set up security rules for your database. For testing purposes, select Start in test mode. In later tutorials, you’ll learn how to secure your database using database rules.
    Firebase Realtime Database Start in Test Mode
  4. Your database is now created. You need to copy and save the database URL—highlighted in the following image—because you’ll need it later in your ESP8266 code.
    Firebase Real time database URL

The Realtime Database is all set. Now, you also need to get your project API key.

4. Get Project API Key

  1. To get your project’s API key, on the left sidebar click on Project Settings.
    Firebase Realtime Database Project Settings
  2. Copy the API Key to a safe place because you’ll need it later.
    Firebase Project API Key

Now, you have everything ready to interface the ESP8266 with the database.


Program the ESP8266 to Interface with Firebase

Now that the Firebase Realtime Database is created, you’ll learn how to interface the ESP8266 with the database.

To program the ESP8266, you can use Arduino IDE, VS Code with the PlatformIO extension, or other suitable software.

Note: For Firebase projects, we recommend using VS Code with the PlatformIO or pioarduino extension. If you plan to develop a web application to connect the ESP8266 with Firebase, VS Code offers all the tools you need. However, since we won’t be building a web application in this tutorial, you can simply use the Arduino IDE, if you prefer.

Installing the FirebaseClient Library

There is a library with lots of examples to use Firebase with the ESP8266: the FirebaseClient library. This library is compatible with the ESP32, ESP8266, and many other boards.

In this tutorial, we’ll look at simple examples to store and read data from the database. The library provides many other examples that you can check here. It also provides detailed documentation explaining how to use the library.

Installation – VS Code + PlatformIO

If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and then select the Libraries tab. Search for “FirebaseClient“. Select the Firebase Client Library by Mobitz.

Install FirebaseClient Library VS Code

Then, click Add to Project and select the project you’re working on.

Add FirebaseClient Library ro project in VS Code

Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:

monitor_speed = 115200

Installation – Arduino IDE

If you’re using Arduino IDE, follow the next steps to install the library.

  1. Go to Sketch > Include Library > Manage Libraries
  2. Search for FirebaseClient and install the FirebaseClient by Mobitz. We’re using version 2.0.3.
Install Firebase Client Library Arduino IDE

Now, you’re all set to start programming the ESP8266 board to interact with the database.


ESP8266 Store Data to Firebase Database

ESP8266 Firebase store data realtime database project example

Copy the following code to your Arduino IDE. This sketch inserts an int, a float number, and a string into the database every 10 seconds. This is a simple example that shows how to connect the ESP8266 to the database to store data.

/*********
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete instructions at https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
*********/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>

// Network and Firebase credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL"
#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

// User function
void processData(AsyncResult &aResult);

// Authentication
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

// Firebase components
FirebaseApp app;
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
RealtimeDatabase Database;

// Timer variables for sending data every 10 seconds
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 10000; // 10 seconds in milliseconds

// Variables to send to the Database
int intValue = 0;
float floatValue = 0.01;
String stringValue = "";

void setup(){
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)    {
    Serial.print(".");
    delay(300);
  }
  Serial.println();

  // Configure SSL client
  ssl_client.setInsecure();
  ssl_client.setTimeout(1000); // Set connection timeout
  ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes

  // Initialize Firebase
  initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
  app.getApp<RealtimeDatabase>(Database);
  Database.url(DATABASE_URL);
}

void loop(){
  // Maintain authentication and async tasks
  app.loop();

  // Check if authentication is ready
  if (app.ready()){
    // Periodic data sending every 10 seconds
    unsigned long currentTime = millis();
    if (currentTime - lastSendTime >= sendInterval){
      // Update the last send time
      lastSendTime = currentTime;

      // send a string
      stringValue = "value_" + String(currentTime);
      Database.set<String>(aClient, "/test/string", stringValue, processData, "RTDB_Send_String");

      // send an int
      Database.set<int>(aClient, "/test/int", intValue, processData, "RTDB_Send_Int");
      intValue++; //increment intValue in every loop

      // send a string
      floatValue = 0.01 + random (0,100);
      Database.set<float>(aClient, "/test/float", floatValue, processData, "RTDB_Send_Float");
    }
  }
}

void processData(AsyncResult &aResult){
  if (!aResult.isResult())
    return;

  if (aResult.isEvent())
    Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());

  if (aResult.isDebug())
    Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());

  if (aResult.isError())
    Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());

  if (aResult.available())
    Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}

View raw code

You need to insert your network credentials, URL database, project API key, firebase user email and password.

This sketch was based on this basic example provided by the library. You can find more examples here.

How the Code Works

Continue reading to learn how the code works, or skip to the demonstration section.

Including Libraries

First, include the required libraries. The ESP8266WiFi.h library to connect the ESP8266 to the internet, the WiFiClientSecure to create a wi-fi client, and the FirebaseClient.h library to interface the ESP8266 with Firebase.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>

Defining Credentials

Include your network credentials in the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert your Firebase project API key—the one you’ve gotten in section 4.1.

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

Insert your database URL—see section 3.4.

#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL"

Set the Firebase email user and corresponding password. The ones you set up in section 2.

#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

Declaring Firebase Authentication and Components

The following line creates an authentication object using the project API key, the project user email, and password.

UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

This creates a FirebaseApp instance called app that refers to the Firebase application.

FirebaseApp app;

The following lines set up the asynchronous communication framework for interacting with Firebase’s Realtime Database. Basically, you create an SSL client using the WiFiClientSecure library. Then, you instantiate an Asynchronous client called aClient that enables secure HTTPS. This will allow you to handle network operations asynchronously.

WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);

The following line creates a RealtimeDatabase object called Database, that represents the Firebase Realtime Database.

RealtimeDatabase Database;

Timer and Data Variables

Then create variables to track the time and save the data to be sent to the database.

unsigned long lastSendTime = 0;
const unsigned long sendInterval = 10000; // 10 seconds in milliseconds
int intValue = 0;
float floatValue = 0.01;
String stringValue = "";

setup()

In the setup(), initialize the Serial Monitor and connect the board to your Wi-Fi network.

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();

Configure the SSL Client.

ssl_client.setInsecure();
ssl_client.setTimeout(1000); // Set connection timeout
ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes

The following line initializes the Firebase app with authentication and sets the processData() as the callback function for async results (this means that any results from the initializeApp() function will be handled on the processData() callback function).

initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");

Then, tell that you want to set the Database object defined earlier as a database for our Firebase app.

app.getApp<RealtimeDatabase>(Database);

Finally, set the database URL.

Database.url(DATABASE_URL);

loop()

The Firebase library we’re using works asynchronously and with callback functions. This means that when an event happens, the corresponding assigned callback functions will run. To keep the Firebase app running, handling authentication and asynchronous tasks, we need to add app.loop() at the start of our loop() function.

void loop(){
  app.loop();

The app.ready() command checks if Firebase authentication is complete and ready, so that we can proceed with other Firebase operations (like writing to the database).

if (app.ready()){

The following lines check if 10 seconds (sendInterval) have passed. We’ll use this to send data periodically every 10 seconds.

unsigned long currentTime = millis();
if (currentTime - lastSendTime >= sendInterval){
  lastSendTime = currentTime;

Send Data to the Database

Next in the loop(), we send our data. We’re sending three different variable types. Sending other types is the same. You just need to specify the type on the set() function as we’ll explain.

The FirebaseClient library supports different methods to send data to the Real Time Database. In this example, we’re using an asynchronous approach with a callback function.

To send data to the database we use Database.set(). This is templated to support different data types. Here’s the general syntax and the arguments:

Database.set<T>(AsyncClient &client, const String &path, T value, AsyncResultCallback callback, const String &uid);

Let’s break down how it works:

  • <T> refers to the data type. In the code, it’s used as Database.set<String>, Database.set<int> and Database.set<float>. You can use other data types.
  • AsyncClient &client: this is the asynchronous client object (aClient in the code) that manages the network connection to Firebase.
  • const String &path: specifies the path in the Firebase Realtime Database where the data will be written. The path is relative to the database root (defined by DATABASE_URL). For example: “test/string”.
  • T value: the value to be written to the specified path.
  • AsyncResultCallback callback: a function pointer to the callback that handles the result of the asynchronous operation. In the code, this is the processData() function. It processes the AsyncResult object to log events, errors, debug messages, or successful payloads. The callback is called when the Firebase server responds or if an error occurs during the request.
  • const String &uid: a unique identifier for the task, used to track the specific operation in the callback. This helps differentiate between multiple asynchronous tasks in the processData() function.

For example, the following lines send a string to the database.

stringValue = "value_" + String(currentTime);
Database.set<String>(aClient, "/test/string", stringValue, processData, "RTDB_Send_String");
  • Client: aClient (manages the HTTPS connection).
  • Path: “/test/string”.
  • Value: stringValue variable that contains a String.
  • Callback: processData (handles the result).
  • UID: “RTDB_Send_String” (identifies this task in logs).

Sending an integer and a float is similar.

// send an int
Database.set<int>(aClient, "/test/int", intValue, processData, "RTDB_Send_Int");
intValue++; //increment intValue in every loop

// send a string
floatValue = 0.01 + random (0,100);
Database.set<float>(aClient, "/test/float", floatValue, processData, "RTDB_Send_Float");

Process the Async Results

Finally, the processData() function logs the results of the asynchronous Firebase operations.

void processData(AsyncResult &aResult) {
  if (!aResult.isResult())
    return;

  if (aResult.isEvent())
    Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());

  if (aResult.isDebug())
    Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());

  if (aResult.isError())
    Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());

  if (aResult.available())
    Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}

Demonstration

Upload the code to your ESP8266 board. Don’t forget to insert your network credentials, database URL path, the project API key, and the Firebase project user email and password.

After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP8266 on-board reset button so it starts running the code.

If everything works as expected, the values should be stored in the database, and you should get success messages.

ESP8266 Send Data to the Realtime Database Firebase - Serial Monitor Demonstration

Go to your project’s Firebase Realtime database, and you’ll see the values saved on the different node paths. Every 10 seconds, it saves a new value. The database blinks when new values are saved.

ESP32 Store value firebase database Success

Congratulations! You’ve successfully stored data in Firebase’s Realtime Database using the ESP8266. In the next section, you’ll learn to read values from the different database node paths.


ESP8266 Read From Firebase Database

ESP8266 Firebase get data realtime database project example

In this section, you’ll learn how to read data from the database. We’ll read the data stored in the previous section. Remember that we saved an int value in the test/int path, a float value in the test/float and a String value in the test/string path.

There are different ways to get values from the database. We’ll show you how to do that synchronously and asynchronously.

ESP8266 – Read From Firebase RTDB (Async Mode)

The following example reads the values stored in the database using an asynchronous method. Upload the following code to your board. You can use the same ESP8266 board or another board to get the data posted by the previous ESP8266.

/*********
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete instructions at https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
*********/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>

// Network and Firebase credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL"
#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

// User functions
void processData(AsyncResult &aResult);

// Authentication
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

// Firebase components
FirebaseApp app;
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
RealtimeDatabase Database;

// Timer variables for reading data every 10 seconds
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 10000; // 10 seconds in milliseconds

// Variables to save values from the database
int intValue;
float floatValue;
String stringValue;

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }

  // Configure SSL client
  ssl_client.setInsecure(); // For testing only
  ssl_client.setTimeout(1000); // Set connection timeout
  ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes

  // Initialize Firebase
  initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
  app.getApp<RealtimeDatabase>(Database);
  Database.url(DATABASE_URL);
}

void loop(){
  // Maintain authentication and async tasks
  app.loop();

  // Check if authentication is ready
  if (app.ready()){
    // Periodic data sending every 10 seconds
    unsigned long currentTime = millis();
    if (currentTime - lastSendTime >= sendInterval){
      // Update the last send time
      lastSendTime = currentTime;

      // GET VALUES FROM DATABASE (using the callback async method method)
      // you can then get the values on the processData function as soon as the results are available
      Database.get(aClient, "/test/int", processData, false, "RTDB_GetInt");
      Database.get(aClient, "/test/float", processData, false, "RTDB_GetFloat");
      Database.get(aClient, "/test/string", processData, false, "RTDB_GetString");
          
      Serial.println("Requested data from /test/int, /test/float, and /test/string");
    }
  }
}

void processData(AsyncResult &aResult){
  if (!aResult.isResult())
    return;

  if (aResult.isEvent())
    Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());

  if (aResult.isDebug())
    Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());

  if (aResult.isError())
    Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());

  // here you get the values from the database and save them in variables if you need to use them later
  if (aResult.available()) {
    // Log the task and payload
    Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());

    // Extract the payload as a String
    String payload = aResult.c_str();

    /// Handle int from /test/int
    if (aResult.uid() == "RTDB_GetInt"){
      // Extract the value as an int
      intValue = payload.toInt();
      Firebase.printf("Stored intValue: %d\n", intValue);
    }
    // Handle float from /test/float
    else if (aResult.uid() == "RTDB_GetFloat"){
      // Extract the value as a float
      floatValue = payload.toFloat();
      Firebase.printf("Stored floatValue: %.2f\n", floatValue);
    }
    
    // Handle String from /test/string
    else if (aResult.uid() == "RTDB_GetString"){
      // Extract the value as a String
      stringValue = payload;
      Firebase.printf("Stored stringValue: %s\n", stringValue.c_str());
    }
  }
}

View raw code

You need to insert your network credentials, URL database, project API key, firebase user email and password.

How the Code Works

The first sections of the code are quite similar to the previous example. It connects and authenticates to Firebase and sets up the database connection. Then, it gets the data from the database in async mode. The results of the operation (the values of the variables) are then handled in the callback function.

Getting Data from the Database

To get data, we need to know the exact path where it is located and its type (for later processing). We can get it using the get() method on the Database object as follows.

Database.get(AsyncClient &client, const String &path, AsyncResultCallback callback, bool queue, const String &uid);

Here’s how it works:

  • AsyncClient &client: this is the asynchronous client object (aClient in the code) that manages the network connection to Firebase.
  • const String &path: specifies the path in the Firebase Realtime Database where we’ll get the data. The path is relative to the database root (defined by DATABASE_URL). For example: “test/string”.
  • AsyncResultCallback callback: a function pointer to the callback that handles the result of the asynchronous operation. In the code, this is the processData() function. In this example, it is where we’ll get the actual data from the database and save it in variables.
  • bool queue: a boolean flag indicating whether the operation should be queued if the client is busy with another task. Set false for immediate execution, or true to queue the request. In more complex examples, it is a good idea to set it to true.
  • const String &uid: a unique identifier for the task, used to track the specific operation in the callback. This helps differentiate between multiple asynchronous tasks in the processData() function.

As you can see, the get() function is quite similar to the set() function we’ve seen previously.

For example, in the following line, we set the operation to read from the database node /test/int. This operation will be handled on the task with the identifier RTDB_GetInt.

Database.get(aClient, "/test/int", processData, false, "RTDB_GetInt");

We proceed similarly to get values from the other node paths.

Database.get(aClient, "/test/float", processData, false, "RTDB_GetFloat");
Database.get(aClient, "/test/string", processData, false, "RTDB_GetString");

Saving the Data Into Variables

The result of the get() operation is then handled in the processData() function.

The following statement if (aResult.available()) verifies if the AsyncResult contains a successful result with data available for processing. If available() returns true, it means we have data to process—we successfully got data from the database.

if (aResult.available())  {
  // Log the task and payload
  Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());

We can get the data as follows:

String payload = aResult.c_str();

Then, with aResult.uid() we can check which operation occurred based on the task name and then save the data in the appropriate variable type.

/// Handle int from /test/int
if (aResult.uid() == "RTDB_GetInt"){
  // Extract the value as an int
  intValue = payload.toInt();
  Firebase.printf("Stored intValue: %d\n", intValue);
}
// Handle float from /test/float
else if (aResult.uid() == "RTDB_GetFloat"){
  // Extract the value as a float
  floatValue = payload.toFloat();
  Firebase.printf("Stored floatValue: %.2f\n", floatValue);
}
        
// Handle String from /test/string
else if (aResult.uid() == "RTDB_GetString"){
  // Extract the value as a String
  stringValue = payload;
  Firebase.printf("Stored stringValue: %s\n", stringValue.c_str());
}

Demonstration

Upload the code to your board. Then, open the Serial Monitor at a baud rate of 115200. After a few seconds, it will print the values saved in the database.

ESP8266 Get Data from Firebase Realtime Database Serial Monitor Result

ESP8266 – Read From Firebase RTDB (No Async Mode)

For simpler applications where you don’t need to queue tasks and blocking code is not critical while waiting for a database operation, you can use the get() function in a simplified format. This allows you to directly retrieve a value from the Firebase Realtime Database and immediately store it in a variable.

For example:

int intValue =  Database.get<int>(aClient, "/test/int");

The Database.get(aClient, “/test/int”) synchronously fetches an integer from the Firebase RTDB path /test/int using aClient, assigns it to intValue, and blocks execution until complete. This is ideal for simple applications where you don’t need multiple tasks, but this may delay other operations.

Here’s an example code using this method. It works exactly like the previous example. But for more complex applications, you should opt for the asynchronous method.

/*********
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete instructions at https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
*********/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>

// Network and Firebase credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL"
#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

// User function
void processData(AsyncResult &aResult);

// Authentication
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

// Firebase components
FirebaseApp app;
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
RealtimeDatabase Database;

// Timer variables for sending data every 10 seconds
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 10000; // 10 seconds in milliseconds

// Variables to save values from the database
int intValue;
float floatValue;
String stringValue;

void setup(){
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)    {
    Serial.print(".");
    delay(300);
  }

  // Configure SSL client
  ssl_client.setInsecure();
  ssl_client.setTimeout(1000); // Set connection timeout
  ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes

  // Initialize Firebase
  initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
  app.getApp<RealtimeDatabase>(Database);
  Database.url(DATABASE_URL);
}

void loop(){
  // Maintain authentication and async tasks
  app.loop();

  // Check if authentication is ready
  if (app.ready()){
    // Periodic data sending every 10 seconds
    unsigned long currentTime = millis();
    if (currentTime - lastSendTime >= sendInterval){
      // Update the last send time
      lastSendTime = currentTime;

      // GET VALUES FROM DATABASE (and save the data in a variable)
      int intValue =  Database.get<int>(aClient, "/test/int");
      check_and_print_value (intValue);

      float floatValue = Database.get<float>(aClient, "/test/float");
      check_and_print_value(floatValue);

      String stringValue = Database.get<String>(aClient, "/test/string");
      check_and_print_value(stringValue);

      Serial.println("Requested data from /test/int, /test/float, and /test/string");
    }
  }
}

template <typename T>
void check_and_print_value(T value){
  // To make sure that we actually get the result or error.
  if (aClient.lastError().code() == 0){
    Serial.print("Success, Value: ");
    Serial.println(value);
  }
  else {
    Firebase.printf("Error, msg: %s, code: %d\n", aClient.lastError().message().c_str(), aClient.lastError().code());
  }
}

void processData(AsyncResult &aResult){
  if (!aResult.isResult())
    return;

  if (aResult.isEvent())
    Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());

  if (aResult.isDebug())
    Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());

  if (aResult.isError())
    Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());

  if (aResult.available()) {
    // Log the task and payload
    Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
  }
}

View raw code

Wrapping Up

Congratulations! In this tutorial, you’ve created a Firebase project with a Realtime Database and learned how to store and read data from the database using the ESP8266 NodeMCU board.

To keep things simple, we’ve stored sample values in the database. The idea is to save useful data like sensor readings or GPIO states.

Then, you can access the database with another ESP8266 to get the data or create a Firebase web app to use that data to display sensor readings or control the ESP8266 GPIOs from anywhere in the world. You can follow the next tutorial to learn more about creating web apps with Firebase:

We hope you find this tutorial useful. If you want to learn more about Firebase with the ESP32 and ESP8266 boards, check out our new eBook:

If you want to learn more about the ESP8266, check our courses:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

64 thoughts on “ESP8266 NodeMCU: Getting Started with Firebase (Realtime Database)”

  1. Looks interesting but so far I haven’t gotten the first part to work. Below is what shows on my serial monitor.
    Any idea what is wrong.

    Serial monitor:
    Connected with IP xxx.xxx.x.xxx
    ok

    FAILED
    REASON: connection lost

    FAILED
    REASON: connection lost

    #define DATABASE_URL “esp-firebase-demo-xxxxx-default-xxxx: null”

    #define DATABASE_URL “esp-firebase-demo-xxxxx-default-xxxx:”
    <I tried but ways but doesn’t work either way>

    Reply
    • probably you put a variable before the “if” in the loop. I added my variable inside the first if and it solved:
      “if (Firebase.ready() && signupOK && (millis() – sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)){
      sendDataPrevMillis = millis();

      variable = (analogRead(A0)*3.3/1023);

      // Write an Int number on the database path test/int
      if..."

      Reply
  2. First post discarded all my comments, one more time

    Looks interesting but so far I haven’t gotten the first part to work. Below is what shows on my serial monitor.
    Any idea what is wrong.

    Serial monitor:
    Connected with IP xxx.xxx.x.xxx
    ok
    //after about 2 minutes//
    //from else line 89//
    FAILED
    REASON: connection lost
    //after about 2 minutes//
    //from else line 101//
    FAILED
    REASON: connection lost
    //repeats//

    //should line 32 include ‘:null’//
    #define DATABASE_URL “esp-firebase-demo-xxxxx-default-xxxx: null”
    //or//
    #define DATABASE_URL “esp-firebase-demo-xxxxx-default-xxxx:”
    //I tried both ways but doesn’t work either way//

    //Nothing shows up on the Realtime Database//

    Reply
  3. It sort of works for me. I have added the snippets to my program which displays time and temp on Oled and I get several exception(3) restarts just after initializing the firebase stuff in setup.
    I wonder if more people see this happening?
    BR
    Jan

    Reply
  4. Realized I could do the test with original program from Sarah as described above.
    That does not give the resets/restarts.
    My program without firebase snippets works ok, but inserting the firebase snippets causes the restarts (Exception (3)) just in setup executing Firebase.begin(&config, &auth);
    No clue why (yet).

    Reply
  5. Exactly what I need bit I can’t get past the Firebase.begin statement. Firebase.signup is ok as I see the IDs O. The Firebase console.

    The error I get is a code 400 bad request. Pretty sure the URL and API key is correct. Any idea?

    Reply
    • Hi.
      What is the version of the ESP Firebase Client Library that you’re using?
      Try downgrading to version 2.3.7 and see if that solves the issue.
      Regards,
      Sara

      Reply
  6. Hi, first I apology for my bad English.

    I almost do eveything above,but it just keep showing these.

    Token info: type = id token, status = error
    Token error: code: 400, message: bad request
    Token info: type = id token, status = on request

    Is that something I did wrong?

    Reply
    • Hi
      Check Your project API key and database URL.
      If everything is correct, try downgrading to the ESP Firebase Client library to version 2.3.7
      Regards,
      Sara

      Reply
  7. I tried and it works, but I expected to see in the database give all the values, and the previous ones. I found it interesting as a data logger. May?

    Reply
  8. Hello,

    The Arduino Serial Monitor is only printing “Connecting to WiFI…………………………..”
    Please let me know the resolution to this issue.
    John

    Reply
        • I don’t know.
          That issue is usually related to:
          – incorrect SSID or password;
          – poor wi-fi range (the ESP can’t connect to the router)

          I don’t think it has anything to do with the project itself.
          Regards,
          Sara

          Reply
  9. Congratulations on the article, finally someone able to explain in a simple and accurate way how to start a Firebase-ESP8266 project.
    I followed your examples and everything works fine. I tried to manage my data and I found some difficulties that I hope you will help me to solve.
    In firebase I have this example:
    MW-COUNT
    0-MAX 5
    1-TOUT 3
    2-TING 2
    I generated this structure by inserting integer values (5,3,2)
    Now I tried to read them in a single function but I only ever get the first value 5.
    Do you have a solution to this problem?
    Is it possible to read the entire MW-COUNT node?
    Thanks for your kind cooperation.

    Reply
  10. Hello Sarah,
    Very nice project. I have lots of ideas for firebase. Just a question. how much does it cost for basic projects. Is there a limit before we pay.
    thank you Michel

    Reply
  11. Hi Sara, I have encounter the following error when I compiling. I have downgraded the library to 2.3.7 version but still cannot work.

    Arduino: 1.8.19 (Windows 10), Board: “Arduino Nano, ATmega328P”
    In file included from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37:0,

    from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,

    from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:41,

    from C:\Users\angyo\Desktop\Arduino\ESP_Testing_Send\ESP_Testing_Send.ino:18:

    C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:36:10: fatal error: vector: No such file or directory

    #include

    ^~~~~~~~

    compilation terminated.

    exit status 1

    Error compiling for board Arduino Nano.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply
    • Hi.
      Select an ESP32 or ESP8266 board in Tools > Board.
      From your output, it seems you have an Arduino Nano selected.
      Regards,
      Sara

      Reply
      • Hi Sara, I have choose the correct board but still cannot work, this is what I get:

        Arduino: 1.8.19 (Windows 10), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)”

        In file included from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:45:0,

        from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37,

        from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,

        from C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:41,

        from C:\Users\angyo\Desktop\Arduino\ESP_Testing_Send\ESP_Testing_Send.ino:18:

        C:\Users\angyo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp8266/FB_TCP_Client.h:56:30: fatal error: CertStoreBearSSL.h: No such file or directory

        #include <CertStoreBearSSL.h>

        ^

        compilation terminated.

        exit status 1

        Error compiling for board NodeMCU 1.0 (ESP-12E Module).

        This report would have more information with
        “Show verbose output during compilation”
        option enabled in File -> Preferences.

        Reply
  12. hello, I still have this error, I redid the tutorial 10 times but still the same error

    13:55:00.902 -> Connected with IP: 192.168.1.60
    13:55:00.902 ->
    13:55:02.065 -> API key not valid. Please pass a valid API key.
    13:55:02.065 -> Token info: type = id token, status = on request
    13:55:03.189 -> Token info: type = id token, status = error
    13:55:03.189 -> Token error: code: 400, message: API key not valid. Please pass a valid API key.
    13:55:03.189 -> Token info: type = id token, status = error
    13:55:03.237 -> Token error: code: 400, message: bad request
    13:55:03.237 -> Token info: type = id token, status = on request
    13:55:04.334 -> Token info: type = id token, status = error
    13:55:04.380 -> Token error: code: 400, message: API key not valid. Please pass a valid API key.
    13:55:04.380 -> Token info: type = id token, status = error
    13:55:04.380 -> Token error: code: 400, message: bad reques

    Reply
    • Hi.
      Double-check your API key.
      Are you copying the API key correctly? Are you copying the database URL correctly?
      The error is about the API key.
      Maybe create a new Firebase project and see if that solves the issue.
      Regards,
      Sara

      Reply
  13. Hi !
    Token info: type = id token, status = error
    Token error: code: 400, message: bad request
    Token info: type = id token, status = on request

    I am a student studying in Korea.
    The above error appears repeatedly.
    Can you help?

    I respect you.
    Can you tell me how to study?

    Reply
  14. finally man. i have done a through research on this subject for my home automation and found only outdated material which my board wont be able to run but before i gave up i found this article and it works great . thank you so much really appreciate it keep up the good work .

    Reply
  15. Hi Sara Santos,

    Very useful. I have different issue. My firebase RTDB store N number of data of people (name, age , salary). Surely I need a loop to read all data of N people. My path is like this

    root/uniqueID_1/name
    root/uniqueID_1/age
    root/uniqueID_1/salary

    root/uniqueID_2/name
    root/uniqueID_2/age
    root/uniqueID_2/salary
    and so on.

    How can parse this entire databse ot retreive each data

    Reply
  16. Itried the code, gives the error: Token error: code: 400, message: INVALID_PASSWORD.
    For login the gmail account after inserting the correct password, I need to tap on the phone. Is the error has anything to do with login procedure?

    Reply
  17. Hi Sara,
    I try this sketch, it runs for ESP32 but with ESP8266 I can’t compile.
    I use as you suggested but it is full of errors, i.e. <C:\Users\Renzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\SD\src/SD.h:30:20: note: to match this ‘(‘>
    or <C:\Users\Renzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\SD\src/SD.h:30:28: note: in expansion of macro ‘O_READ’
    30 | #define FILE_WRITE (sdfat::O_READ | sdfat::O_WRITE | sdfat::O_CREAT | sdfat::O_APPEND)>
    For me is deep dark.

    Probably there is another library that is incompatible

    If you have any solution , thanks
    Renzo

    Reply
  18. Hi Sara,
    greate tutorial, thank-you 👍😀
    after completing successful the first one in the “firebase” series “esp8266-nodemcu-firebase-realtime-database” step by step I have tried the more realistic one
    “esp32-data-logging-firebase-realtime-database/”
    using the same firebase as created by the first tutorial. Using the same API Key and DATABASE_URL. However access was denied due to PASSWORD_LOGIN_DISABLED.

    Token info: type = id token (GITKit token), status = on request
    Token info: type = id token (GITKit token), status = error
    Token error: code: 400, message: PASSWORD_LOGIN_DISABLED
    Token info: type = id token (GITKit token), status = error
    Token error: code: 400, message: bad request
    Getting User UID

    Maybe I have to change the access method for my firebase or other settings. Please tell me where and how to do this.
    Thanks again for sharing your knowledge😊
    Joshen

    Reply
  19. Hi, I am getting the error:
    FAILED
    REASON: send request failed

    Can you please help me with this. It is really urgent for me. I’d be really thankful.

    Thanks.

    Reply
    • I tried downgrading the library to 2.3.7 and now it only shows the line
      Connected to IP: (and the address)_and thats it. Can you help?

      Reply
  20. Hello,

    I have followed this tutorial and successfully build a project using Esp8266 and Firebase Realtime Database. Everything works fine except that when my project is kept idle for like an hour or something it gives me this error:

    Token info: type = id token, status = on request
    Token info: type = id token, status = error
    Token error: code: 400, message: INVALID_EMAIL

    Please Note that my Token and Database URL are totally fine. As far as the Email is concerned, im using the anonymous authentication of firebase so that the ESP can connect directly without any human interaction.

    Thank you.

    Reply
  21. I successfully logged into the firebase. But in the loop() part, the error “connection lost” keeps comming. I am using v 2.3.7. The newest version gave me error “connection failed”

    Reply
  22. Hi Sara,
    I try to compile for Wemos mini ESP8266 , but the compilation in not successful.
    Probably the error is here;
    In file included from C:\Users\Renzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\SD\src/SD.h:25,
    from c:\users\renzo\documents\arduino\libraries\firebase_arduino_client_library_for_esp8266_and_esp32\src\firebasefs.h:162,
    from C:\Users\Renzo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:36,
    from C:\Users\Renzo\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:34,
    from C:\Users\Renzo\AppData\Local\Temp\arduino_modified_sketch_190486\sketch_sep12b.ino:18:
    C:\Users\Renzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\SDFS\src/SDFS.h: In member function ‘virtual int sdfs::SDFSFileImpl::availableForWrite()’:
    C:\Users\Renzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\SDFS\src/SDFS.h:279:31: error: ‘using element_type = class File32’ {aka ‘class File32’} has no member named ‘availableSpaceForWrite’; did you mean ‘availableForWrite’?
    279 | return _opened ? _fd->availableSpaceForWrite() : 0;
    | ^~~~~~~~~~~~~~~~~~~~~~
    | availableForWrite
    Pi

    Can you help me?
    Tanks
    Renzo Giurini

    Reply
  23. hello i did your tutorial but i keep getting this error:

    Token info: type = id token (GITKit token), status = on request
    Token info: type = id token (GITKit token), status = error
    Token error: code: -4, message: connection lost

    Reply
    • Hi.
      It still works using the deprecated library on VS Code.
      The interface on Firebase console has changed the colors, but the menus are the same.

      Are you stuck at some point in the process?

      Regards,
      Sara

      Reply

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.