Zbotic Logo Zbotic Logo
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

  • Shop
  • About Us
  • Contact Us
  • Reseller
  • Blogs
020 69134444
1800 209 0998
[email protected]
Help Desk
Facebook Twitter Instagram Linkedin YouTube
Zbotic Logo Zbotic Logo
0 0

View Wishlist Add all to cart

0 0
0 Shopping Cart
Shopping cart (0)
Subtotal: ₹0.00

View cartCheckout

All departments
  • 3D Print Service
  • 3D Printer
  • Batteries & Chargers
  • Development Boards
  • Drone Parts
  • EBike parts
  • Sensor Modules
  • Electronic Components
  • Electronic Modules
  • IoT and Wireless
  • Mechanical Parts and Workbench Tools
  • Motors & Drivers & Pumps & Actuators
  • DIY and Robot Kits
  • Show more
  • Home
  • Shop
  • Sale
  • 3D Print Service
  • PCB Service
  • B2B
  • Blogs
  • Contact Us
Return to previous page
Home IoT & Smart Home

Firebase Realtime Database with ESP32: IoT Data Storage

Firebase Realtime Database with ESP32: IoT Data Storage

March 11, 2026 /Posted byJayesh Jain / 0

One of the most powerful combinations in modern IoT development is using Firebase Realtime Database with ESP32 for IoT data storage. Firebase, Google’s cloud platform, provides a real-time, NoSQL database that syncs data instantly across all connected clients. Combined with the ESP32’s built-in WiFi and Bluetooth, you can build robust IoT systems that store sensor readings in the cloud, trigger remote actions, and display live data on a web dashboard — all without managing your own server. In this tutorial, we will walk you through the entire process of connecting your ESP32 to Firebase Realtime Database from scratch.

Table of Contents

  1. Why Use Firebase with ESP32?
  2. Setting Up Firebase Realtime Database
  3. Installing Firebase ESP32 Client Library
  4. Writing Sensor Data to Firebase
  5. Reading Data from Firebase on ESP32
  6. Using Firebase Real-Time Streaming
  7. Firebase Authentication and Security Rules
  8. Frequently Asked Questions

Why Use Firebase with ESP32?

Before diving into the code, let us understand why Firebase is an excellent choice for ESP32 IoT projects, especially for Indian makers and students.

  • Free Tier: Firebase’s Spark (free) plan gives you 1GB storage and 10GB/month download — more than enough for most hobby and small commercial IoT projects.
  • Real-Time Sync: Data updates are pushed to all connected clients instantly, enabling live dashboards without polling.
  • No Server Management: You don’t need to set up or maintain a backend server. Google handles infrastructure, scaling, and uptime.
  • REST API Support: Firebase Realtime Database has a built-in REST API, meaning you can interact with it from the ESP32 using standard HTTP requests — no special protocol needed.
  • Dashboard Integration: Build a web dashboard using Firebase hosting that automatically updates when the ESP32 posts new data.
Ai Thinker NodeMCU-32S ESP32 Development Board

Ai Thinker NodeMCU-32S ESP32 Development Board

The NodeMCU-32S is the go-to ESP32 board for Firebase projects — dual-core processor, 4MB flash, and built-in WiFi makes it perfect for IoT data storage applications.

View on Zbotic

Setting Up Firebase Realtime Database

The first step is creating and configuring your Firebase project. Follow these steps carefully.

Step 1: Create a Firebase Project

  1. Go to console.firebase.google.com and sign in with your Google account.
  2. Click Add project and give it a name (e.g., “ESP32-IoT-Monitor”).
  3. You can disable Google Analytics for simplicity, then click Create Project.

Step 2: Create a Realtime Database

  1. In the Firebase console, click Realtime Database in the left menu under Build.
  2. Click Create Database.
  3. Choose a location (select asia-south1 for India for lower latency).
  4. For now, start in Test Mode (we will add security rules later).

Step 3: Get Your Database URL and Secret

  1. Your database URL will look like: https://your-project-default-rtdb.asia-southeast1.firebasedatabase.app/
  2. For authentication, go to Project Settings > Service Accounts and note the Database Secret (or use the Legacy token).
  3. Alternatively, for modern auth, go to Project Settings > General and get the Web API Key.

