Skip to content

Commit f7036c0

Browse files
committed
fix(core): consume response body in _flush() and _capture() to prevent Cloudflare Workers warnings
`_flush()` and the single-event `_capture()` path both call `fetchWithRetry()` but discard the returned response without reading the body. In runtimes like Cloudflare Workers that enforce response body consumption, this causes cross-request promise resolution warnings and may silently cancel post-flush error handling continuations. Consume the response body with `res.text().catch(() => {})` at both call sites on the success path. Also consume the response body held by `PostHogFetchHttpError` on error paths (e.g. 413 batch-size reduction) to prevent the same leak on failed requests. The `fetchWithRetry()` return type is preserved so callers that need the response (e.g. surveys API) can still read it. Fixes #3173
1 parent dc59f94 commit f7036c0

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

packages/core/src/posthog-core-stateless.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -964,8 +964,16 @@ export abstract class PostHogCoreStateless {
964964
}
965965

966966
try {
967-
await this.fetchWithRetry(url, fetchOptions)
967+
const res = await this.fetchWithRetry(url, fetchOptions)
968+
// Consume the response body to prevent resource leaks in runtimes like
969+
// Cloudflare Workers that require the body to be read before the handler completes.
970+
// See: https://github.com/PostHog/posthog-js/issues/3173
971+
await res.text().catch(() => {})
968972
} catch (err) {
973+
// Consume the error response body to prevent resource leaks (see #3173)
974+
if (err instanceof PostHogFetchHttpError) {
975+
await err.response.text().catch(() => {})
976+
}
969977
this._events.emit('error', err)
970978
}
971979
}
@@ -1139,8 +1147,17 @@ export abstract class PostHogCoreStateless {
11391147
}
11401148

11411149
try {
1142-
await this.fetchWithRetry(url, fetchOptions, retryOptions)
1150+
const res = await this.fetchWithRetry(url, fetchOptions, retryOptions)
1151+
// Consume the response body to prevent resource leaks in runtimes like
1152+
// Cloudflare Workers that require the body to be read before the handler completes.
1153+
// See: https://github.com/PostHog/posthog-js/issues/3173
1154+
await res.text().catch(() => {})
11431155
} catch (err) {
1156+
// Consume the error response body to prevent resource leaks (see #3173)
1157+
if (err instanceof PostHogFetchHttpError) {
1158+
await err.response.text().catch(() => {})
1159+
}
1160+
11441161
if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
11451162
// if we get a 413 error, we want to reduce the batch size and try again
11461163
this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2))

0 commit comments

Comments
 (0)