AJAX - Using the Fetch Keepalive Option for Background Data Submission
1. Introduction
In modern web applications, users frequently perform actions such as submitting forms, saving information, updating preferences, and sending analytics data. Sometimes, these operations need to continue even when the user navigates to another webpage, closes a tab, or moves away from the current page. Normally, when a browser page is unloaded, ongoing network requests may be interrupted or cancelled. This can result in incomplete data submission or loss of important information.
The Fetch API provides a special option called keepalive that helps address this problem. It allows certain network requests to continue even after the webpage that initiated them has started unloading. By setting keepalive: true in a Fetch request, developers can allow the browser to complete small data submissions without depending on the continued presence of the original webpage.
This feature is particularly useful for submitting analytics information, recording user activity, saving small amounts of application data, and sending final status updates to a server.
2. What Is the Fetch Keepalive Option?
The Fetch Keepalive option is a feature of the JavaScript Fetch API that allows a network request to remain active during page navigation or unloading.
Normally, when a user leaves a webpage, the browser may terminate requests that are still in progress. However, when the keepalive option is enabled, the browser attempts to complete the request even if the page is no longer active.
The option is specified inside the Fetch API configuration object.
Syntax:
fetch("https://example.com/api/activity", {
method: "POST",
keepalive: true,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
activity: "User left the page"
})
});
In this example:
-
fetch()sends a request to the specified server endpoint. -
method: "POST"indicates that information is being submitted. -
keepalive: trueallows the request to continue during page unloading. -
headersspecify the format of the submitted information. -
bodycontains the data being sent to the server.
The browser attempts to deliver the request even after the webpage has started closing or navigating elsewhere.
3. Why Is the Keepalive Option Important?
Without the Keepalive option, applications may lose important information when users leave a webpage before a network request finishes.
Consider an online shopping website where a customer adds products to a cart and then navigates to another page. The application may need to send an event to the server indicating that the customer has left the current page or abandoned the shopping session.
If the request is interrupted during navigation, the server may not receive the information.
The Keepalive option helps reduce this possibility by allowing suitable requests to continue during page unloading.
Its importance includes:
-
Improved data submission: Helps complete small data submissions when users leave a webpage.
-
Reliable analytics collection: Allows applications to send final browsing activity information.
-
Reduced data loss: Helps prevent important information from being lost during page navigation.
-
Better application monitoring: Supports the submission of final application status updates.
-
Improved user experience: Reduces the need to interrupt users with unnecessary confirmation messages.
4. How Does Fetch Keepalive Work?
The Keepalive option works by allowing the browser to maintain a request independently of the continued activity of the webpage that initiated it.
The process generally follows these steps:
Step 1: User performs an action
A user visits a webpage, interacts with its content, or completes an activity.
Step 2: Application prepares information
JavaScript collects the necessary information, such as user activity, form details, or session status.
Step 3: Fetch request is created
The application creates a Fetch API request and enables the Keepalive option.
Step 4: Browser sends the request
The browser sends the information to the specified server endpoint.
Step 5: User leaves the webpage
The user navigates to another page or closes the current tab.
Step 6: Request continues
The browser attempts to complete the request even though the original webpage is unloading.
Step 7: Server processes the information
If the request reaches the server successfully, the server processes and stores the submitted information.
5. Practical Example of Fetch Keepalive
Consider a website that tracks when users leave a particular webpage. The application needs to send an activity notification to the server when the user navigates away.
The following example demonstrates how to implement this functionality.
window.addEventListener("pagehide", function () {
const activityData = {
event: "page_exit",
page: window.location.href,
timestamp: new Date().toISOString()
};
fetch("/api/activity", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(activityData),
keepalive: true
});
});
In this example, the pagehide event is triggered when the browser hides the current document, including during navigation.
The application collects the page URL, event information, and timestamp. It then sends this information to the server using a POST request with keepalive: true.
The browser attempts to complete the request even after the page begins unloading.
This approach is useful for collecting final activity information without requiring the user to remain on the webpage.
6. Difference Between Fetch Keepalive and Normal Fetch Requests
Both normal Fetch requests and Fetch requests with Keepalive enabled are used to communicate with servers. However, they differ in how they behave when the webpage is unloaded.
|
Feature |
Normal Fetch |
Fetch with Keepalive |
|---|---|---|
|
Request submission |
Sends data to a server |
Sends data to a server |
|
Page navigation |
Request may be interrupted |
Browser attempts to continue the request |
|
Page unloading |
Not specifically designed for this situation |
Designed to support requests during unloading |
|
Data submission |
Suitable for regular application operations |
Suitable for small final data submissions |
|
Response handling |
Can process the response normally |
Response may not be available to the original page after unloading |
|
Common applications |
Loading records and submitting forms |
Analytics and final activity updates |
The Keepalive option does not guarantee successful delivery. It only allows the browser to make an effort to complete the request after the page begins unloading.
7. Limitations of the Fetch Keepalive Option
Although Fetch Keepalive is useful, developers must understand its limitations before using it in applications.
Request Size Restrictions: Keepalive requests have a limited amount of data that can remain in flight. The combined body size of outstanding keepalive requests is generally limited to 64 KiB per browser context. Therefore, it is not suitable for uploading large files or transferring large datasets.
No Guaranteed Delivery: Enabling Keepalive does not guarantee that the server will receive the request. Network failures, browser restrictions, and server errors can still prevent successful submission.
Limited Response Processing: If the webpage has already been unloaded, the original JavaScript environment may no longer be available to process the server response.
Not Suitable for Large Transactions: Important operations involving large amounts of information should use more reliable application-level mechanisms rather than depending entirely on Keepalive.
Browser Support Considerations: Modern browsers support the Fetch Keepalive option, but developers should test their applications across the browsers and environments they intend to support.
8. Real-World Applications of Fetch Keepalive
Fetch Keepalive is useful in several practical web development situations.
Website Analytics: Websites can submit information about page visits, navigation events, and user interactions when visitors leave a webpage.
Online Shopping Applications: Shopping websites can send small session updates when customers navigate away from product or checkout pages.
User Activity Monitoring: Applications can record the time when users leave a page or complete a particular activity.
Learning Management Systems: Educational platforms can submit small progress updates when students navigate away from lessons.
Business Applications: Enterprise applications can send final status information when users close or leave a particular working page.
9. Best Practices for Using Fetch Keepalive
Developers should follow certain practices to use the Keepalive option effectively.
-
Use Keepalive primarily for small data submissions that should continue during page unloading.
-
Avoid using it for large file uploads or lengthy data transfers.
-
Use the
pagehideevent when handling page navigation and unloading-related activities. -
Ensure that the server endpoint can process repeated requests safely.
-
Avoid collecting unnecessary personal information when tracking user activity.
-
Use HTTPS to protect information transmitted between the browser and server.
-
Implement appropriate error-handling and server-side logging mechanisms.
-
Test the functionality across different browsers and network conditions.
For critical information that must be reliably stored, applications should use additional mechanisms such as persistent local storage, IndexedDB, or server-side confirmation and retry strategies.
10. Conclusion
The Fetch Keepalive option is an important feature of modern JavaScript web development that helps applications submit small amounts of information even when users navigate away from a webpage or close a browser tab. By setting keepalive: true, developers allow the browser to attempt to complete network requests independently of the original page's continued activity.
It is especially useful for website analytics, session updates, user activity tracking, and final application status submissions. However, developers must understand its limitations, particularly regarding request size, response processing, and delivery guarantees.
By using Fetch Keepalive appropriately, developers can build more dependable web applications that reduce the loss of important information during page navigation and unloading.