Special network function for analytics data in browser

How to use 'sendBeacon' to reliably transmit small data chunks

What is "sendBeacon"

You probably know the two options to use when you want to make a request from a client, like from your progressive web app: either XMLHttpRequest or the newer "fetch". But did you know that there’s a third option, specifically designed for sending very small data chunks like analytics data? It’s a function called "sendBeacon", which is available in modern browsers from the "navigator"-object.

How to use "sendBeacon"

Using this purpose-built request-function for small data chunks is really simple. As long as both the "navigator" as well as the "sendBeacon"-function on the navigator are available, all you need to do is provide a URL as well as payload to send.

You can send the following types of data.

  • ArrayBuffer
  • ArrayBufferView
  • Blob
  • DOMString
  • FormData
  • URLSearchParams

Every call of "sendBeacon" will transmit a POST-request to the specified endpoint.

async function track(payload: TrackPayload){
  // We're using 'optional property access'
  // for a simple and clean implementation.
  //
  // You could of course also use nested if(){ ... }.
  await navigator?.sendBeacon?.('/track', payload);
}

// The following example is taken directly
// from the MDN page, linked in the addendum
// at the end of this page.
//
// It demonstrates the usage with the
// 'visibilitychange'-event when the user
// could close your web app.
document.addEventListener('visibilitychange', function logData() {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/log', analyticsData);
  }
});

What’s different

The main advantage of "sendBeacon" is that your requests will actually be queued by the agent, which means by the browser that currently has your client loaded. As long as a network connection is available, the data gets then sent. If no data is available or the user closes your web app (before the request could have been sent), the browser will still guarantee that the request will be transmitted, eventually.

The other, common request-functions don’t guarantee that your request will be sent when a user closes the web app (for instance by closing the tab). "sendBeacon" is also completely asynchronous and doesn’t introduce any delay when navigating to another page in your web app while still sending the analytics data for the user’s page history.

Progressively enhance your web app

If you have a custom endpoint for analytics data, you should definitely try out this new API. Please keep in mind that a user might call you web app with a browser that doesn’t support the API (although this is highly unlikely), so you can progressively enhance your app with a simple check for support before using it.

Suggestions

Related

Addendum

Languages