PostHog / posthog-js

Send usage data from your web app or site to PostHog, with autocapture.
https://posthog.com/docs/libraries/js
Other
285 stars 121 forks source link

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

Open davidbarratt opened 6 hours ago

davidbarratt commented 6 hours ago

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. https://github.com/PostHog/posthog-js/blob/38744a512abef2f4eb7327e7a3c23d184c3993ca/src/request.ts#L202-L216

Indeed, XHR is the default transport: https://github.com/PostHog/posthog-js/blob/38744a512abef2f4eb7327e7a3c23d184c3993ca/src/request.ts#L237

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.

pauldambra commented 6 hours ago

Hey,

We're currently testing switching the default to fetch

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

davidbarratt commented 6 hours ago

Oh dope. Thanks! I will do that!