Skip to main content
Quick Reference

Firebase Cheatsheet

Firebase on one page — Auth, Firestore reads and writes, listeners, security rules, indexes, and the traps around setDoc and the apiKey.

10 sections 10 tables 14 code snippets

Start the app

Install

npm install firebase

One app, two services

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const app = initializeApp({
  apiKey: "YOUR_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT",
});
const auth = getAuth(app);
const db = getFirestore(app);

What each piece is

PieceRole
firebaseThe modular web SDK. New code imports functions, not firebase.firestore()
initializeAppOnce per page. A second call with the same name throws
apiKeyPublic in the browser. It does not grant database access
getAuth / getFirestoreOne handle each, from the same app
ConsoleCreate the project, register a web app, and copy firebaseConfig
ProductsEmail sign-in and a Firestore database stay off until you create them

This page is Authentication and Cloud Firestore. The Realtime Database and the Admin SDK are different products.

Sign in

Email account and the session

import {
  createUserWithEmailAndPassword,
  onAuthStateChanged,
  signOut,
} from "firebase/auth";

const cred = await createUserWithEmailAndPassword(auth, email, password);
onAuthStateChanged(auth, (user) => {
  if (user) console.log(user.uid);
});
await signOut(auth);

Session rules

CallEffect
createUserWithEmailAndPasswordCreates the account. Fails when that email is already registered
signInWithEmailAndPasswordSigns in an existing account. Turn on Email/Password in the console first
onAuthStateChangedRuns after the saved session is restored. This is the check to trust
auth.currentUserOften null on the first render, before that callback
user.uidThe id to store on documents that person should own
signInWithPopupGoogle and other providers. Enable the provider. A popup can be blocked on a phone

Create and update

Create with your own id

import { doc, setDoc } from "firebase/firestore";

await setDoc(doc(db, "books", "dune"), {
  title: "Dune",
  pages: 412,
});

Change one field

import { doc, updateDoc } from "firebase/firestore";

await updateDoc(doc(db, "books", "dune"), {
  price: 19,
});

Which write to use

CallResult
setDocCreates the document, or replaces every field
{ merge: true }Writes the fields you pass and leaves the rest
updateDocChanges named fields. Fails when the document is missing
addDocCreates a document and lets Firestore pick the id
Document idYour choice with setDoc. A slash is not allowed, and the id cannot be . or ..
One documentA single write is atomic. Other clients see all of it or none of it

Read

One document

import { doc, getDoc } from "firebase/firestore";

const snap = await getDoc(doc(db, "books", "dune"));
if (snap.exists()) console.log(snap.data());

A filtered list

import { collection, query, where, orderBy, limit, getDocs } from "firebase/firestore";

const q = query(
  collection(db, "books"),
  where("pages", ">=", 300),
  orderBy("pages", "desc"),
  limit(10)
);
const snaps = await getDocs(q);

Query rules

FormMeaning
getDocA missing document is not an error. exists() is false
getDocsThe matches. An empty list is a success
where plus orderBy on another fieldNeeds a composite index. The error links to the console
Missing orderBy fieldThat document is left out of the result
EqualityCase-sensitive. Dune and dune are different
No joinRead a second collection, or copy the title onto the order

Listen for changes

Stay subscribed

import { collection, onSnapshot, query, where } from "firebase/firestore";

const q = query(collection(db, "books"), where("pages", ">=", 300));
const stop = onSnapshot(q, (snaps) => {
  snaps.forEach((snap) => console.log(snap.id));
});

How a listener behaves

FactDetail
First callbackThe current result, then a callback after each change
Return valueCall stop() when the view goes away. Otherwise the listener keeps running
ErrorsA permission failure arrives in the error callback, not as a thrown await
metadata.fromCacheThe first snapshot can come from memory. Check this when you need the server copy
getDocOne read. A listener is a stream and bills for each changed document
Several listenersEach onSnapshot is its own stream. Share one if two views need the same query

Update a field

