Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Keepalive requests

Blue Mousec32bdc770b89
diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.ts
index 046a3d847..7dfc38fcb 100644
--- a/packages/tracker-js/src/Lib.ts
+++ b/packages/tracker-js/src/Lib.ts
@@ -1553,12 +1553,17 @@ export class Lib {
private async sendRequest(path: string, body: object): Promise<void> {
const host = this.options?.apiURL || DEFAULT_API_HOST
+ const payload = JSON.stringify(body)
await fetch(`${host}/${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
- body: JSON.stringify(body),
+ // Lets the request survive page unloads (e.g. tracking an outbound
+ // link click). Browsers reject keepalive bodies over ~64 KB, so
+ // oversized payloads fall back to a regular request.
+ keepalive: payload.length < 60_000,
+ body: payload,
})
}
}
diff --git a/packages/tracker-js/tests/sendRequest.test.ts b/packages/tracker-js/tests/sendRequest.test.ts
new file mode 100644
index 000000000..c429e9736
--- /dev/null
+++ b/packages/tracker-js/tests/sendRequest.test.ts
@@ -0,0 +1,45 @@
+/// <reference types="jest" />
+
+import { Lib } from '../src/Lib'
+import { setLocation } from './testUtils'
+
+const PROJECT_ID = 'test-project-id'
+
+describe('sendRequest keepalive', () => {
+ let fetchMock: jest.Mock
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ setLocation({ hostname: 'example.com', pathname: '/test-page' })
+
+ fetchMock = jest.fn().mockResolvedValue({ ok: true })
+ Object.defineProperty(globalThis, 'fetch', {
+ value: fetchMock,
+ writable: true,
+ configurable: true,
+ })
+ })
+
+ test('track() sends events with keepalive so they survive page unloads', async () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+
+ await lib.track({ ev: 'outbound_link_click' })
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [, options] = fetchMock.mock.calls[0]
+ expect(options.keepalive).toBe(true)
+ })
+
+ test('oversized payloads fall back to a regular request', async () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+
+ await lib.track({
+ ev: 'big_event',
+ meta: { blob: 'x'.repeat(70_000) },
+ })
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [, options] = fetchMock.mock.calls[0]
+ expect(options.keepalive).toBe(false)
+ })
+})