🔄 Fix a Fetch Keepalive Flag Truncating a Large Payload
Setting keepalive: true on a fetch() call is the standard way to make a request survive the page unloading — useful for a final analytics ping or a last save on navigation away — but browsers cap the total size of all in-flight keepalive request bodies combined, typically around 64 KB in Chromium. A request built to carry a larger payload (a batch of queued events, a full form snapshot) doesn’t get a clear error when it exceeds that cap; depending on the browser, it either fails to send at all or the request is rejected before it leaves the page, with nothing in your .catch() because the fetch promise itself may never even reject in the way you’d expect from a normal network failure.
🔎 The Problem
window.addEventListener("pagehide", () => {
fetch("/api/analytics/batch", {
method: "POST",
keepalive: true,
body: JSON.stringify(queuedEvents), // 180 KB of queued events
});
// Exceeds the browser's combined keepalive body size limit (~64KB in
// Chromium) - request silently fails to be queued, queuedEvents is lost,
// and no catch block fires because the failure happens before the
// fetch's own promise machinery gets involved
✅ Fix: A Fetch Keepalive Flag Truncating a Large Payload
- Check the serialized payload size before sending and chunk it into multiple requests under the browser’s keepalive limit, rather than sending one large batch on unload.
- For the common final-ping-on-unload case, prefer navigator.sendBeacon() instead, and check its own boolean return value (it also has a size cap, but tells you synchronously whether the browser accepted the request).
- Flush and send analytics data incrementally as it’s generated rather than queuing everything for a single request at unload, so there’s nothing large left to send in that narrow, failure-prone window.
🚨 Why This Is Dangerous
- A payload that silently fails to send on page unload leaves no trace in your client-side logs, since the page is already gone by the time anyone could see an error — the first sign is just missing data on the server side.
keepalive buys a request a little extra time after the page is gone — it was never meant to buy it unlimited size.




