Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Beyond Fetch

Beacons, keepalive and Sending Data on Page Exit

Send analytics and saved state reliably when a user leaves the page: navigator.sendBeacon, fetch with keepalive, the visibilitychange event, size limits and a batching queue.

Some data is only worth sending at the very end of a visit: how long the user stayed, how far they scrolled, which video position they reached, a draft they typed but never saved. The obvious place to send it is when the page closes. The obvious way, an ordinary fetch() call in an unload handler, is also the way that fails. The browser tears the page down, and a request that is in flight may be cancelled before it leaves the machine.

This lesson explains why, and shows the two tools designed for the job: navigator.sendBeacon() and fetch() with the keepalive option. You will also learn the right event to listen to, the size limits, how to batch events into a queue, and what the server has to do. Basic fetch knowledge from Your First fetch Request and Sending Data is assumed.

The page-exit problem

Page closes Pending requests may be cancelled.
sendBeacon Queued for delivery by the browser.
keepalive fetch that outlives the page.
1 / 2

Why a normal fetch is not enough

When the user closes the tab, follows a link or reloads, the browser starts unloading the document. Any request that your script started but that has not been sent yet is aborted along with the page. Even if the request leaves, there is nobody left to read the response. Older code worked around this with a synchronous XMLHttpRequest in the unload handler, which froze the page while it waited. Browsers now block or discourage it, and it made navigation feel slow.

What you want is a request that:

  1. is handed to the browser to deliver even after the page is gone,
  2. does not block the user from leaving,
  3. does not need a response.

That is exactly what a beacon is.

JavaScript
const queued = navigator.sendBeacon(url, data);

sendBeacon makes a POST request to url with data as the body. It returns true if the browser accepted the request into its queue, and false if it did not (for example because the payload exceeded the limit). It does not tell you whether the server answered; the response is discarded.

The data can be a string, a Blob, FormData, URLSearchParams, an ArrayBuffer or a typed array. The Content-Type follows from the type: a string is sent as text/plain, a URLSearchParams as form-encoded, a FormData as multipart/form-data, and a Blob uses its own type. To send JSON with the right header, wrap it in a Blob:

JavaScript
const blob = new Blob([JSON.stringify({ page: location.pathname, ms: 4210 })], { type: "application/json" });
navigator.sendBeacon("/collect", blob);

Know the limits:

  • It is always POST. You cannot pick the method.
  • You cannot set custom headers (no Authorization header). Put a token in the body or in a cookie, which beacons send for same-site requests.
  • You cannot read the response.
  • The browser limits the total size of queued beacons, commonly 64 KB per page. A call that would go beyond the limit returns false.
  • A Blob with a type other than a simple one (such as application/json) makes a cross-origin beacon trigger a CORS preflight, which some browsers handle poorly. Same-origin endpoints avoid this problem.

fetch with keepalive

Newer code can use fetch() for the same job by adding keepalive: true. The request is allowed to outlive the page. Compared with a beacon, it gives you everything fetch normally does: any method (PUT, PATCH, DELETE), custom headers such as Authorization, and the ability to read the response while the page is still alive.

JavaScript
fetch("/api/session/end", {
  method: "POST",
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
  body: JSON.stringify({ ms: 4210 }),
  keepalive: true,
});

The same size budget applies: all in-flight keepalive requests together can carry only about 64 KB of body. Beyond that, the call rejects with a TypeError. Also, you cannot stream a request body with keepalive. If you do not need headers or other methods, sendBeacon is simpler and slightly more widely understood; if you do, use fetch with keepalive.

sendBeacon fetch + keepalive
Method always POST any
Custom headers no yes
Response discarded readable while the page lives
Returns true / false a promise
Size budget about 64 KB queued about 64 KB in flight
Best for analytics, logging authenticated saves and deletes

When to send: visibilitychange, not unload

The classic habit is window.addEventListener("unload", send). It is unreliable: on mobile browsers the page is often frozen or killed without firing unload, and having an unload handler stops the browser from keeping the page in its fast back/forward cache. beforeunload has the same problems, and also makes the browser show a confirmation if you misuse it.

