How and why to use JavaScript navigator.sendBeacon ?

Gourav Mukhija
1 min readAug 10, 2021

The navigator.sendBeacon() lets you asynchronously transfer small HTTP data from the User Agent to a web server. It makes POST requests without waiting for a response.

It’s often used for analytics or diagnostics purpose, since it can be called right when a user closes a page and the request will still fire off.

Syntax

navigator.sendBeacon("/api-url", JSON.stringify(payload))

The sample below sends a beacon to a sample server at https://putsreq.herokuapp.com/4GE2nVUuDoDGsNyKES2G on unload. Close this page and visit the PutsReq inspect page to see if the beacon data was received.

if ('sendBeacon' in navigator) {
window.addEventListener('pagehide', function() {
navigator.sendBeacon(
'https://putsreq.herokuapp.com/4GE2nVUuDoDGsNyKES2G',
'Sent by a beacon!');
}, false);
}

The data is queued and sent when the browser has an opportunity to do so, without getting in the way of other actions. Therefore, it can be more efficient and reliable than the fetch API, which may block execution of other code and be a heavier load on the CPU.

Example

https://web.dev/vitals-field-measurement-best-practices/

https://create-react-app.dev/docs/measuring-performance/

--

--

Gourav Mukhija

Nature lover, Full Stack Web developer and creator of IG: traveler_india