Installing Firebase ESP32 Client Library

The most popular library for Firebase on ESP32 is the Firebase ESP Client by Mobizt. This library supports Realtime Database, Firestore, Storage, Authentication, and more.

Installation via Arduino IDE

  1. Go to Sketch > Include Library > Manage Libraries
  2. Search for Firebase ESP Client
  3. Install the library by Mobizt
  4. Also install ArduinoJson as a dependency if not already installed

Installation via PlatformIO

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
  mobizt/Firebase Arduino Client Library for ESP8266 and ESP32 @ ^4.4.10
  bblanchon/ArduinoJson @ ^7.0.0

Alternative: Using Firebase REST API Directly

For simple projects, you can skip the library entirely and use the HTTPClient to interact with Firebase’s REST API. We will cover both approaches in this tutorial.

Writing Sensor Data to Firebase

Now let us write a complete sketch that reads temperature and humidity from a DHT11 sensor and saves the data to Firebase Realtime Database every 30 seconds.

#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <addons/TokenHelper.h>
#include <addons/RTDBHelper.h>
#include <DHT.h>

// WiFi credentials
#define WIFI_SSID "YourWiFiSSID"
#define WIFI_PASSWORD "YourPassword"

// Firebase credentials
#define API_KEY "your-firebase-api-key"
#define DATABASE_URL "https://your-project-default-rtdb.asia-southeast1.firebasedatabase.app/"
#define USER_EMAIL "[email protected]"
#define USER_PASSWORD "your-firebase-password"

// DHT Sensor
#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
const long sendInterval = 30000; // 30 seconds

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

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
  Serial.println(" Connected!");
  Serial.println(WiFi.localIP());

  // Configure Firebase
  config.api_key = API_KEY;
  config.database_url = DATABASE_URL;
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  config.token_status_callback = tokenStatusCallback;

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);

  Serial.println("Connecting to Firebase...");
  while (!Firebase.ready()) delay(1000);
  Serial.println("Firebase ready!");
}

void loop() {
  if (Firebase.ready() && (millis() - sendDataPrevMillis > sendInterval)) {
    sendDataPrevMillis = millis();

    float temp = dht.readTemperature();
    float hum = dht.readHumidity();

    if (!isnan(temp) && !isnan(hum)) {
      String path = "/sensors/room1/";

      if (Firebase.RTDB.setFloat(&fbdo, path + "temperature", temp)) {
        Serial.printf("Temp saved: %.1f Cn", temp);
      } else {
        Serial.println(fbdo.errorReason());
      }

      if (Firebase.RTDB.setFloat(&fbdo, path + "humidity", hum)) {
        Serial.printf("Humidity saved: %.1f%%n", hum);
      } else {
        Serial.println(fbdo.errorReason());
      }

      // Save timestamp
      Firebase.RTDB.setInt(&fbdo, path + "timestamp", millis());
    }
  }
}

After running this sketch, open your Firebase console and navigate to your Realtime Database. You should see your sensor data appearing under /sensors/room1/.

DHT11 Temperature And Humidity Sensor with LED

DHT11 Temperature And Humidity Sensor Module with LED

The DHT11 module with LED indicator is perfect for your Firebase ESP32 project — easily read temperature and humidity data to store in the cloud.

View on Zbotic

Reading Data from Firebase on ESP32

Reading data from Firebase is just as straightforward. This is useful when you want the ESP32 to act on commands sent from a web dashboard or mobile app.

// Read a float value
if (Firebase.RTDB.getFloat(&fbdo, "/commands/setpoint_temperature")) {
  float setpoint = fbdo.floatData();
  Serial.printf("Setpoint received: %.1f Cn", setpoint);
} else {
  Serial.println("Read failed: " + fbdo.errorReason());
}

// Read a string value
if (Firebase.RTDB.getString(&fbdo, "/commands/mode")) {
  String mode = fbdo.stringData();
  Serial.println("Mode: " + mode);
}

