navigator.sendBeacon VS fetch + keepalive

Zack HuZack Hu
2 min read

When try to send some requests to the backend whenever frontend user ‘leave’ the page, there are two approaches navigator.sendBeacon or fetch with keepalive set to true.

So what is the tradeoff?

Advantages of navigator.sendBeacon:

  • Specifically designed for sending data when a page is being unloaded

  • Asynchronous with low priority, won't block page unload process

  • Browser ensures data transmission completion even after page closure

  • Simple to use with a clean API interface

  • Automatically uses POST method

  • No need to handle responses, ideal for one-way data reporting

Limitations of navigator.sendBeacon:

  • Only supports POST requests

  • Cannot receive response content

  • Size limitations (Chrome limits to approximately 64KB)

  • No custom headers support (except Content-Type)

Advantages of fetch + keepalive:

  • Supports all HTTP methods (GET, POST, PUT, etc.)

  • Allows custom request headers

  • Can handle response content

  • No data size limitations

  • More flexible error handling

Limitations of fetch + keepalive:

  • More complex implementation

  • Requires manual keepalive option setting

  • Slightly lower browser compatibility compared to sendBeacon

Usage examples:

  1. Using navigator.sendBeacon (for simple data reporting):
javascriptCopywindow.addEventListener('unload', () => {
  navigator.sendBeacon('/api/log', JSON.stringify({
    event: 'page_exit',
    duration: performance.now()
  }));
});
  1. Using fetch + keepalive (for more control):
javascriptCopywindow.addEventListener('unload', () => {
  fetch('/api/sync', {
    method: 'POST',
    keepalive: true,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer token'
    },
    body: JSON.stringify({
      data: 'important_data'
    })
  });
});

Recommendation: Choose navigator.sendBeacon for simple analytics and logging scenarios, and fetch + keepalive when you need more control over the request or need to handle responses. For critical data, consider synchronizing during user interactions rather than waiting for page unload.

0
Subscribe to my newsletter

Read articles from Zack Hu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zack Hu
Zack Hu