logo
post image

Setting HTTP Headers in a Beacon Request

Use-Cases of this Tutorial

  • Set custom HTTP headers while calling navigator.sendBeacon method.
  • Know how to access the data send by navigator.sendBeacon on the server side.

navigator.sendBeacon is used to send a one-way HTTP POST request to the server. Although is a HTTP request, it seems that the only header you can set is the Content-Type header.

The Beacon API extracts the type of the transmitted data, and sets this as the Content-Type for the HTTP request.

Types of Data that Can Set a Content-Type Header in a Beacon Request

  1. If the data transmitted is a Blob object, then the Content-Type of the HTTP request will be the Blob's type (whatever it has been set).

    var data = { ajax_data: 22 };
    var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
    
    // Content-Type of the Beacon HTTP request will be application/json in this case
    navigator.sendBeacon('ajax.php', blob);
    
  2. If the data transmitted is a FormData object, then Content-Type of the HTTP request will be "multipart/form-data".

    var fd = new FormData();
    fd.append('ajax_data', 22);
    navigator.sendBeacon('ajax.php', fd);
    
  3. If the data transmitted is a URLSearchParams object, then Content-Type of the HTTP request will be "application/x-www-form-urlencoded" (the most common Content-Type while sending data).

    var params = new URLSearchParams({ ajax_data: 22 })
    navigator.sendBeacon('ajax.php', params);
    
  4. If the data transmitted is a USVString object, then Content-Type of the HTTP request will be "text/plain".

    A USVString object is basically a string in Javascript.

What If You Want to Send Other Type of Headers

According to W3C :

The sendBeacon() method does not provide ability to customize the request method, provide custom request headers, or change other processing properties of the request and response. Applications that require non-default settings for such requests should use the [FETCH] API with keep-alive flag set to true.