Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

This site used to use Umami as a self-hosted and privacy-first analytics tool. Meanwhile, I switched to a paid Plausible instance because I couldn't be bothered with the server maintenance, but that's another story...

An item in Umami's changelog caught my eye โ€“ "Update tracker/index.js: SendBeacon() to Fetch API".

sendBeacon is a JavaScript method that sends POST requests to an analytics server. These requests are supposed to be async, not be canceled and outlive the current navigation. But apparently, sendBeacon is sometimes blocked by ad blockers.

MDN Compat Data (source)
Browser support info for sendBeacon
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
394214313111.111.14.040

That's not a big deal, though, because today I learned I can drop sendBeacon from my memory and use the fetch method with a keepalive option. ๐Ÿ‘‡

await fetch(`${root}/api/collect`, {
  method: 'POST',
  body: data,
  // keep request alive if the page is unloaded
  // before the request is complete
  keepalive: true,
});

What's the browser support? The upcoming Firefox 133 release moves keepalive into baseline territory.

MDN Compat Data (source)
Browser support info for `init.keepalive` parameter
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
66661513313313139.066

fetch with a keepalive option has the same not-cancelable characteristics as sendBeacon and can act as its replacement. But it has the advantage that it's more flexible than sendBeacon. You're not limited to POST requests and can add headers if you want to. Nice!

Don't confuse the keepalive fetch attribute with the Keep-Alive HTTP header.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles