Firebase Realtime Database Guide
Firebase Realtime Database Guide
🔰 1. Introduction to Firebase
Topics:
• What is Firebase?
• Firebase services (Firestore vs Realtime DB, Auth, Storage, Hosting, etc.)
• Use cases of Firebase Realtime Database
Resources:
Resources:
Code Examples:
javascript
CopyEdit
import { getDatabase, ref, set, onValue } from "firebase/database";
const db = getDatabase();
set(ref(db, 'users/user1'), {
name: "John",
age: 30
});
Resources:
🔐 4. Authentication Integration
Topics:
Resources:
🛡️ 5. Security Rules
Topics:
• Default rules
• Read/Write rules
• User-based permissions
• Custom validation rules
Example Rule:
json
CopyEdit
{
"rules": {
"users": {
"$uid": {
".read": "$uid === [Link]",
".write": "$uid === [Link]"
}
}
}
}
Resources:
Resources:
🧰 8. Advanced Operations
Topics:
Resources:
Example:
Resources:
• Firebase Hosting
• Deploying your app
• Monitoring and usage analytics
• Firebase Emulator Suite for local testing
Resources:
📚 Practice Projects
Ideas:
It provides:
• Cloud-based databases
• Authentication services
• Hosting
• Cloud Functions
• Push notifications
• Analytics
• and more…
Firebase allows frontend or mobile developers to integrate robust backend features using just a few lines of
code and SDKs, especially useful for real-time and cloud-based apps.
2. Cloud Firestore
3. Firebase Authentication
4. Firebase Storage
• Used to store and serve user-generated files like images, videos, PDFs, etc.
• Secured by Firebase Authentication and Firebase Rules.
• Uses Google Cloud Storage behind the scenes.
5. Firebase Hosting
• A fast and secure way to deploy web apps, static content, and dynamic content.
• Global CDN, HTTPS, and free SSL.
• One-line deployment: firebase deploy
Key Features:
• Realtime sync: Changes in data are instantly reflected to all connected clients.
• Offline support: Caches data and syncs when reconnected.
• Cross-platform: Works on Web, Android, iOS.
🔧 Example:
json
CopyEdit
{
"users": {
"user1": {
"name": "Alice",
"age": 25
},
"user2": {
"name": "Bob",
"age": 30
}
},
"messages": {
"msg1": {
"text": "Hello!",
"sender": "user1"
}
}
}
⚠️ Best Practices:
[Link]
✅ For Web:
js
CopyEdit
const firebaseConfig = {
apiKey: "AIzaSy...",
authDomain: "[Link]",
databaseURL: "[Link]
projectId: "your-app",
storageBucket: "[Link]",
messagingSenderId: "123456789",
appId: "1:123456789:web:abc123"
};
html
CopyEdit
<script type="module">
// Import Firebase SDK
import { initializeApp } from "[Link]
import { getDatabase } from "[Link]
const firebaseConfig = {
apiKey: "AIzaSy...",
authDomain: "[Link]",
databaseURL: "[Link]
projectId: "your-app",
storageBucket: "[Link]",
messagingSenderId: "123456789",
appId: "1:123456789:web:abc123"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
gradle
CopyEdit
dependencies {
implementation '[Link]:firebase-database:20.3.0'
}
kotlin
CopyEdit
val database = [Link]()
val myRef = [Link]("message")
[Link]("Hello, World!")
ruby
CopyEdit
pod 'Firebase/Database'
swift
CopyEdit
import Firebase
[Link]()
let ref = [Link]().reference()
[Link]("message").setValue("Hello, World!")
js
CopyEdit
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
In Android:
java
CopyEdit
FirebaseDatabase database = [Link]();
DatabaseReference ref = [Link]("path");
In iOS:
swift
CopyEdit
let ref = [Link]().reference()
js
CopyEdit
import { initializeApp } from "firebase/app";
import { getDatabase, ref, set, onValue } from "firebase/database";
const firebaseConfig = {
apiKey: "YOUR_KEY",
authDomain: "[Link]",
databaseURL: "[Link]
projectId: "your-app",
};
// Write data
set(ref(db, "users/user1"), {
name: "Alice",
age: 25
});
// Read data
onValue(ref(db, "users/user1"), (snapshot) => {
const data = [Link]();
[Link]("User Data:", data);
});
🔁 What is CRUD?
CRUD stands for:
All these operations in Firebase work on references to nodes in the JSON tree structure of the Realtime
Database.
🟢 Writing Data
javascript
CopyEdit
import { getDatabase, ref, set } from "firebase/database";
const db = getDatabase();
set(ref(db, 'users/user1'), {
name: "Alice",
age: 25
});
Explanation: If the user1 node already exists, it will be completely replaced with the new object.
javascript
CopyEdit
import { push } from "firebase/database";
Explanation: push() is ideal for lists (e.g., messages, posts). It creates a unique key each time.
🔵 Reading Data
javascript
CopyEdit
import { onValue } from "firebase/database";
javascript
CopyEdit
import { get } from "firebase/database";
Explanation: Use once() (or get() in the modular SDK) when you just need to read data one time.
🟡 Updating Data
javascript
CopyEdit
import { update } from "firebase/database";
update(ref(db, 'users/user1'), {
age: 26, // changes age
city: "New York" // adds a new field
});
Explanation: Ideal when you want to modify or add specific fields while keeping the rest intact.
🔴 Deleting Data
javascript
CopyEdit
import { remove } from "firebase/database";
remove(ref(db, 'users/user1'));
Explanation: The user1 node and all its children are permanently deleted.
javascript
CopyEdit
import {
getDatabase,
ref,
set,
push,
onValue,
update,
remove
} from "firebase/database";
const db = getDatabase();
// CREATE
const newUserRef = push(ref(db, "users")); // generates unique key
set(newUserRef, {
name: "Eve",
age: 29
});
// READ
onValue(ref(db, "users"), (snapshot) => {
[Link]("All Users:", [Link]());
});
// UPDATE
update(ref(db, "users/" + [Link]), {
age: 30
});
// DELETE
remove(ref(db, "users/" + [Link]));
🔐 Notes on Permissions
To use any CRUD operation, your security rules must allow access:
json
CopyEdit
{
"rules": {
".read": true,
".write": true
}
}
• Email/Password
• Google, Facebook, GitHub
• Phone number
• Anonymous
🔹 Step 1: Enable Authentication Method
1. Go to Firebase Console
2. Choose your project → Build > Authentication
3. Click Get Started
4. Enable Email/Password or any other provider you want under Sign-in method
js
CopyEdit
import { getAuth } from "firebase/auth";
js
CopyEdit
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
js
CopyEdit
import { signInWithEmailAndPassword } from "firebase/auth";
signInWithEmailAndPassword(auth, "user@[Link]", "password123")
.then((userCredential) => {
const user = [Link];
[Link]("User signed in:", [Link]);
})
.catch((error) => {
[Link]("Login error:", [Link]);
});
js
CopyEdit
import { signOut } from "firebase/auth";
signOut(auth)
.then(() => {
[Link]("User signed out");
})
.catch((error) => {
[Link]("Sign out error:", error);
});
js
CopyEdit
import { getDatabase, ref, set } from "firebase/database";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
📌 Summary
Action Function Purpose
createUserWithEmailAndPasswor
Sign Up Register new user
d
Sign In signInWithEmailAndPassword Log in an existing user
Sign Out signOut Log out current user
Link to DB set(ref(db, 'users/' + uid)) Store user profile or metadata
Rules are evaluated every time a client tries to read or write data.
📄 Topics Breakdown
json
CopyEdit
{
"rules": {
".read": false,
".write": false
}
}
This means:
json
CopyEdit
{
"rules": {
".read": true,
".write": true
}
}
json
CopyEdit
{
"rules": {
"messages": {
".read": true,
".write": true
},
"users": {
".read": false,
".write": false
}
}
}
json
CopyEdit
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
json
CopyEdit
{
"rules": {
"users": {
"$uid": {
".read": "$uid === [Link]",
".write": "$uid === [Link]"
}
}
}
}
This ensures:
json
CopyEdit
{
"rules": {
"users": {
"$uid": {
".write": "$uid === [Link]",
".validate": "[Link](['name', 'age'])",
"age": {
".validate": "[Link]() && [Link]() >= 0"
},
"name": {
".validate": "[Link]() && [Link]().length <= 30"
}
}
}
}
}
This ensures:
✅ Best Practices
Tip Why It Matters
Use auth != null Block unauthenticated users
Use $uid === [Link] Enforce user-level isolation
Validate all critical fields Prevent bad or malicious data writes
Never use true in production Avoid public database exposure
✅ Syntax
js
CopyEdit
onValue(ref, callback)
js
CopyEdit
import { getDatabase, ref, onValue } from "firebase/database";
const db = getDatabase();
const userRef = ref(db, 'users/user1');
What it does:
✅ Common Events:
✅ Example: child_added
js
CopyEdit
import { onChildAdded } from "firebase/database";
Good for chat apps: gets called once for existing children and every time a new one is added.
✅ Example: child_changed
js
CopyEdit
import { onChildChanged } from "firebase/database";
✅ Example: child_removed
js
CopyEdit
import { onChildRemoved } from "firebase/database";
js
CopyEdit
import { getDatabase } from "firebase/database";
const db = getDatabase();
[Link](); // optional to force offline
[Link](); // reconnects to server
Realtime Database Web SDK doesn’t support full offline caching as well as Firestore does. On mobile
it’s more robust.
Android Example:
java
CopyEdit
[Link]().setPersistenceEnabled(true);
✅ Summary
Feature Tool/Method Purpose
Realtime updates onValue() Listen for entire node changes
Child tracking onChildAdded() etc. Listen for item-level updates
Offline support (web) Limited Works partially (writes are queued)
Offline support (mobile) Full Works offline + syncs automatically
📁 7. Structuring & Normalizing Data in Firebase Realtime Database
This topic is crucial for designing efficient, scalable, and maintainable databases, especially in NoSQL
systems like Firebase.
json
CopyEdit
{
"users": {
"user1": {
"name": "Alice",
"posts": {
"post1": {
"title": "Post 1"
}
}
}
}
}
Problems:
• Hard to query all posts
• Data duplication becomes a mess if reused
json
CopyEdit
{
"users": {
"user1": {
"name": "Alice"
}
},
"posts": {
"post1": {
"title": "Post 1",
"author": "user1"
}
}
}
Benefits:
json
CopyEdit
{
"posts": {
"post1": {
"title": "Post 1",
"authorId": "user1"
}
},
"users": {
"user1": {
"name": "Alice"
}
}
}
🔗 One-to-Many Relationships
Firebase does not support joins, so one-to-many must be manually modeled using ID references.
Structure:
json
CopyEdit
{
"users": {
"user1": {
"name": "Alice"
}
},
"posts": {
"post1": {
"title": "Post 1",
"authorId": "user1"
},
"post2": {
"title": "Post 2",
"authorId": "user1"
}
},
"user-posts": {
"user1": {
"post1": true,
"post2": true
}
}
}
Here:
js
CopyEdit
const userPostsRef = ref(db, 'user-posts/user1');
onChildAdded(userPostsRef, (snapshot) => {
const postId = [Link];
const postRef = ref(db, 'posts/' + postId);
onValue(postRef, (snap) => {
[Link]("User post:", [Link]());
});
});
📌 Summary Guidelines
Pattern Description
Flatten deeply nested data Avoid slow reads, complex updates
Use IDs and references Simulate relationships without joins
Denormalize where useful Duplicate minimal data for fast reads
Use mapping tables (e.g. user-posts) Model many-to-many and one-to-many relationships
Fetch data in multiple steps Read reference IDs, then fetch objects
json
CopyEdit
{
"users": {
"uid123": {
"username": "alice"
}
},
"posts": {
"post123": {
"title": "Hello World",
"body": "This is a post",
"authorId": "uid123"
}
},
"comments": {
"comment1": {
"postId": "post123",
"authorId": "uid456",
"text": "Nice post!"
}
},
"post-comments": {
"post123": {
"comment1": true
}
}
}
Transactions ensure that concurrent updates to a value are safe — great for counters, votes, or atomic
updates.
js
CopyEdit
import { getDatabase, ref, runTransaction } from "firebase/database";
const db = getDatabase();
const likesRef = ref(db, 'posts/post1/likes');
⏱️ 2. Server Timestamps
🔹 What Is It?
Firebase provides a special value: [Link], which inserts a timestamp from Firebase
servers, ensuring accuracy regardless of device clock.
js
CopyEdit
import { getDatabase, ref, set, serverTimestamp } from "firebase/database";
const db = getDatabase();
const msgRef = ref(db, 'messages/msg1');
set(msgRef, {
text: "Hello World",
createdAt: serverTimestamp()
});
Output in database:
json
CopyEdit
"createdAt": 1714681632000 // Unix timestamp (ms)
🔍 3. Querying Data
Firebase allows querying ordered and filtered subsets of data with query functions.
Method Description
orderByChild(key) Order by a child property
orderByKey() Order by the node's key
orderByValue() Order by value directly
limitToFirst(n) Limit to first n items
limitToLast(n) Limit to last n items
startAt(), endAt(), equalTo() Filtering ranges
js
CopyEdit
import { query, ref, orderByChild, limitToLast, onValue } from "firebase/database";
const db = getDatabase();
const messagesRef = ref(db, 'messages');
const recentMessagesQuery = query(messagesRef, orderByChild('timestamp'), limitToLast(5));
js
CopyEdit
const usersQuery = query(
ref(db, 'users'),
orderByChild('age'),
startAt(18),
endAt(25)
);
• limitToFirst(), limitToLast()
• startAt() or startAfter() with a known key or value
js
CopyEdit
let lastKey = null;
// First page
let firstPageQuery = query(ref(db, 'posts'), orderByKey(), limitToFirst(5));
onValue(firstPageQuery, (snapshot) => {
[Link]((child) => {
lastKey = [Link];
[Link]([Link], [Link]());
});
});
You must track the last key or value of the previous page to get the next.
🧠 Summary Table
Feature Function Use Case
Transactions runTransaction() Safe counters, atomic updates
Server timestamp serverTimestamp() Reliable created/updated times
Ordered queries orderByChild(), orderByKey() Sorting
Filtering startAt(), endAt() Ranges, filtering
Pagination limitToFirst(), startAfter() Load data page by page
js
CopyEdit
query(
ref(db, 'posts'),
orderByChild('category'),
equalTo('tech'),
limitToFirst(10)
);
1. Install Firebase:
bash
CopyEdit
npm install firebase
js
CopyEdit
// [Link]
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_DOMAIN",
databaseURL: "YOUR_DB_URL",
projectId: "YOUR_PROJECT_ID"
};
export { db };
jsx
CopyEdit
import { useEffect, useState } from 'react';
import { ref, onValue } from 'firebase/database';
import { db } from './firebase';
function Messages() {
const [messages, setMessages] = useState([]);
useEffect(() => {
const messagesRef = ref(db, 'messages');
const unsubscribe = onValue(messagesRef, (snapshot) => {
const data = [Link]() || {};
const list = [Link](data).map(([id, val]) => ({ id, ...val }));
setMessages(list);
});
return (
<ul>
{[Link](msg => <li key={[Link]}>{[Link]}</li>)}
</ul>
);
}
js
CopyEdit
const [user, setUser] = useState(null);
useEffect(() => {
const userRef = ref(db, 'users/user1');
return onValue(userRef, (snapshot) => {
setUser([Link]());
});
}, []);
✅ useFirebaseList Hook
js
CopyEdit
import { useEffect, useState } from 'react';
import { ref, onValue } from 'firebase/database';
import { db } from './firebase';
useEffect(() => {
const dataRef = ref(db, path);
const unsubscribe = onValue(dataRef, (snapshot) => {
const val = [Link]() || {};
const list = [Link](val).map(([id, value]) => ({ id, ...value }));
setData(list);
});
return () => unsubscribe();
}, [path]);
return data;
}
Usage:
jsx
CopyEdit
const messages = useFirebaseList('messages');
bash
CopyEdit
npm install firebase
js
CopyEdit
// [Link]
import { initializeApp } from 'firebase/app';
import { getDatabase } from 'firebase/database';
vue
CopyEdit
<script setup>
import { onValue, ref as dbRef } from "firebase/database";
import { db } from "./firebase";
import { ref, onMounted } from "vue";
onMounted(() => {
const messagesRef = dbRef(db, 'messages');
onValue(messagesRef, (snapshot) => {
const data = [Link]() || {};
[Link] = [Link](data).map(([id, val]) => ({ id, ...val }));
});
});
</script>
<template>
<ul>
<li v-for="msg in messages" :key="[Link]">{{ [Link] }}</li>
</ul>
</template>
🅰️ 5. Firebase with Angular
🔹 Using AngularFire
bash
CopyEdit
ng add @angular/fire
Setup in [Link]:
ts
CopyEdit
import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
import { provideDatabase, getDatabase } from '@angular/fire/database';
@NgModule({
imports: [
provideFirebaseApp(() => initializeApp([Link])),
provideDatabase(() => getDatabase()),
],
})
ts
CopyEdit
@Injectable({ providedIn: 'root' })
export class MessageService {
constructor(private db: Database) {}
getMessages() {
const messagesRef = dbRef([Link], 'messages');
return rxOnValue(messagesRef).pipe(
map(snapshot => [Link]())
);
}
}
bash
CopyEdit
npx create-react-app my-firebase-app
cd my-firebase-app
npm install firebase
1. Go to Firebase Console
2. Create a new project.
3. Click “Web App” icon (</>) to register your app.
4. Copy the Firebase config and add it to your project.
Create src/[Link]:
js
CopyEdit
// src/[Link]
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.[Link]",
databaseURL: "[Link]
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID"
};
Example: src/[Link]
js
CopyEdit
import React, { useState, useEffect } from 'react';
import { db } from './firebase';
import { ref, onValue, push } from 'firebase/database';
function Messages() {
const [messages, setMessages] = useState([]);
const [text, setText] = useState('');
useEffect(() => {
const msgRef = ref(db, 'messages');
onValue(msgRef, (snap) => {
const data = [Link]() || {};
setMessages([Link](data).map(([id, val]) => ({ id, ...val })));
});
}, []);
Use in [Link]:
js
CopyEdit
import Messages from './Messages';
function App() {
return <Messages />;
}
export default App;
bash
CopyEdit
npm install -g firebase-tools
bash
CopyEdit
firebase login
firebase init
• Select Hosting
• Select your project
• Set build as the public directory
• Choose yes for SPA rewrite ([Link])
• Say no to overwriting [Link]
3. Build Your App:
bash
CopyEdit
npm run build
4. Deploy:
bash
CopyEdit
firebase deploy
arduino
CopyEdit
[Link]
🌐 1. Firebase Hosting
📌 Prerequisites
bash
CopyEdit
npm install -g firebase-tools
🔧 Steps to Deploy
1. Login to Firebase:
bash
CopyEdit
firebase login
bash
CopyEdit
firebase init
Choose:
• Hosting
• Select your Firebase project
• Set build as your public directory (if using React/Vue)
• Enable single-page app rewrite: Yes
• Don’t overwrite [Link]
bash
CopyEdit
npm run build
• Vue:
bash
CopyEdit
npm run build
4. Deploy:
bash
CopyEdit
firebase deploy
🚀 Example Output:
After deployment:
arduino
CopyEdit
✔ Deploy complete!
Project Console: [Link]
Hosting URL: [Link]
🔹 Hosting Metrics
• Bandwidth usage
• Number of requests
• Error logs
🔹 Realtime Database Metrics
• Read/write counts
• Bandwidth
• Storage usage
For mobile apps or web apps using Google Analytics, you can integrate:
bash
CopyEdit
npm install firebase
js
CopyEdit
import { getAnalytics } from "firebase/analytics";
const analytics = getAnalytics(app);
Track events:
js
CopyEdit
logEvent(analytics, 'login', { method: 'email' });
🔹 What is it?
2. Enable Emulators:
bash
CopyEdit
firebase init emulators
Choose:
• Realtime Database
• Authentication
• Hosting (optional)
3. Start Emulators:
bash
CopyEdit
firebase emulators:start
🔁 Example Output:
less
CopyEdit
✔ All emulators started
✔ UI: [Link]
Hosting: [Link]
Database: [Link]
Auth: [Link]
In development code:
js
CopyEdit
import { connectDatabaseEmulator } from 'firebase/database';
import { connectAuthEmulator } from 'firebase/auth';
connectDatabaseEmulator(db, 'localhost', 9000);
connectAuthEmulator(auth, "[Link]
Now your app talks to the local emulators, not the live Firebase services.
📌 Summary Table
Feature Tool/Command Purpose
Deploy App firebase deploy Live deploy to Hosting
Init Project firebase init Setup project & Hosting configs
Monitor Usage Firebase Console Track bandwidth, usage, errors
Test Locally firebase emulators:start Offline dev without affecting prod
Connect to Emulator connectDatabaseEmulator() Redirect app to local DB/Auth