PostHog/posthog-js

TypeError: Load failed when page is unloaded before posthog events are finished sending

Opened this issue · 2 comments

We are getting thousands of "TypeError: Load failed" errors in Sentry and this appears to be because PostHog has a request in flight while we are redirecting the user to an external URL.

It looks like this is because XMLHttpRequest is preferred over fetch.

posthog-js/src/request.ts

Lines 202 to 216 in 38744a5

// We add the transports in order of preference
if (XMLHttpRequest) {
AVAILABLE_TRANSPORTS.push({
transport: 'XHR',
method: xhr,
})
}
if (fetch) {
AVAILABLE_TRANSPORTS.push({
transport: 'fetch',
method: _fetch,
})
}

Indeed, XHR is the default transport:

const transport = options.transport ?? 'XHR'

From my understanding, XMLHttpRequest does not have a mechanism like keepalive that will not cancel the request when the page is unloaded.

Fetch is available on every major supported browser. Could fetch be made the default? If not, could an option be provided to make it the default for our instance?

Alternatively, it could be helpful to have a method that returns a promise that resolves when all the pending events have been sent so we can block the redirect on that request, but that seems unnecessary with keepalive.

Hey,

We're currently testing switching the default to fetch

If you set api_transport: 'fetch', then that's switch the default for you.

Oh dope. Thanks! I will do that!