1. Firebase Overview
| Feature | Description |
|---|
| Firebase | A BaaS (Backend-as-a-Service) platform by Google |
| Realtime Services | Firestore, Realtime Database, Authentication, Cloud Functions |
| Analytics Tools | Google Analytics, Crashlytics, Performance Monitoring |
| Storage & Hosting | Firebase Storage, Firebase Hosting |
2. Core Firebase Services
Authentication
Handles user identity and login.
Auth Providers:
- Email/Password
- Google, Facebook, Apple, Twitter
- Phone Number (OTP)
- Anonymous
- Custom Authentication
Key Auth Functions:
| Function | Purpose |
|---|
| Create User | Register new user |
| Sign In | Log in existing user |
| Sign Out | Log out |
| On Auth State | Listen for login/logout events |
| Email Verification | Send link to verify email |
| Reset Password | Send password reset link |
Cloud Firestore (Document-based NoSQL)
| Concept | Description |
|---|
| Collection | A group of documents |
| Document | A record with fields |
| Field | Key-value pair in a document |
| Reference | Path to document/collection |
| Query | Search/filter documents |
Firestore Data Model Example:
users (collection)
└── user123 (document)
├── name: "Alice"
├── age: 25
└── isActive: true
Common Firestore Operations:
| Operation | Method |
|---|
| Add Document | add() |
| Get Document | get() |
| Update Document | update() |
| Delete Document | delete() |
| Realtime Listener | onSnapshot() |
| Query with Filters | where(), orderBy(), limit() |
⚠️ Firestore Limits:
- 1 write/second/document (burst allowed)
- Max doc size: 1MB
- Max 1M docs/query
- Composite indexes needed for complex queries
Realtime Database (JSON-based)
| Feature | Description |
|---|
| Structure | Entire DB is a JSON tree |
| Sync | Realtime sync across devices |
| Use Cases | Chat, IoT, low-latency apps |
Limitations:
- No rich querying (compared to Firestore)
- Max depth: 32 nodes
- Limited offline capabilities
Firebase Storage
| Feature | Description |
|---|
| Stores | Files: images, videos, docs |
| Powered by | Google Cloud Storage |
| Supports | Upload/download/delete, metadata |
| Use | With Auth to restrict access |
Firebase Analytics
| Feature | Description |
|---|
| Tracks | Events, users, behavior, traffic |
| Auto Events | first_open, app_update, etc. |
| Custom Events | Define your own (e.g., purchase, download) |
| Dashboard | See in Firebase Console or Google Analytics |
| Integrates With | A/B Testing, Remote Config, Ads |
Cloud Functions for Firebase
| Feature | Description |
|---|
| Type | Serverless backend functions |
| Triggered by | Auth, Firestore, Realtime DB, HTTP, Pub/Sub |
| Use Cases | Sending emails, push notifications, payments, cron jobs |
| Language | JavaScript, TypeScript (Node.js environment) |
Firebase Hosting
| Feature | Description |
|---|
| Fast & Secure | CDN-backed static file hosting |
| SSL | Free HTTPS for all domains |
| Rewrites | For SPAs & functions |
| Custom Domains | Supported |
| Deploy | CLI tool (firebase deploy) |
Firebase Cloud Messaging (FCM)
| Feature | Description |
|---|
| Purpose | Push notifications (mobile, web, server) |
| Channels | Topic messaging, device tokens |
| Triggers | App behavior, server-side events |
| Config | Server key required |
⚙️ Firebase Remote Config
| Feature | Description |
|---|
| Dynamic Settings | Change values without app update |
| Use Case | A/B testing, feature flags, UI tuning |
| Target Users | Based on app version, location, language, etc. |
Firebase Security Rules
Firestore Rules Syntax
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
Storage Rules Syntax
service firebase.storage {
match /b/{bucket}/o {
match /user_uploads/{file} {
allow read, write: if request.auth != null;
}
}
}
Firebase CLI Commands
| Command | Description |
|---|
| firebase login | Auth with Firebase |
| firebase init | Initialize Firebase in project |
| firebase deploy | Deploy to Firebase |
| firebase emulators:start | Run local emulators |
| firebase serve | Host locally |
| firebase logout | Sign out from Firebase |
Firebase Emulators
| Service | Emulator |
|---|
| Firestore | ✅ |
| Realtime DB | ✅ |
| Functions | ✅ |
| Hosting | ✅ |
| Auth | ✅ |
| Pub/Sub | ✅ |
Best Practices
- Use Firestore for complex apps, Realtime DB for chat/IoT
- Use Auth state listeners to secure UI
- Always write Firestore/Storage rules before going live
- Use indexes for better query performance
- Use batch writes or transactions for atomic operations
- Enable billing to unlock quotas if needed
- Use emulator suite for local dev/testing
- Export/import data using gcloud or Firebase CLI for backups
⚠️ Firebase Plan Limits
| Plan | Free (Spark) | Paid (Blaze) |
|---|
| Firestore | 50K reads/day | Pay-as-you-go |
| Storage | 1GB | Scalable |
| Auth | 10K verifications/month | Scalable |
| Hosting | 1GB/10GB transfer | Scalable |
| Functions | 2M invocations/month | Scalable |
Firebase Firestore CRUD
1. Setup
import {
getFirestore,
collection,
doc,
setDoc,
addDoc,
getDoc,
getDocs,
updateDoc,
deleteDoc,
onSnapshot,
} from "firebase/firestore";
const db = getFirestore(); // Initialize Firestore instance
2. Create / Add Data
Add a document with a generated ID
await addDoc(collection(db, "users"), {
name: "Alice",
age: 25,
isActive: true,
});
Add document with a custom ID
await setDoc(doc(db, "users", "user123"), {
name: "Bob",
age: 30,
isActive: false,
});
3. Read / Get Data
Get a single document by ID
const docRef = doc(db, "users", "user123");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
console.log("No such document!");
}
Get all documents in a collection
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(`${doc.id} =>`, doc.data());
});
4. Update Data
Update specific fields
await updateDoc(doc(db, "users", "user123"), {
age: 31,
isActive: true,
});
Merge with setDoc
await setDoc(
doc(db, "users", "user123"),
{
nickname: "Bobby",
},
{ merge: true },
);
5. Delete Data
Delete a document
await deleteDoc(doc(db, "users", "user123"));
Note
Firestore does not support deleting entire collections directly from the client. Use Firebase Admin SDK or a Cloud Function for that.
6. Realtime Listener
Listen for document changes in real time
const unsub = onSnapshot(doc(db, "users", "user123"), (docSnap) => {
console.log("Current data: ", docSnap.data());
});
// Stop listening
unsub();
7. Summary Table
| Operation | Method |
|---|
| Create (Auto ID) | addDoc() |
| Create (Custom ID) | setDoc() |
| Read Single Doc | getDoc() |
| Read All Docs | getDocs() |
| Update | updateDoc() or setDoc({ merge: true }) |
| Delete | deleteDoc() |
| Realtime Listen | onSnapshot() |
8. Security Rules Example
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
Firebase SDK Languages
| Language/Platform | SDK Available |
|---|
| JavaScript (Web/Node.js) | ✅ |
| Android (Kotlin/Java) | ✅ |
| iOS (Swift/Obj-C) | ✅ |
| Flutter | ✅ |
| Unity | ✅ |
| C++ | ✅ |
| Admin SDK (Node.js, Python, Java, Go) | ✅ |
Useful Links