// Read a boolean value
if (Firebase.RTDB.getBool(&fbdo, "/commands/relay1")) {
  bool relayState = fbdo.boolData();
  digitalWrite(RELAY_PIN, relayState ? HIGH : LOW);
}

Pushing Data with Auto-Generated Keys

Instead of overwriting a single value, you can push data with an auto-generated timestamp key — useful for logging historical readings:

FirebaseJson json;
json.set("temperature", temp);
json.set("humidity", hum);
json.set("timestamp/.sv", "timestamp"); // Firebase server timestamp

if (Firebase.RTDB.pushJSON(&fbdo, "/logs/room1", &json)) {
  Serial.println("Log entry added: " + fbdo.pushName());
}

Using Firebase Real-Time Streaming

One of Firebase’s most powerful features is the ability to stream data changes. Instead of polling Firebase every few seconds, you can set up a listener on your ESP32 that is automatically called whenever data changes in the database.

// Stream callback function
void streamCallback(FirebaseStream data) {
  Serial.printf("Stream path: %sn", data.streamPath().c_str());
  Serial.printf("Event path: %sn", data.dataPath().c_str());
  Serial.printf("Data type: %sn", data.dataType().c_str());

  if (data.dataTypeEnum() == firebase_rtdb_data_type_boolean) {
    bool value = data.boolData();
    if (data.dataPath() == "/relay1") {
      digitalWrite(RELAY_PIN, value ? HIGH : LOW);
      Serial.printf("Relay 1 set to: %sn", value ? "ON" : "OFF");
    }
  }
}

void streamTimeoutCallback(bool timeout) {
  if (timeout) Serial.println("Stream timeout, resuming...");
}

// In setup():
Firebase.RTDB.beginStream(&fbdo_stream, "/commands");
Firebase.RTDB.setStreamCallback(&fbdo_stream, streamCallback, streamTimeoutCallback);

With this approach, the ESP32 reacts to database changes within milliseconds — perfect for controlling relays, LEDs, or motors from a web app or mobile dashboard.

DHT20 SIP Temperature and Humidity Sensor

DHT20 SIP Packaged Temperature and Humidity Sensor

The DHT20 offers improved accuracy over DHT11 with I2C interface — ideal for professional IoT data logging projects with Firebase and ESP32.

View on Zbotic

Firebase Authentication and Security Rules

Leaving your Firebase database in Test Mode (open access) is fine for development but dangerous for production. Here is how to properly secure your database.

Setting Up Email/Password Authentication

  1. In Firebase Console, go to Build > Authentication > Sign-in method
  2. Enable Email/Password provider
  3. Create a user for your ESP32 device under Users tab (e.g., [email protected])

Firebase Security Rules

Restrict database access so only authenticated users can read/write:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

For more granular control, restrict by user UID:

{
  "rules": {
    "sensors": {
      ".read": "auth != null",
      ".write": "auth.uid === 'your-esp32-uid'"
    },
    "commands": {
      ".read": "auth.uid === 'your-esp32-uid'",
      ".write": "auth != null"
    }
  }
}

Data Validation Rules

Prevent invalid data from being written:

{
  "rules": {
    "sensors": {
      "room1": {
        "temperature": {
          ".validate": "newData.isNumber() && newData.val() >= -40 && newData.val() <= 85"
        }
      }
    }
  }
}
18650 Battery Shield for ESP32

2 x 18650 Lithium Battery Shield for Arduino/ESP32/ESP8266

Make your Firebase ESP32 data logger portable with this dual 18650 battery shield — provides 5V/3A output for uninterrupted remote IoT monitoring.

View on Zbotic

Frequently Asked Questions

Q1: Can I use Firebase Realtime Database with multiple ESP32 devices?

Yes! You can connect as many ESP32 devices as you want. Simply organize your database structure to separate data by device ID (e.g., /sensors/esp32-001/, /sensors/esp32-002/). Each device authenticates independently and reads/writes to its own path.

Q2: How do I handle WiFi disconnections in a long-running Firebase project?

The Firebase ESP Client library automatically handles reconnection. Set Firebase.reconnectWiFi(true) in your setup. The library will queue operations and retry when the connection is restored. For critical applications, also implement a watchdog timer to reset the ESP32 if it stays disconnected too long.

