Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/warm-birds-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'posthog-js': patch
---

fix: wrap sendBeacon body in Blob to ensure Content-Type header is set
12 changes: 8 additions & 4 deletions packages/browser/src/__tests__/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,11 +502,15 @@ describe('request', () => {

expect(mockedNavigator?.sendBeacon).toHaveBeenCalledWith(
'https://any.posthog-instance.com/?_=1700000000000&ver=1.23.45&compression=gzip-js&beacon=1',
expect.any(ArrayBuffer)
expect.any(Blob)
)
const arrayBuffer = mockedNavigator?.sendBeacon.mock.calls[0][1] as ArrayBuffer

const result = new TextDecoder().decode(arrayBuffer)
const blob = mockedNavigator?.sendBeacon.mock.calls[0][1] as Blob
expect(blob.type).toBe('text/plain')
const result = await new Promise<string>((resolve) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.readAsText(blob)
})

expect(result).toMatchInlineSnapshot(`
"��VJ��W�RJJ,R���+�
Expand Down
9 changes: 7 additions & 2 deletions packages/browser/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,13 @@ const _sendBeacon = (options: RequestWithOptions) => {

try {
const { contentType, body } = encodePostData(options) ?? {}
// sendBeacon requires a blob so we convert it
const sendBeaconBody = typeof body === 'string' ? new Blob([body], { type: contentType }) : body
if (!body) {
return
}
// sendBeacon requires a Blob to set the Content-Type header correctly.
// Without wrapping, ArrayBuffer bodies are sent with no Content-Type,
// which can cause issues with proxies/WAFs that require it.
const sendBeaconBody = body instanceof Blob ? body : new Blob([body], { type: contentType })
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does not interfer with #3172 cus this is sendBeacon transport only

navigator!.sendBeacon!(url, sendBeaconBody)
} catch {
// send beacon is a best-effort, fire-and-forget mechanism on page unload,
Expand Down
Loading