BackgroundThe image may or may not be related. If it's not related then I just want to share my shots with you! ehe

What is Beacon API?

September 18, 2025

You've worked hard on all those features and you ship them to millions of users (finally!). How do you know they're using your features? That's right, analytics!

Depending on your use cases, you either use ready-to-use analytics like Google Analytics or Plausible, or roll your own solutions. We do this by creating backend endpoints and manually sending each event using either fetch or axios. While this approach could work, these requests are prone to cancellation that could happen when users navigate away from the page or close their browser while the request is still in flight. There is no guarantee that the analytics data will reach the servers. Fortunately, the web has a better way.

Behold, the Beacon API. Quoting MDN, the Beacon API "is used to send an asynchronous and non-blocking request to a web server." Requests made using the Beacon API are guaranteed to be completed even after the page has been closed. This is perfect for our use case of sending analytics data. The Beacon API is Baseline Widely available.

It's very easy to use this API. Here's an example in JavaScript:

javascript
// An empty array to hold our analytics data temporarily // We buffer the data for efficiency let dataHistory = []; document.addEventListener('click', (event) => { //add data to the array everytime the user click a button dataHistory.push({ clickedElement: event.target.outerHTML, timestamp: new Date(), eventName: "BUTTON_CLICK", }); }) window.onload = window.onunload = function analytics(event) { // Check if the Beacon API exists // A good practice even though Beacon API is Baseline Widely available if (!navigator.sendBeacon) return; // URL we are sending the data to let url = "https://xinfan.topanlabs.com/analytics"; // By default, Beacon API will send text/string data to backend. To change it to JSON, // we have to send Blob data with type application/json const dataHistoryBlob = new Blob([JSON.stringify(dataHistory)], { type: 'application/json' }); navigator.sendBeacon(url, dataHistoryBlob); };

The Beacon API represents a significant improvement over traditional analytics tracking methods. By ensuring that your analytics data reaches the server regardless of user navigation patterns, you can maintain more accurate insights into how your features are being used. This reliability translates to better data-driven decisions and ultimately, better products for your users.