Skip to content

fix(browser-utils): Ensure web vital client hooks unsubscribe correctly #17272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2025
Merged
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
14 changes: 11 additions & 3 deletions packages/browser-utils/src/metrics/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,13 +226,21 @@ export function listenForWebVitalReportEvents(
// we only want to collect LCP if we actually navigate. Redirects should be ignored.
if (!options?.isRedirect) {
_runCollectorCallbackOnce('navigation');
unsubscribeStartNavigation?.();
unsubscribeAfterStartPageLoadSpan?.();
safeUnsubscribe(unsubscribeStartNavigation, unsubscribeAfterStartPageLoadSpan);
}
});

const unsubscribeAfterStartPageLoadSpan = client.on('afterStartPageLoadSpan', span => {
pageloadSpanId = span.spanContext().spanId;
unsubscribeAfterStartPageLoadSpan?.();
safeUnsubscribe(unsubscribeAfterStartPageLoadSpan);
});
}

/**
* Invoke a list of unsubscribers in a safe way, by deferring the invocation to the next tick.
* This is necessary because unsubscribing in sync can lead to other callbacks no longer being invoked
* due to in-place array mutation of the subscribers array on the client.
*/
function safeUnsubscribe(...unsubscribers: (() => void | undefined)[]): void {
unsubscribers.forEach(u => u && setTimeout(u, 0));
}
Loading