Skip to content

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

DodaTech Updated 2026-06-06 6 min read

In this tutorial, you'll learn about Firebase API Reference & Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

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

{{< callout type="info" icon="sparkles" >}} Prerequisites: Basic familiarity with Firebase Overview. This is a reference — use alongside the Firebase Authentication and Firebase Database. {{< /callout >}}

Firebase Authentication Reference

Method Description
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

Code Meaning Fix
auth/user-not-found No account for email Show sign-up prompt
auth/wrong-password Incorrect password Show "forgot password?"
auth/email-already-in-use Account exists Suggest sign-in
auth/weak-password Password too short Require 6+ chars
auth/too-many-requests Brute-force protection Wait before retrying
auth/popup-closed-by-user User closed popup Show 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

Variable Description
request.auth Auth object (null if unauthenticated)
request.auth.uid Authenticated user's UID
request.auth.token Custom claims from ID token
request.resource.data Incoming document data
resource.data Existing document data
request.time Current 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 <a href="/apis/firebase/">Firebase</a> 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-<a href="/apis/firebase/">Firebase</a>/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

Topic Description
GraphQL Introduction Schema-based APIs and flexible data fetching
RESTful APIs Compare Firebase with traditional REST backends
Firebase Overview Review the full Firebase platform
SQL vs NoSQL Compare database paradigms and Data Modeling
⬅ Security Rules & Hosting
➡ NoSQL Data Modeling

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro