How do you paginate Firestore queries?

Answer

Firestore pagination uses query cursors to split data into pages. Cursor-based pagination (preferred over offset-based): (1) Initial page: const q = query(collection(db, "posts"), orderBy("createdAt", "desc"), limit(10)); const snap = await getDocs(q); const lastDoc = snap.docs[snap.docs.length - 1]; (2) Next page: const nextQ = query(collection(db, "posts"), orderBy("createdAt", "desc"), startAfter(lastDoc), limit(10)); (3) Previous page: store the first document of the current page and use endBefore(firstDoc) with limitToLast(10). For infinite scroll: append data from each page to the list as the user scrolls. For numbered pages: Firestore doesn't support offset pagination natively (offset(n) requires reading and discarding n documents — expensive). The recommended approach is always cursor-based. Store page cursors (document snapshots or document field values) for "jump to page" scenarios if needed. startAt(value) and endAt(value) use field values instead of document snapshots for more control.