Sentinels, not a read-then-write

import { doc, updateDoc, increment, arrayUnion, serverTimestamp, deleteField } from "firebase/firestore";

await updateDoc(doc(db, "books", "dune"), {
  stock: increment(1),
  tags: arrayUnion("scifi"),
  updated: serverTimestamp(),
  draft: deleteField(),
});

Field operations

CallDoes
increment(1)Adds on the server. A missing number starts at 0
arrayUnionAdds a value that is not already in the array
arrayRemoveRemoves every equal value
serverTimestamp()The server clock. A client Date can be wrong
deleteField()Removes the field. null is stored as null
undefinedRejected. Leave the field out, or turn on ignoreUndefinedProperties

Batch and transaction

Two writes, one outcome

import { doc, writeBatch } from "firebase/firestore";

const batch = writeBatch(db);
batch.update(doc(db, "books", "dune"), { price: 19 });
batch.set(doc(db, "orders", "o1"), { bookId: "dune", amount: 19 });
await batch.commit();

When to group writes

ToolUse it when
writeBatchUp to 500 writes. commit sends them together. All succeed or none do
runTransactionYou must read a document and write a value that depends on it
Read orderIn a transaction, finish the reads before the writes. The SDK retries on a clash
A batch cannot readUse a transaction when the next number depends on the current one
Client SDKBatches still pass through security rules
Admin SDKRuns on a server and uses IAM. It bypasses security rules

Security rules

Only signed-in owners can write

service cloud.firestore {
  match /databases/{database}/documents {
    match /books/{bookId} {
      allow read: if request.auth != null;
      allow write: if request.auth != null
        && request.auth.uid == request.resource.data.owner;
    }
  }
}

Rules and queries

RuleEffect
Rules are not filtersA query fails if it could return a document the rule would deny
Match the constraintIf the rule checks owner, the query needs where("owner", "==", uid)
getDocChecked against that one document
A collection queryChecked against every document it might return
request.authNull when nobody is signed in
request.resource.dataThe document after this write. resource.data is the document before it

Indexes and document shape

This query needs a composite index

query(
  collection(db, "books"),
  where("author", "==", uid),
  orderBy("pages", "desc")
);

Limits worth knowing

LimitDetail
Composite indexNeeded when a filter and an orderBy use different fields. Build it from the error link
1 MiBThe maximum size of one document. A growing log belongs in a subcollection
DeleteRemoving a document leaves its subcollections in place
CollectionsCreated by the first document. There is no separate create step
Dotted pathfavorites.color updates that nested field. It does not replace favorites
CacheThe default cache is memory and disappears on reload. persistentLocalCache keeps IndexedDB

Interview traps

Traps worth memorising

TrapWhat happensPrefer
firebase.firestore()The old namespaced APIFunctions imported from firebase/firestore
Hiding the apiKeyAnyone can read it in the page. It does not grant accessSecurity rules, and App Check for production
auth.currentUser on the first renderOften null, before the session is restoredonAuthStateChanged
setDoc with no mergeReplaces the document. Other fields disappearmerge: true, or updateDoc
updateDoc on a missing documentThe write failssetDoc with merge when the document might be new
A list query the rules might rejectThe whole query failsThe same where the rule checks
orderBy on another field and no indexAn index error, plus a console linkCreate that composite index
Ignoring the unsubscribe functionThe listener keeps running after the view is goneCall the function onSnapshot returned
Saving undefinedThe write is rejectedOmit the field
null to remove a fieldnull is storeddeleteField()
Deleting a parent documentSubcollections remainDelete those documents too
A client Date for the created timeThe device clock can be wrongserverTimestamp()

The session

onAuthStateChanged(auth, (user) => {
  console.log(user && user.uid);
});

Keep the other fields

await setDoc(ref, { price: 19 }, { merge: true });

How to use this page: install firebase, call initializeApp once, and wait for onAuthStateChanged before you read uid. Then setDoc a book, query it with where and orderBy, and publish rules that match that query.