Firebase API Reference & Cheatsheet — Auth, Firestore, Hosting Quick Guide
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
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 serverfirebase.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
- Missing indexes for compound queries — Firestore requires composite indexes for
where+orderByon different fields - Deleting documents without cleaning subcollections — subcollections persist after parent deletion
- Overusing
get()in Security Rules — eachget()costs a document read - Writing rules with
if truein production — global access until rules are deployed - Not using batched writes — individual writes for related data are not atomic
- Forgetting to unsubscribe listeners — memory leaks in single-page apps
Practice Questions
- What is the difference between
setDocandaddDoc? - How does
onAuthStateChangedhelp manage UI state? - What does
writeBatchprovide that individualsetDoccalls don’t? - How do Security Rules prevent unauthorized data access?
- What does
firebase hosting:channel:deploydo?
Answers:
setDocwrites to a specific document path (you choose ID).addDocauto-generates a unique document ID.- It fires on sign-in, sign-out, and page load — providing a centralized state listener for updating the UI.
writeBatchmakes multiple writes atomic (all succeed or all fail) and reduces the number of billed write operations.- Rules evaluate every request on Firebase servers, checking auth state and data conditions before allowing any read/write.
- 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
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 |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro