How to Ensure HTTP Requests Complete When Users Leave a Page
This article explains why browsers cancel pending requests during navigation, the risks of lost data, and demonstrates reliable solutions using JavaScript—first by awaiting fetch, then leveraging the fetch keepalive option—to guarantee logs reach the server without delaying page loads.
When a user navigates away from a page, browsers often cancel any pending HTTP requests, so data such as logs may never reach the server.
The reliability of these requests depends on network speed, server response time, and browser behavior, which can cause data loss for analytics.
One approach is to prevent the default navigation, send the request with fetch, await its completion, and then manually trigger the navigation.
document.getElementById('link').addEventListener('click', async (e) => {
e.preventDefault();
await fetch("/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: 'FedJavaScript' })
});
window.location = e.target.href;
});However, waiting for the request can introduce noticeable latency, especially on mobile devices.
Modern browsers support the keepalive option in fetch, which allows the request to continue in the background even after the page starts unloading, eliminating the need to block navigation.
document.getElementById('link').addEventListener('click', (e) => {
fetch("/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: 'FedJavaScript' }),
keepalive: true
});
});Using keepalive ensures that logging data is reliably sent without affecting user experience.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
