An empty snapshot is not an empty database. Last night my marketplace's homepage rendered "0 services" while the Firestore console and a plain REST call both showed eleven documents. Detail pages worked, the data was fine, and nothing in the error logs pointed anywhere. Here is the whole chain, including two hypotheses that were wrong, because the wrong hypotheses are usually the expensive part.
The setup
The site is a static Firebase Hosting deployment: one HTML file, one JS bundle, Firestore for data, no build step and no server. The homepage subscribes to a services collection and renders cards. A small badge computes totals from the same array, so an empty array is visually obvious.
After a layout change I redeployed. The home screen came up with the empty state, the requests board said there were no requests, and /service/<id> still rendered perfectly.
Hypothesis 1: missing composite index (wrong)
The first guess was a Firestore index error: where('status', '==', 'published') combined with orderBy('createdAt', 'desc') needs a composite index, and a missing one fails with FAILED_PRECONDITION. If the catch block swallowed it, you get an empty array.
I checked the query in the source. There is no where clause at all, only a single orderBy. A single-field order needs no composite index, and the index config file being empty is correct, not suspicious.
Hypothesis 2: security rules (also wrong)
Next guess: rules blocking anonymous reads. But the deployed ruleset matched the local file, and match /services { allow read: if true; } was in force. Anonymous REST reads with nothing but the public API key returned all eleven documents, which is the cleanest possible proof that rules were not the problem.
Data was fine too: every document had status: published and a createdAt.
The evidence that actually mattered
Inside the same broken page, I created a second Firebase app instance and queried the same collection from the console. Eleven documents. Same page, same rules, same network.
So the database was reachable from that tab. The failure had to be in how the already-running listener handled its first response.
The actual cause: an empty snapshot counted as loaded
The homepage uses onSnapshot and a loaded flag:
let loaded = false;
let items = [];
onSnapshot(q, (snap) => {
items = snap.docs.map(toItem);
loaded = true; // <-- the bug
render();
});
On a cold first load the realtime listener can deliver a snapshot with zero documents before the server response lands, because the SDK emits the local cache view first. My code saw "a snapshot arrived", flipped loaded = true, rendered the empty state, and the follow-up snapshot with real data did not reliably fix the screen: the render path short-circuited on an already-completed state, and on slow connections the second snapshot came late enough that people had already left.
The bug was not Firestore. It was my definition of "loaded". A snapshot callback firing means the client has an opinion about the collection, not that the server has answered.
The fix
Three changes, all small:
let items = null; // null = still loading, [] = genuinely empty
let firstServerRead = false;
function applyServerDocs(docs) {
items = docs.map(toItem);
firstServerRead = true;
render();
}
onSnapshot(q, (snap) => {
const fromCache = snap.metadata.fromCache;
if (!fromCache || snap.size > 0) applyServerDocs(snap.docs);
// an empty cache snapshot: keep the skeleton and wait
}, () => {});
// safety net: if the listener has not produced server data in 3s, read once over REST
setTimeout(function poll(n) {
if (firstServerRead) return;
fetch(restUrl).then(r => r.json()).then(d => {
if (d.documents && d.documents.length) applyServerDocs(d.documents);
else if (n < 4) setTimeout(() => poll(n + 1), 800);
}).catch(() => { if (n < 4) setTimeout(() => poll(n + 1), 800); });
}, 3000, 0);
// refetch when the tab returns or the network comes back
document.addEventListener('visibilitychange', () => {
if (!document.hidden && !firstServerRead) reattachListener();
});
window.addEventListener('online', reattachListener);
Then the two UI states had to be separated. Loading renders skeletons; "nothing here yet" renders only after a server read. The requests board had the same flaw and got the same fix, and I added a small diagnostics object on window that records each load's error count and whether the first render came from cache, so the next report of this symptom starts with evidence instead of a guess.
I also bumped the asset query string and set no-cache on the HTML so nobody kept a stale bundle.
What I would check first next time
- Does a plain REST read with only the public API key return documents? If yes, rules and data are out of the picture in under a minute.
- Does a fresh SDK instance in the same page return documents? If yes, the listener's state handling is the suspect.
- Does the query contain a
whereplus anorderBy? Only then think about composite indexes. - Is "loaded" set because a callback fired, or because server data arrived?
snapshot.metadata.fromCacheanswers that in one line.
The empty state stayed on production for a few hours. The fix was about forty lines, and most of that was making the loading state honest.
I run a one-person studio that finishes AI-built apps - the 3-5 day kind that work locally and then need this sort of production clean-up. If you are stuck on a "works on my machine, empty in production" problem, my English page is https://cpcai-studio.web.app/en/ and you can write to me at yyhak12345@gmail.com in your own language.
Top comments (0)