sendBeacon in JavaScript
Tags: javascript, learning, webdev, tutorial
Published: 2024-07-12 14:00:23

Have you ever needed to transmit information to the server when the user navigates to a different page? 🧐

When a user exits a page, the **unload** and **beforeunload** events are triggered.

We can use either the **XMLHttpRequest** or **fetch method** to send information to the server when these events occur.

However, the limitation is that you **cannot** send information to the server using the fetch method or XMLHttpRequest when the user navigates away from the page

what happens is the browser takes a look at the fact that it's leaving this page and says i don't have time to do fetch or XMLHttpRequest.

so your request get rejected ... 😣

but with **sendBeacon method** from the **navigator** object , we can actually do the call! 

**_notice_**: we're not going to get a response back from the server and that's okay.

**_notice_**: the sendBeacon method only returns boolean which means if the data successfully sent to the server we receive true and if not we receive false value

## let's dive into the code: 🏊🏻

here is a simple express server that i created to get the data from the browser: 


![express server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5oaubb847kynqcbtlgs.png)


as you can see i created a route called : '/analytics' with POST method. but why?

notice : the sendBeacon method sends the data with HTTP POST method and uses `Content-Type:text/plain;charset=UTF-8` to transmit string data.

so in order to get the data from the server we need to utilize the express.text() middleware inside our server : 


![express.text()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pb1p72dj2lkq8k8zgf2r.png)

after that we have access to the data via req.body

_**notice**_ : if you want to add `Content-Type:application/json` header in your request , you can use **blob **: 

```javascript
let blob = new Blob(data , {type: 'application/json;charset=UTF-8'});
navigator.sendBeacon(url , blob);
```
for the front side of our example code i created a file called index.html : 


![front side](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5vvdcq7day9z7jc0r1j.png)

i provided a link to a page called : other.html 
and I've added an unload event listener to the window object so that means any time i click on the link to go to other.html, this code is going to be triggered:


![unload event](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tn2fzmkj6fk5qih7jtv.png)

we are going to call the fetchData function and inside this function we are using the actual fetch method just to see what happens...

so we are not going to able to actually send the request here and we are not gonna get a response. 

if you click on the link you'll see this:


![fetch result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hn4r3fvuks39663be6w9.png)


you can see here that the status of call to /analytics endpoint was **cancelled ** and it was cancelled because the browser unloaded the page.

let's try sendBeacon method this time :


![sendBeacon method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1g2fp34xm677pauu2tkx.png)

this time if you navigate to other.html page at your server terminal you'll see : 


![server result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/of4fzqlfhllyhi0vu6h5.png)

and in your browser you will see that the status of your request changed to **pending** instead of **cancelled**! 
 
that is pretty much i have learned from this method 😁
let me know what you think 🧐