sendBeacon Fires And Forgets On Page Hide

Queue analytics with navigator.sendBeacon on pagehide, where fetch can be cancelled mid-unload and the payload would be lost.

JavascriptData Fetching

Code

javascriptsnippet
15 lines
// sendBeacon hands a small payload to the browser for delivery that
// survives the page unloading — the fire-and-forget channel for
// analytics, where fetch can be cancelled mid-flight
const cart = { sku: 'AB-1234', qty: 2 };

function reportCartOnHide() {
  // The boolean return only says the payload was queued for delivery,
  // not that the server has answered
  const queued = navigator.sendBeacon('/api/cart-exit', JSON.stringify(cart));
  console.log(`beacon queued: ${queued}`);
}

// pagehide fires on every kind of unload, including mobile app
// backgrounding — the reliable moment to flush
window.addEventListener('pagehide', reportCartOnHide);

Why pagehide and not fetch

navigator.sendBeacon('/api/cart-exit', JSON.stringify(cart)) hands the payload to the browser for delivery that survives the page unloading — during teardown a plain fetch can be cancelled mid-flight and the analytics are lost. The boolean return only says the payload was queued for delivery, not that the server has answered; the handler logs it as `beacon queued: ${queued}`.

The unload moment it targets

window.addEventListener('pagehide', reportCartOnHide) fires on every kind of unload, including mobile app backgrounding — the file’s comment calls it the reliable moment to flush. cart is a plain object ({ sku: 'AB-1234', qty: 2 }) serialized once per fire.

The line that queues the beacon

const queued = navigator.sendBeacon('/api/cart-exit', JSON.stringify(cart));

window and navigator make this browser-side — run it in a page, where the queued payload stays small and fire-and-forget by design.

Interactive Tools for This Topic

FAQ

Does sendBeacon Fires And Forgets On Page Hide run in plain Node.js?
No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.