Skip to content
Firebase API Reference & Cheatsheet — Auth, Firestore, Hosting Quick Guide

Firebase API Reference & Cheatsheet — Auth, Firestore, Hosting Quick Guide

DodaTech Updated Jun 6, 2026 5 min read

Firebase API reference and cheatsheet covering Authentication, Firestore, Security Rules, Hosting CLI commands, and common SDK patterns for daily development.

What You’ll Learn

  • Firebase Auth: sign-up, sign-in, providers, user management
  • Firestore: CRUD, queries, real-time listeners, batched writes
  • Security Rules: syntax, patterns, and best practices
  • Hosting CLI commands and configuration
  • Common patterns and error codes

Why This Reference Matters

Firebase has a large API surface — 19+ products with dozens of methods each. Even experienced developers need a quick reference for method signatures, security rule syntax, and CLI flags. DodaTech’s team uses this reference when building Durga Antivirus Pro features, ensuring consistent usage of Auth, Firestore, and Hosting across the codebase.

    flowchart LR
    A["Firebase Reference"] --> B["Auth"]
    A --> C["Firestore"]
    A --> D["Security Rules"]
    A --> E["Hosting CLI"]
    A --> F["Common Patterns"]
    style A fill:#dbeafe,stroke:#2563eb
  
Prerequisites: Basic familiarity with Firebase Overview. This is a reference — use alongside the Firebase Authentication and Firebase Database.

Firebase Authentication Reference

MethodDescription
createUserWithEmailAndPassword(auth, email, password)Email/password sign-up
signInWithEmailAndPassword(auth, email, password)Email/password sign-in
signInWithPopup(auth, provider)OAuth sign-in (Google, Facebook)
signInWithRedirect(auth, provider)OAuth with redirect
signInWithPhoneNumber(auth, phone, verifier)Phone OTP
signOut(auth)Sign out current user
onAuthStateChanged(auth, callback)Auth state listener
sendPasswordResetEmail(auth, email)Reset password
updateProfile(user, { displayName, photoURL })Update profile
deleteUser(user)Delete account

Auth Error Codes

CodeMeaningFix
auth/user-not-foundNo account for emailShow sign-up prompt
auth/wrong-passwordIncorrect passwordShow “forgot password?”
auth/email-already-in-useAccount existsSuggest sign-in
auth/weak-passwordPassword too shortRequire 6+ chars
auth/too-many-requestsBrute-force protectionWait before retrying
auth/popup-closed-by-userUser closed popupShow manual sign-in option

Firestore Reference

CRUD Operations

// Create
setDoc(doc(db, "collection", "docId"), data);
addDoc(collection(db, "collection"), data);

// Read
getDoc(doc(db, "collection", "docId"));
getDocs(collection(db, "collection"));

// Update
updateDoc(doc(db, "collection", "docId"), { field: newValue });

// Delete
deleteDoc(doc(db, "collection", "docId"));

Query Methods

// Filtering
where("field", "==", value)
where("field", ">=", value)
where("field", "array-contains", value)
where("field", "in", [value1, value2])

// Sorting & Limits
orderBy("field", "asc" | "desc")
limit(n)

// Pagination
startAfter(document)
startAt(document)
endBefore(document)
endAt(document)

Real-time Listeners

// Document listener
onSnapshot(doc(db, "coll", "id"), (snap) => { });

// Collection listener
onSnapshot(query, (snapshot) => {
  snapshot.docChanges().forEach((change) => {
    change.type; // "added" | "modified" | "removed"
    change.doc;  // DocumentSnapshot
  });
});

Batched Writes & Transactions

// Batched write (atomic)
const batch = writeBatch(db);
batch.set(doc(db, "users", uid), data);
batch.update(doc(db, "counters", "threats"), { count: increment(1) });
await batch.commit();

// Transaction (reads then writes atomically)
await runTransaction(db, async (transaction) => {
  const doc = await transaction.get(docRef);
  if (doc.exists()) {
    transaction.update(docRef, { count: doc.data().count + 1 });
  }
});

