Skip to content

Commit aa30782

Browse files
authored
feat(browser): Use fetch keepalive flag (#5697)
1 parent 549370c commit aa30782

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

packages/browser/src/transports/fetch.ts

+10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ export function makeFetchTransport(
1717
method: 'POST',
1818
referrerPolicy: 'origin',
1919
headers: options.headers,
20+
// Outgoing requests are usually cancelled when navigating to a different page, causing a "TypeError: Failed to
21+
// fetch" error and sending a "network_error" client-outcome - in Chrome, the request status shows "(cancelled)".
22+
// The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're
23+
// frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).
24+
// Gotchas:
25+
// - `keepalive` isn't supported by Firefox
26+
// - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch), a request with `keepalive: true`
27+
// and a content length of > 64 kibibytes returns a network error. We will therefore only activate the flag when
28+
// we're below that limit.
29+
keepalive: request.body.length <= 65536,
2030
...options.fetchOptions,
2131
};
2232

packages/browser/test/unit/transports/fetch.test.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ describe('NewFetchTransport', () => {
4444
expect(mockFetch).toHaveBeenLastCalledWith(DEFAULT_FETCH_TRANSPORT_OPTIONS.url, {
4545
body: serializeEnvelope(ERROR_ENVELOPE, new TextEncoder()),
4646
method: 'POST',
47+
keepalive: true,
4748
referrerPolicy: 'origin',
4849
});
4950
});
@@ -81,7 +82,7 @@ describe('NewFetchTransport', () => {
8182

8283
const REQUEST_OPTIONS: RequestInit = {
8384
referrerPolicy: 'strict-origin',
84-
keepalive: true,
85+
keepalive: false,
8586
referrer: 'http://example.org',
8687
};
8788

0 commit comments

Comments
 (0)