Capacitor HTTP request cancellation and timeout configuration
0 reputation · 15 Mar 2025, 13:07 UTC
0 reputation · 15 Mar 2025, 13:07 UTC
Ionic applications utilizing the Capacitor HTTP plugin to bypass CORS and improve performance rely on native bridge calls for network operations. While this provides native performance, it introduces a discrepancy in how asynchronous requests are managed compared to the standard browser Fetch API.
A primary challenge arises when implementing strict timeout policies or canceling pending requests during component destruction. Because Capacitor HTTP operates outside the standard browser XHR/Fetch lifecycle, AbortController may not consistently terminate the underlying native network task on iOS or Android.
There is uncertainty regarding the most reliable way to ensure native resources are released when a user navigates away from a page before a large payload is received.
Promise.race()?32275 reputation · 16 Mar 2025, 00:19 UTC
Capacitor HTTP does not expose a stable cancel API that accepts a request ID. The plugin’s request methods return a Promise; there is no cancel or requestId property that can be used to abort a pending native task from JavaScript.
The only timeout knobs available in the current Capacitor HTTP plugin are connectTimeout and readTimeout. connectTimeout limits the time spent establishing the TCP connection; readTimeout limits the time the socket can sit idle while data is being transferred. These values are applied per request and are the only way to bound the amount of native work that will be performed.
Promise.race is insufficientUsing Promise.race with a JavaScript timer only rejects the promise that you await. The underlying native HTTP call keeps running on the device and may finish after the user has navigated away, consuming bandwidth and battery. It does not free the native socket or cancel the network operation.
connectTimeout and readTimeout values that match the expected network conditions. For large payloads increase readTimeout; for slow networks increase connectTimeout.fetch API and use AbortController, or implement a small native plugin that keeps a reference to the native request and exposes a cancel(id) method.Does the endpoint you are calling need the Capacitor HTTP plugin to bypass CORS, or can you use a standard fetch call with proper CORS headers? The answer to that question determines whether you must rely on native timeouts or can use AbortController for true cancellation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.