🔄 Ajax: Fix a Retry Loop Re-sending a Request After a 304 Response
A 304 Not Modified response is the browser’s HTTP cache telling the server “I already have this, don’t resend it” – and critically, a 304 has no body at all, since the whole point is to avoid retransmitting data the client already has cached. A retry wrapper written to treat “response has no usable body” or “JSON.parse failed on an empty string” as a failed request will treat a perfectly successful 304 exactly like a network error, and dutifully retry a request that didn’t need to be sent again in the first place – sometimes in a loop, since the retried request gets cached-and-304’d again every time.
🔎 The Problem
async function fetchWithRetry(url, attempts = 3) {
const res = await fetch(url);
const text = await res.text();
if (!text) { // true for a 304's empty body
if (attempts > 0) return fetchWithRetry(url, attempts - 1);
throw new Error('Empty response');
}
return JSON.parse(text);
}
// A valid 304 keeps triggering retries, burning all 3 attempts
// and still throwing, even though the resource is unchanged and fine
âś… The Fix
- Check res.status === 304 explicitly before inspecting the body, and read the cached value back from the browser’s own cache API or your own local copy instead of expecting the network response to carry it.
- Treat “empty body” and “request failed” as separate conditions in the retry logic – gate retries on res.ok being false or a thrown network error, not on whatever the body happens to contain.
- If you’re fetching JSON through a wrapper that needs a body every time, set cache: ‘no-store’ (or an appropriate Cache-Control header) deliberately where a fresh body is actually required, rather than fighting the browser’s caching behavior from inside the retry logic.
🚨 Why This Is Dangerous
A retry loop that keeps firing against an endpoint that’s already answering correctly adds real, invisible load – from the server’s perspective every attempt looks like a legitimate new request, not an error being quietly chased by a client that misunderstood a 304.
A 304 isn’t a failure to retry – it’s the server confirming you already have the right answer.




