DEV Community

Vishal Sharma
Vishal Sharma

Posted on

[Video] Frontend logging and Navigator Beacon

In this post I wanted to talk about why front-end logs are essential and how Navigator.sendBeacon() is useful for solving this real-world problem.

Explanation video

To see this in action please head on to the link below!

IMAGE ALT TEXT HERE

Why to log frontend events?

Frontend logging is an essential for many use-cases like,

  • identifying how the user is navigating around the website.
  • log JavaScript errors on the server to help with debugging, etc.

It depends on the implementer on how they would like to implement their front-end logs. For example, in my react applications I have created an HOC to log the Component mount and un-mount along with the props passed to the component.

Implementation

The implementation is really simple. We will just create an event queue and keep pushing our log events in to the queue. Once the queue threshold breaches, we will push all the events in queue to server and reset our queue.

Part 1

Below is the simple implementation -

let events = [];

const logEvent = (event) => {
  events.push(event);

  // 10 is the event queue threshold
  if (events.length >= 10) {
    const payload = JSON.stringify({
      events: [...events],
    });

    events = []; // reset the queue

    fetch('/frontend-log', {
      method: 'POST',
      body: payload
    }).then();
  }
}

Enter fullscreen mode Exit fullscreen mode

Part 2

The above implementation works fine, however, the problem is when the the browser is closed and the event threshold is not breached. This would result in undelivered events, which could result is missing some important error logs as well. So, lets handle that case.

We will add another arg to our logEvent() to force push the events in queue to the server. We will also add an event listener to trigger force push on window unload.

Another issue is with fetch. It doesn't take guarantee of making the request on window close or unload. This is when navigator.sendBeacon() comes in, as it takes guarantee of making the request even after the window is closed.

So our final implementation is as below -

let events = [];

const logEvent = (event, force = false) => {
  events.push(event);

  // 10 is the event queue threshold
  if (events.length >= 10 || force) {
    const payload = JSON.stringify({
      events: [...events],
    });

    events = []; // reset the queue
    window.navigator.sendBeacon('/frontend-log', payload);
  }
}

window.addEventListener('unload', () => {
  logEvent({
    type: 'INFO',
    message: 'Window closed',
  }, true);
})

Enter fullscreen mode Exit fullscreen mode

Refer the video explanation for a working example over a sample Sails JS application.

Top comments (0)