Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(web-analytics): Stop oversized replay snapshots crashing the browser (#77767)

Jordan Mryyan29852144db9e
diff --git a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
index ed7b51a52f49..80c3f271fb78 100644
--- a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
+++ b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
@@ -29,7 +29,11 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonBannerProps } from 'lib/lemon-ui/LemonBanner'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { objectsEqual } from 'lib/utils/objects'
-import { removeReplayIframeDataFromLocalStorage } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+import {
+ ReplayIframeData,
+ getStoredRecordingBackground,
+ removeReplayIframeDataFromLocalStorage,
+} from 'scenes/heatmaps/replayIframeData'
import { teamLogic } from 'scenes/teamLogic'
import { hogql } from '~/queries/utils'
@@ -90,14 +94,6 @@ export function preflightBannerMessage(preflight: PagePreflight | null): string
return null
}
-export interface ReplayIframeData {
- html: string
- width: number // NB this should be meta width
- height: number // NB this should be meta height
- startDateTime: string | undefined
- url: string | undefined
-}
-
// Helper function to detect if a URL contains regex pattern characters
export const isUrlPattern = (url: string): boolean => {
return /[*+?^${}()|[\]\\]/.test(url)
@@ -827,10 +823,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
},
'/heatmaps/recording': (_, searchParams) => {
if (searchParams.iframeStorage) {
- const replayFrameData = JSON.parse(
- localStorage.getItem(searchParams.iframeStorage) || '{}'
- ) as ReplayIframeData
- actions.setReplayIframeData(replayFrameData)
+ actions.setReplayIframeData(getStoredRecordingBackground(searchParams.iframeStorage))
}
},
})),
diff --git a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts
index f70c740f9ad8..b1bc9705e465 100644
--- a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts
+++ b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts
@@ -26,8 +26,8 @@ import type {
import type { CommonFilters } from '../../../lib/components/heatmaps/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'
+import type { ReplayIframeData } from '../replayIframeData'
import { heatmapsBrowserLogic, isUrlPattern } from './heatmapsBrowserLogic'
-import type { ReplayIframeData } from './heatmapsBrowserLogic'
export interface ClickmapBox {
top: number
diff --git a/frontend/src/scenes/heatmaps/replayIframeData.test.ts b/frontend/src/scenes/heatmaps/replayIframeData.test.ts
new file mode 100644
index 000000000000..7165c8ee2dbf
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/replayIframeData.test.ts
@@ -0,0 +1,61 @@
+import {
+ ReplayIframeData,
+ ReplayIframeDatakeyPrefix as PREFIX,
+ getStoredRecordingBackground,
+ persistReplayIframeData,
+} from './replayIframeData'
+
+describe('replayIframeData', () => {
+ const data: ReplayIframeData = {
+ html: '<body>snapshot</body>',
+ width: 100,
+ height: 200,
+ startDateTime: undefined,
+ url: 'https://e',
+ }
+
+ const prefixedKeys = (): string[] => Object.keys(localStorage).filter((k) => k.startsWith(PREFIX))
+
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('prunes older snapshots once the new one is written', () => {
+ localStorage.setItem(`${PREFIX}stale`, '{}')
+
+ const key = persistReplayIframeData(data)
+
+ expect(key).not.toBeNull()
+ expect(prefixedKeys()).toEqual([key])
+ expect(getStoredRecordingBackground(key)).toEqual(data)
+ })
+
+ it('keeps the previous snapshot when the write is rejected', () => {
+ localStorage.setItem(`${PREFIX}previous`, '{"html":"<body>old</body>"}')
+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new DOMException('quota', 'QuotaExceededError')
+ })
+
+ expect(persistReplayIframeData(data)).toBeNull()
+ expect(prefixedKeys()).toEqual([`${PREFIX}previous`])
+ })
+
+ it.each([
+ ['malformed json', '{not json'],
+ ['a snapshot missing its dimensions', '{"html":"<body>x</body>"}'],
+ ['a blank snapshot', '{"html":" ","width":1,"height":2}'],
+ ])('reads %s as null', (_name, stored) => {
+ localStorage.setItem('stored', stored)
+
+ expect(getStoredRecordingBackground('stored')).toBeNull()
+ })
+
+ it('reads an absent snapshot as null', () => {
+ expect(getStoredRecordingBackground(null)).toBeNull()
+ expect(getStoredRecordingBackground('never-written')).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/heatmaps/replayIframeData.ts b/frontend/src/scenes/heatmaps/replayIframeData.ts
new file mode 100644
index 000000000000..bffcde7adda8
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/replayIframeData.ts
@@ -0,0 +1,54 @@
+import { z } from 'zod'
+
+import { uuid } from 'lib/utils/dom'
+import { localStorageSlot } from 'lib/utils/localStorageSlot'
+
+export interface ReplayIframeData {
+ html: string
+ width: number // NB this should be meta width
+ height: number // NB this should be meta height
+ startDateTime: string | undefined
+ url: string | undefined
+}
+
+export const ReplayIframeDatakeyPrefix = 'ph_replay_fixed_heatmap_'
+
+// Serializing the replayed DOM allocates several full copies of this on the main thread, in a tab
+// that is already holding a decoded recording. Past roughly this size that spike is what kills the
+// renderer.
+export const MAX_REPLAY_IFRAME_HTML_CHARS = 2_000_000
+
+const replayIframeDataSchema = z.object({
+ html: z.string().refine((html) => !!html.trim()),
+ width: z.number(),
+ height: z.number(),
+ startDateTime: z.union([z.string(), z.undefined()]),
+ url: z.union([z.string(), z.undefined()]),
+})
+
+export function removeReplayIframeDataFromLocalStorage(exceptKey?: string): void {
+ for (let i = localStorage.length - 1; i >= 0; i--) {
+ const key = localStorage.key(i)
+ if (key?.startsWith(ReplayIframeDatakeyPrefix) && key !== exceptKey) {
+ localStorage.removeItem(key)
+ }
+ }
+}
+
+export function persistReplayIframeData(data: ReplayIframeData): string | null {
+ const key = ReplayIframeDatakeyPrefix + uuid()
+ try {
+ localStorage.setItem(key, JSON.stringify(data))
+ } catch {
+ return null
+ }
+ // prune only after a successful write, so a failed write leaves the previous key usable
+ removeReplayIframeDataFromLocalStorage(key)
+ return key
+}
+
+// a missing or malformed snapshot must resolve to null rather than throwing, so callers land on the
+// recording fallback instead of unwinding out of a router listener with the scene half-mounted
+export function getStoredRecordingBackground(storageKey: string | null): ReplayIframeData | null {
+ return storageKey ? localStorageSlot(storageKey, replayIframeDataSchema).get() : null
+}
diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
index 2105d1773265..5b31b5a45600 100644
--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts
@@ -24,7 +24,8 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
-import { ReplayIframeData, heatmapsBrowserLogic, isUrlPattern } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
+import { heatmapsBrowserLogic, isUrlPattern } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
+import { ReplayIframeData, getStoredRecordingBackground } from 'scenes/heatmaps/replayIframeData'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -129,27 +130,6 @@ export function getBackgroundStepBlockReason({
return null
}
-export function getStoredRecordingBackground(storageKey: string | null): ReplayIframeData | null {
- if (!storageKey) {
- return null
- }
- try {
- const data = JSON.parse(localStorage.getItem(storageKey) ?? 'null') as Partial<ReplayIframeData> | null
- if (
- !data ||
- typeof data.html !== 'string' ||
- !data.html.trim() ||
- typeof data.width !== 'number' ||
- typeof data.height !== 'number'
- ) {
- return null
- }
- return data as ReplayIframeData
- } catch {
- return null
- }
-}
-
export function getAuthorizationOrigin(url: string | null): string | null {
if (!url) {
return null
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index 4a77924e3b69..ce3da9eb7b9d 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -37,11 +37,15 @@ import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { dayjs, now } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { findLastIndex } from 'lib/utils/arrays'
-import { downloadFile, uuid } from 'lib/utils/dom'
+import { downloadFile } from 'lib/utils/dom'
import { clamp } from 'lib/utils/numbers'
import { objectsEqual } from 'lib/utils/objects'
import { openBillingPopupModal } from 'scenes/billing/BillingPopup'
-import { ReplayIframeData } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
+import {
+ MAX_REPLAY_IFRAME_HTML_CHARS,
+ ReplayIframeData,
+ persistReplayIframeData,
+} from 'scenes/heatmaps/replayIframeData'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { playerCommentModel } from 'scenes/session-recordings/player/commenting/playerCommentModel'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
@@ -153,8 +157,6 @@ export interface SessionRecordingPlayerLogicProps extends SessionRecordingDataCo
skipToFirstMatchingEvent?: boolean
}
-const ReplayIframeDatakeyPrefix = 'ph_replay_fixed_heatmap_'
-
// Positions less than this far before the next FullSnapshot are treated as
// renderable: recordings routinely start a few ms before their first
// FullSnapshot (the recording start is min(event start, snapshot start)) and
@@ -218,19 +220,6 @@ const trackingStateMap: Record<SessionPlayerState, PlayerTimeTracking['state']>
const isMediaElementPlaying = (element: HTMLMediaElement): boolean =>
!!(element.currentTime > 0 && !element.paused && !element.ended && element.readyState > 2)
-function removeFromLocalStorageWithPrefix(prefix: string): void {
- for (let i = localStorage.length - 1; i >= 0; i--) {
- const key = localStorage.key(i)
- if (key?.startsWith(prefix)) {
- localStorage.removeItem(key)
- }
- }
-}
-
-export function removeReplayIframeDataFromLocalStorage(): void {
- removeFromLocalStorageWithPrefix(ReplayIframeDatakeyPrefix)
-}
-
const NOSCRIPT_BLOCK_RE = /<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi
/**
@@ -244,6 +233,18 @@ export function stripRrwebScriptShims(html: string): string {
return html.replace(NOSCRIPT_BLOCK_RE, '')
}
+const SNAPSHOT_REJECTION_PROBLEM = {
+ too_large: 'This part of the recording is too large to use as a heatmap background.',
+ storage_failed: "Couldn't save this moment as a heatmap background.",
+} as const
+
+function rejectHeatmapSnapshot(reason: keyof typeof SNAPSHOT_REJECTION_PROBLEM, htmlChars: number): void {
+ posthog.capture('in-app heatmap background snapshot rejected', { reason, html_chars: htmlChars })
+ lemonToast.error(
+ `${SNAPSHOT_REJECTION_PROBLEM[reason]} Try a different moment, or create a heatmap from the page URL instead.`
+ )
+}
+
/**
* returns the relative second in the recording
* e.g. if the player starts at 1000ms and the snapshot is at 2000ms or 1500ms, the relative second is 1
@@ -3099,16 +3100,25 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
return
}
- removeFromLocalStorageWithPrefix(ReplayIframeDatakeyPrefix)
- const key = ReplayIframeDatakeyPrefix + uuid()
+ const html = stripRrwebScriptShims(rawIframeHtml)
+ const htmlChars = html.length
+ if (htmlChars > MAX_REPLAY_IFRAME_HTML_CHARS) {
+ rejectHeatmapSnapshot('too_large', htmlChars)
+ return
+ }
+
const data: ReplayIframeData = {
- html: stripRrwebScriptShims(rawIframeHtml),
+ html,
width: resolution.width,
height: resolution.height,
startDateTime: values.sessionPlayerMetaData?.start_time,
url: values.currentURL,
}
- localStorage.setItem(key, JSON.stringify(data))
+ const key = persistReplayIframeData(data)
+ if (!key) {
+ rejectHeatmapSnapshot('storage_failed', htmlChars)
+ return
+ }
const modalLogic = sessionPlayerModalLogic.findMounted()
if (modalLogic?.values.modalContext?.type === 'heatmap-background-selection') {
modalLogic.actions.completeHeatmapBackgroundSelection(key)