Firebase

This Firebase cheatsheet provides a complete

1. Firebase Overview

FeatureDescription
FirebaseA BaaS (Backend-as-a-Service) platform by Google
Realtime ServicesFirestore, Realtime Database, Authentication, Cloud Functions
Analytics ToolsGoogle Analytics, Crashlytics, Performance Monitoring
Storage & HostingFirebase Storage, Firebase Hosting

2. Core Firebase Services

Authentication

Handles user identity and login.

Auth Providers:

Key Auth Functions:

FunctionPurpose
Create UserRegister new user
Sign InLog in existing user
Sign OutLog out
On Auth StateListen for login/logout events
Email VerificationSend link to verify email
Reset PasswordSend password reset link

Cloud Firestore (Document-based NoSQL)

ConceptDescription
CollectionA group of documents
DocumentA record with fields
FieldKey-value pair in a document
ReferencePath to document/collection
QuerySearch/filter documents

Firestore Data Model Example:

users (collection)
  └── user123 (document)
        ├── name: "Alice"
        ├── age: 25
        └── isActive: true

Common Firestore Operations:

OperationMethod
Add Documentadd()
Get Documentget()
Update Documentupdate()
Delete Documentdelete()
Realtime ListeneronSnapshot()
Query with Filterswhere(), orderBy(), limit()

⚠️ Firestore Limits:

Realtime Database (JSON-based)

FeatureDescription
StructureEntire DB is a JSON tree
SyncRealtime sync across devices
Use CasesChat, IoT, low-latency apps

Limitations:

Firebase Storage

FeatureDescription
StoresFiles: images, videos, docs
Powered byGoogle Cloud Storage
SupportsUpload/download/delete, metadata
UseWith Auth to restrict access

Firebase Analytics

FeatureDescription
TracksEvents, users, behavior, traffic
Auto Eventsfirst_open, app_update, etc.
Custom EventsDefine your own (e.g., purchase, download)
DashboardSee in Firebase Console or Google Analytics
Integrates WithA/B Testing, Remote Config, Ads

Cloud Functions for Firebase

FeatureDescription
TypeServerless backend functions
Triggered byAuth, Firestore, Realtime DB, HTTP, Pub/Sub
Use CasesSending emails, push notifications, payments, cron jobs
LanguageJavaScript, TypeScript (Node.js environment)

Firebase Hosting

FeatureDescription
Fast & SecureCDN-backed static file hosting
SSLFree HTTPS for all domains
RewritesFor SPAs & functions
Custom DomainsSupported
DeployCLI tool (firebase deploy)

Firebase Cloud Messaging (FCM)

FeatureDescription
PurposePush notifications (mobile, web, server)
ChannelsTopic messaging, device tokens
TriggersApp behavior, server-side events
ConfigServer key required

⚙️ Firebase Remote Config

FeatureDescription
Dynamic SettingsChange values without app update
Use CaseA/B testing, feature flags, UI tuning
Target UsersBased 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

CommandDescription
firebase loginAuth with Firebase
firebase initInitialize Firebase in project
firebase deployDeploy to Firebase
firebase emulators:startRun local emulators
firebase serveHost locally
firebase logoutSign out from Firebase

Firebase Emulators

ServiceEmulator
Firestore✅
Realtime DB✅
Functions✅
Hosting✅
Auth✅
Pub/Sub✅

Best Practices

⚠️ Firebase Plan Limits

PlanFree (Spark)Paid (Blaze)
Firestore50K reads/dayPay-as-you-go
Storage1GBScalable
Auth10K verifications/monthScalable
Hosting1GB/10GB transferScalable
Functions2M invocations/monthScalable

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

OperationMethod
Create (Auto ID)addDoc()
Create (Custom ID)setDoc()
Read Single DocgetDoc()
Read All DocsgetDocs()
UpdateupdateDoc() or setDoc({ merge: true })
DeletedeleteDoc()
Realtime ListenonSnapshot()

8. Security Rules Example

match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; }

Firebase SDK Languages

Language/PlatformSDK Available
JavaScript (Web/Node.js)✅
Android (Kotlin/Java)✅
iOS (Swift/Obj-C)✅
Flutter✅
Unity✅
C++✅
Admin SDK (Node.js, Python, Java, Go)✅

Useful Links