jahed.dev

Don't Fail on Analytics

It's common practice in web development to use navigator.sendBeacon for analytics. It was made exactly for that purpose, and because of that, you should never assume it'll work.

I've recently encountered issues with popular websites that render and then disappear. It looks like after the page is rendered, some JavaScript is executed to "rehydrate" the page with more features, only for it to crash on navigator.sendBeacon is undefined or a similar error.

Looking at the documentation for navigator.sendBeacon, we can see that it's widely supported. So why is it failing on my browser of choice: Firefox?

Firefox has an option called beacon.enabled, when set to false, it removes navigator.sendBeacon. Yes, that means it's a user choice. I don't recall making that choice, but I did, or maybe something else did it for me. It doesn't help much since developers can just fallback to one of the many alternatives, so I've already set it back to true.

But that's not the point. Regardless of why navigator.sendBeacon is failing, do you really want it to break your entire application?

In general, when developing software with non-essential side effects like analytics, always make sure to completely isolate it from the main flow. It's as simple as a try with an empty catch.

try {
  navigator.sendBeacon(/* ... */);
} catch {
  /* ignore failures */
}

Thanks for reading.