Q3: What are the Firebase free tier limits for IoT projects?

The free Spark plan gives you 1GB of database storage, 10GB/month of download, and 100 simultaneous connections. For most hobby IoT projects with a few ESP32 devices, this is more than sufficient. If you exceed limits, the Blaze (pay-as-you-go) plan is very affordable.

Q4: Is Firebase Realtime Database or Firestore better for ESP32?

For ESP32 projects, Firebase Realtime Database is generally better because it has a simpler API, lower latency for real-time updates, and uses less bandwidth. Firestore is more feature-rich for complex queries but has higher overhead. The Firebase ESP Client library supports both.

Q5: Can I use Firebase with ESP32 without a library using just HTTP?

Yes! Firebase Realtime Database has a full REST API. You can do a PUT request to write data: https://your-db.firebaseio.com/sensors.json?auth=YOUR_SECRET with a JSON body. This approach works with the standard HTTPClient library and requires no additional dependencies.

Start Your Firebase IoT Project Today

With ESP32 and Firebase Realtime Database, you have everything you need to build a professional IoT data monitoring system. Get your ESP32 boards, sensors, and power modules from Zbotic — shipped across India with fast delivery.

Shop ESP32 & IoT Modules on Zbotic

Tags: ESP32, ESP32 WiFi, Firebase, Firebase Realtime Database, IoT data storage
Share Post
  • Facebook
  • Linkedin
  • Whatsapp
ESP32 Sensor Fusion: Combine I...
blog esp32 sensor fusion combine imu baro and gps data 595518
blog telegram bot with esp32 remote control via messaging app 595520
Telegram Bot with ESP32: Remot...

Related posts

Svg%3E
Read more

IoT Home Insurance Sensor Kit: Leak, Smoke, and Motion

April 1, 2026 0
Table of Contents IoT and Home Insurance Water Leak Detection Smoke and Fire Detection Motion and Intrusion Sensing Building the... Continue reading
Svg%3E
Read more

IoT Pet Tracker: GPS Collar with Geofencing Alerts

April 1, 2026 0
Table of Contents Introduction and Overview Hardware Components Required GPS Module Integration with ESP32 Cloud Platform Setup Real-Time Tracking Dashboard... Continue reading
Svg%3E
Read more

IoT Aquaponics Controller: Fish and Plant Automation

April 1, 2026 0
Table of Contents The Water Monitoring Challenge in India Sensor Technologies for Water Building the Sensor Node Data Transmission and... Continue reading
Svg%3E
Read more

IoT Composting Monitor: Temperature and Moisture Tracking

April 1, 2026 0
Table of Contents Why Temperature Monitoring Matters Sensor Selection Guide Hardware Assembly and Wiring Firmware Development Cloud Data Logging Alert... Continue reading
Svg%3E
Read more

IoT Beehive Monitor: Weight, Temperature, and Humidity

April 1, 2026 0
Table of Contents Why Monitor Beehives Weight Measurement System Temperature and Humidity Sensing Building the Monitor Data Analysis for Bee... Continue reading

Add comment Cancel reply

Your email address will not be published. Required fields are marked

Facebook Twitter Instagram Pinterest Linkedin Youtube

Get the latest deals and more.

Download on Google Play Download on the App Store

Call us: 020 69134444 / 1800 209 0998

Monday - Saturday 09:30 AM - 06:00 PM
For Technical Supports Email: [email protected]
For Sales / Enquiries Email: [email protected]

  • My Account

    • Cart

    • Wishlist

    • Checkout

    • My Orders

    • Track Order

    • My Account

  • Information

    • FAQs

    • Blogs

    • Career

    • About Us

    • Contact Us

    • Payment Options

  • Policies

    • Privacy Policy

    • Terms & Conditions

    • GST Input Tax Credit

    • Shipping Return Policy

    • E-Waste Collection Points

    • Our Sitemap

© Zbotic.in is registered trademark of Moxie Supply Pvt Ltd – All Rights Reserved
Login
Use Phone Number
Use Email Address
Not a member yet? Register Now
Reset Password
Use Phone Number
Use Email Address
Register
Already a member? Login Now