"fetch" supports a "keepAlive" option to make it outlive page navigations
- Published at
- Updated at
- Reading time
- 2min
This site used to use Umami as a self-hosted and privacy-first analytics tool. Meanwhile, I switched to a paid Plausible instance because I couldn't be bothered with the server maintenance, but that's another story...
An item in Umami's changelog caught my eye โ "Update tracker/index.js: SendBeacon() to Fetch API".
sendBeacon is a JavaScript method that sends POST requests to an analytics server. These requests are supposed to be async, not be canceled and outlive the current navigation. But apparently, sendBeacon is sometimes blocked by ad blockers.
| 39 | 42 | 14 | 31 | 31 | 11.1 | 11.1 | 4.0 | 40 |
That's not a big deal, though, because today I learned I can drop sendBeacon from my memory and use the fetch method with a keepalive option. ๐
await fetch(`${root}/api/collect`, {
method: 'POST',
body: data,
// keep request alive if the page is unloaded
// before the request is complete
keepalive: true,
});
What's the browser support? The upcoming Firefox 133 release moves keepalive into baseline territory.
| 66 | 66 | 15 | 133 | 133 | 13 | 13 | 9.0 | 66 |
fetch with a keepalive option has the same not-cancelable characteristics as sendBeacon and can act as its replacement. But it has the advantage that it's more flexible than sendBeacon. You're not limited to POST requests and can add headers if you want to. Nice!
Don't confuse the keepalive fetch attribute with the Keep-Alive HTTP header.
Join 6.1k readers and learn something new every week with Web Weekly.
