DEV Community

Cover image for Web Beacon API for Analytics

Posted on

Web Beacon API for Analytics

What is it?

The Web Beacon API is a simple API that is made to simplify data gathering from a client navigating your website.

Send analytics beacons

This API exposes a simple method sendBeacon on the window.navigator global object. It takes one argument which is the URL to send data.

"use strict";

Enter fullscreen mode Exit fullscreen mode

Note that you can use whatever convention you are using on the server-side for the route from where to send analytics data, this is just an example to illustrate the API.

Send analytics data

It optionally takes a second argument which is the data to send.

"use strict";

const analyticsData = JSON.stringify({
    page: "/about",
    clicks: 17,
    scrollHeight: 723

window.navigator.sendBeacon("/analytics/beacon", analyticsData);
Enter fullscreen mode Exit fullscreen mode

I used a string for the data, but you can use some more objects, see the parameters documentation for this method for more informations.

Browser support

This API is kind of new and is still in the recommendation for standard adoption (although some browsers have already adopted it).

You should check for the browser support before using this API and fallback to a traditional way of sending data such as the Fetch API.

Why not simply use the Fetch API?

You could be tempted to send a big chunk of data on page unload (before the page is closed) using the good old Fetch API or even the XMLHttpRequest one.

But this is too risky as you might lose some data and thus some precious analytics information, especially on large requests because you are not guaranteed that the request will successfully be sent on before page unload.

So you might want to record and send data for every events that you might want to register and send to your analytics server.

But that is a huge amount of requests sent from the client for every event (especially events like page scroll or mouse position recording).

Plus, you don't know when the client will abruptly close the browser, and you might lose some context for your data.

Instead, you can just gather data and send them on page unload as this API is made to run in the background once it is used so that the client can safely quit the page and you'll still receive your data for analytics purposes.

This makes the work of qualifying the data easier since one client session equals one beacon sent.

And, beacons do not expect any responses by design, whereas the Fetch API does, so that makes them fast and ideal for sending analytics data.


Make sure you are in compliance with your country's current legislation regarding the collection of user data for knowing what to gather from your clients.

Top comments (0)