The reliable signal is visibilitychange. It fires when the user switches tabs, minimizes the window, goes to the home screen or navigates away. When document.visibilityState becomes "hidden", send what you have:

JavaScript
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    flush();
  }
});

pagehide is a good second listener for older Safari versions. Do not remove your data after a flush as if the user were definitely leaving: they may come back to the tab, so keep collecting and flush again later.

A batching queue

Sending one beacon per click would waste the 64 KB budget and flood your server. Collect events in an array, flush on visibilitychange (and sometimes on a timer), and make the flush choose the best available transport.

JS An analytics queue with beacon and keepalive fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first flush sends all three events in one beacon. The oversized batch of 40 events is split in halves, recursively, until every piece fits the budget. A real queue would also retry failures when the user returns, and would cap how many events it keeps.

What the server must do

A beacon request has no response that anyone reads, so keep the endpoint fast and boring:

  • Read the body whatever its content type claims. A string beacon arrives as text/plain, so a JSON endpoint should parse the raw body (JSON.parse(request.body)) rather than insist on application/json.
  • Reply immediately with 204 No Content and do the heavy work later (queue it).
  • Validate and limit the data like any other input: an open /collect endpoint attracts junk. See Security for AJAX.
  • Expect duplicates (a user can hide and show the tab many times) and make the processing idempotent by including an event ID.
  • Do not rely on cookies alone for authentication of cross-site endpoints; same-site cookies may be withheld.

Other ways to save work on exit

  • Local drafts. For form drafts, save to localStorage while the user types (debounced). Nothing is lost whether or not a request succeeds, and you can sync later. This is the safest mechanism for user-written text.
  • Periodic autosave. A timer or a change event that saves in the background means the exit send is only the last few seconds.
  • Reporting APIs. Browsers also have a Reporting API and observers (such as PerformanceObserver and web vitals libraries) that use beacons internally; analytics libraries do the flush logic for you, so check before writing your own.
  • A newer option. Some browsers have fetchLater(), which asks the browser to send a request at a later time or when the page is discarded. It is not available everywhere yet, so feature-detect it before using it.

Common mistakes

Mistake Why it hurts Fix
Using unload to send not fired on mobile; blocks the back/forward cache use visibilitychange
await fetch(...) without keepalive in a handler the page may die first keepalive: true or sendBeacon
Sending a huge JSON in one beacon returns false / rejects batch and split at ~60 KB
Ignoring the boolean from sendBeacon silent data loss check it and fall back
Expecting a response body beacons discard it send fire-and-forget data only
Putting secrets in the URL URLs are logged keep tokens in the body or a cookie

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does navigator.sendBeacon() return?

    The beacon is fire-and-forget. The boolean only tells you whether the browser accepted it into its queue.
  2. 2. Which event is the most reliable place to send data when the user leaves?

    unload and beforeunload are unreliable (especially on mobile) and hurt the back/forward cache. visibilitychange fires in all the cases that matter.
  3. 3. When would you choose fetch with keepalive over sendBeacon?

    fetch with keepalive supports any method and headers. Both share a small total size budget.
  4. 4. A string passed to sendBeacon arrives at the server with which content type?

    A string body is sent as text/plain, so wrap JSON in a Blob with type application/json, or parse the raw body on the server.
  5. 5. What should the server answer to an analytics beacon?

    Nobody reads the response, so reply fast and process the data afterwards.

Summary

  • Requests started in an unload handler can be cancelled; use navigator.sendBeacon() or fetch(..., { keepalive: true }).
  • sendBeacon is a fire-and-forget POST with no custom headers and no readable response; keepalive fetch allows any method and headers.
  • Both share a small budget of about 64 KB, so batch events and split big payloads.
  • Send on visibilitychange to "hidden" (and pagehide as a backup), not on unload or beforeunload.
  • Make the endpoint quick and tolerant: accept the raw body, return 204, validate, and handle duplicates.

Next: see how to protect your requests in Security for AJAX.