A route change can make an in-flight request irrelevant. An AbortSignal communicates that cancellation to an asynchronous operation. Pass it through the functions that start work, rather than treating cancellation as an unrelated router or component concern. section 10.3.3 section 12.5
event.intercept({
async handler() {
const response = await fetch(`/api/products/${id}`, {
signal: event.signal
});
if (!response.ok) throw new Error("Failed to load product");
const product = await response.json();
renderProductPage(product);
}
});
Passing event.signal to fetch() ties the product request to its navigation. If another navigation supersedes it, the request is aborted automatically. section 10.3.3
Treat an expected abort differently from a failed request. An uncaught aborted fetch throws an error named AbortError and causes a navigateerror event. Catch that error in the route handler and return silently; show an error for other failures. section 10.3.3
The same signal pattern applies beyond route requests:
- Pass a signal to the original fetch() for a streaming response; aborting the request also stops reading its body. section 12.1.7
- Pass a component-owned controller’s signal to addEventListener() calls. A component can set listeners up on connection and abort them together on disconnection. section 13.2.7
Shared requests need a cancellation policy
A cache that stores an in-flight Promise lets two callers share one request. If the first caller supplied its signal and aborts, both callers awaiting that Promise fail. Independent cancellation requires reference counting around the underlying AbortController; do not assume a shared request gives each caller its own cancellation state. section 12.3