Security Rules Reference

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Deny all by default
    match /{document=**} { allow read, write: if false; }
    
    // Authenticated access to own data
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid == request.resource.data.userId;
    }
    
    // Role-based access (requires user doc lookup)
    match /admin-data/{doc} {
      allow read: if request.auth != null &&
        get(/databases/(default)/documents/users/${request.auth.uid}).data.role == 'admin';
    }
  }
}

Rule Variables

VariableDescription
request.authAuth object (null if unauthenticated)
request.auth.uidAuthenticated user’s UID
request.auth.tokenCustom claims from ID token
request.resource.dataIncoming document data
resource.dataExisting document data
request.timeCurrent timestamp

Firebase Hosting CLI Commands

firebase init hosting          # Initialize hosting
firebase deploy --only hosting # Deploy to production
firebase hosting:channel:deploy preview  # Deploy preview
firebase hosting:clone source target     # Clone hosting
firebase serve --only hosting  # Local server

firebase.json Config

{
  "hosting": {
    "public": "dist",
    "ignore": ["firebase.json", "**/.*"],
    "rewrites": [
      { "source": "/api/**", "function": "api" },
      { "source": "**", "destination": "/index.html" }
    ],
    "headers": [
      { "source": "**/*.@(js|css)", "headers": [
        { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
      ]}
    ]
  }
}

Common Mistakes

  1. Missing indexes for compound queries — Firestore requires composite indexes for where + orderBy on different fields
  2. Deleting documents without cleaning subcollections — subcollections persist after parent deletion
  3. Overusing get() in Security Rules — each get() costs a document read
  4. Writing rules with if true in production — global access until rules are deployed
  5. Not using batched writes — individual writes for related data are not atomic
  6. Forgetting to unsubscribe listeners — memory leaks in single-page apps

Practice Questions

  1. What is the difference between setDoc and addDoc?
  2. How does onAuthStateChanged help manage UI state?
  3. What does writeBatch provide that individual setDoc calls don’t?
  4. How do Security Rules prevent unauthorized data access?
  5. What does firebase hosting:channel:deploy do?

Answers:

  1. setDoc writes to a specific document path (you choose ID). addDoc auto-generates a unique document ID.
  2. It fires on sign-in, sign-out, and page load — providing a centralized state listener for updating the UI.
  3. writeBatch makes multiple writes atomic (all succeed or all fail) and reduces the number of billed write operations.
  4. Rules evaluate every request on Firebase servers, checking auth state and data conditions before allowing any read/write.
  5. It deploys to a preview URL for testing before production deployment.

Challenge: Write a Firebase Security Rule that allows users to create documents in a notifications collection but only read notifications where targetUserId matches their UID. Include data validation that requires a message field (string, 1-500 chars).

FAQ

How do I handle Firebase errors in the client?
: Firebase throws errors with code and message properties. Use try/catch and check error.code to show user-friendly messages. Common codes include permission-denied, not-found, already-exists.
Can I use Firebase with React Native?
: Yes — Firebase has a React Native SDK (@react-native-firebase/app) with support for Auth, Firestore, Storage, and more. The API is similar to the web SDK.
What is the Firebase Admin SDK?
: The Admin SDK runs on trusted servers (Cloud Functions, your backend) with full read/write access to Firebase services. It bypasses Security Rules. Use it for administrative tasks, data migrations, and server-side verification.
How do I export all Firestore data?
: Use gcloud firestore export gs://your-bucket or the Firebase Console > Firestore > Export. Schedule exports with Cloud Scheduler for regular backups.

What’s Next

TopicDescription
GraphQL IntroductionSchema-based APIs and flexible data fetching
RESTful APIsCompare Firebase with traditional REST backends
Firebase OverviewReview the full Firebase platform
SQL vs NoSQLCompare database paradigms and data modeling

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro