: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(frontend): defer authenticated shell to lazy chunk (#58095)
Paul D'Ambra32801ab30616
diff --git a/common/storybook/.storybook/decorators/withKea/kea-story.tsx b/common/storybook/.storybook/decorators/withKea/kea-story.tsxindex 23e3f81db472..9ec88241e56c 100644--- a/common/storybook/.storybook/decorators/withKea/kea-story.tsx+++ b/common/storybook/.storybook/decorators/withKea/kea-story.tsx@@ -5,6 +5,12 @@ import { useEffect, useState } from 'react'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { App } from 'scenes/App'+// Eagerly bring AuthenticatedShell into the storybook bundle. App.tsx code-splits+// it via React.lazy in production, but storybook tests render scenes outside the+// App tree where the lazy chunk would never load - and several scene stories rely+// on module-level side effects from imports inside the shell (kea connect chains,+// CSS, decorators) being present at evaluation time.+import 'scenes/AuthenticatedShell'import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex de1d74274a08..e94e5767f620 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -15,11 +15,22 @@ import { App } from 'scenes/App'import { initKea } from './initKea'import { ErrorBoundary } from './layout/ErrorBoundary'import { loadPostHogJS } from './loadPostHogJS'-import { preWarmDecompression } from './scenes/session-recordings/player/snapshot-processing/DecompressionWorkerManager'loadPostHogJS()initKea()-preWarmDecompression()++const idle =+ typeof window !== 'undefined' && typeof window.requestIdleCallback === 'function'+ ? window.requestIdleCallback.bind(window)+ : (cb: () => void) => setTimeout(cb, 200)++idle(() => {+ void import('./scenes/session-recordings/player/snapshot-processing/DecompressionWorkerManager')+ .then(({ preWarmDecompression }) => preWarmDecompression())+ .catch((error) => {+ console.warn('[index] Failed to load DecompressionWorkerManager for pre-warm:', error)+ })+})// On Chrome + Windows, the country flag emojis don't render correctly. This is a polyfill for that.// It won't be applied on other platforms.diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex 1874e9985b55..751eea73f93d 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -1,31 +1,25 @@import { BindLogic, useMountedLogic, useValues } from 'kea'+import React, { Suspense, useEffect } from 'react'import { Slide, ToastContainer } from 'react-toastify'-import { Command } from 'lib/components/Command/Command'-import { globalSetupLogic, useSetupHighlight } from 'lib/components/ProductSetup'-import { FEATURE_FLAGS, MOCK_NODE_PROCESS } from 'lib/constants'+import { MOCK_NODE_PROCESS } from 'lib/constants'import { useCancelAnimationsOnUnmount } from 'lib/hooks/useCancelAnimationsOnUnmount'import { useThemedHtml } from 'lib/hooks/useThemedHtml'import { KeaDevtools } from 'lib/KeaDevTools'import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'-import { apiStatusLogic } from 'lib/logic/apiStatusLogic'-import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'-import { PostOnboardingModal } from 'scenes/onboarding/PostOnboardingModal'-import { postOnboardingModalLogic } from 'scenes/onboarding/postOnboardingModalLogic'import { sceneLogic } from 'scenes/sceneLogic'import { userLogic } from 'scenes/userLogic'import { ErrorBoundary } from '~/layout/ErrorBoundary'-import { GlobalModals } from '~/layout/GlobalModals'-import { GlobalShortcuts } from '~/layout/GlobalShortcuts'-import { Navigation } from '~/layout/navigation-3000/Navigation'import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'-import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'++import { ChunkLoadErrorBoundary } from './ChunkLoadErrorBoundary'++const AuthenticatedShell = React.lazy(() => import('./AuthenticatedShell'))window.process = MOCK_NODE_PROCESS@@ -56,10 +50,6 @@ export function App(): JSX.Element | null {const { showApp, showingDelayedSpinner, showingDevTools } = useValues(appLogic)useMountedLogic(sceneLogic({ scenes: appScenes }))- useMountedLogic(apiStatusLogic)- useMountedLogic(eventIngestionRestrictionLogic)- useMountedLogic(globalSetupLogic)- useMountedLogic(postOnboardingModalLogic)useThemedHtml()@@ -76,7 +66,6 @@ export function App(): JSX.Element | null {}function AppScene(): JSX.Element | null {- useMountedLogic(breadcrumbsLogic)const { user } = useValues(userLogic)const {activeSceneId,@@ -86,14 +75,27 @@ function AppScene(): JSX.Element | null {sceneConfig,} = useValues(sceneLogic)const { showingDelayedSpinner } = useValues(appLogic)-- const { featureFlags } = useValues(featureFlagLogic)const { isDarkModeOn } = useValues(themeLogic)- // Highlight any relevant element after navigation from the quick start guide- useSetupHighlight()-- const toastContainer = (+ // Once we know the user is authenticated, kick off an idle prefetch of the+ // AuthenticatedShell chunk so the Suspense fallback rarely actually fires+ // when the shell mounts. No-op on prefetch failure — Suspense still works.+ useEffect(() => {+ if (!user) {+ return+ }+ const idle =+ typeof window.requestIdleCallback === 'function'+ ? window.requestIdleCallback.bind(window)+ : (cb: () => void) => setTimeout(cb, 200)+ idle(() => {+ void import('./AuthenticatedShell').catch(() => {+ /* prefetch is best-effort; the real Suspense load will surface failures */+ })+ })+ }, [user])++ const unauthToastContainer = (<ToastContainerautoClose={6000}transition={Slide}@@ -138,23 +140,22 @@ function AppScene(): JSX.Element | null {return sceneConfig?.onlyUnauthenticated || sceneConfig?.allowUnauthenticated ? (<>{wrappedSceneElement}- {toastContainer}+ {unauthToastContainer}</>) : null}return (- <div className="contents isolate">- <Navigation sceneConfig={sceneConfig}>{wrappedSceneElement}</Navigation>- {toastContainer}- <GlobalModals />- <GlobalShortcuts />- <Command />- <PostOnboardingModal />- <ImpersonationNotice />- {featureFlags[FEATURE_FLAGS.EXPERIMENTS_DW_AA_TEST] === 'test' && (- <div data-attr="experiments-dw-aa-test-variant" className="hidden" />- )}- </div>+ <ChunkLoadErrorBoundary>+ <Suspense+ fallback={+ <WrappingLoadingSkeleton fullWidth>+ <span className="block w-full h-screen" />+ </WrappingLoadingSkeleton>+ }+ >+ <AuthenticatedShell>{wrappedSceneElement}</AuthenticatedShell>+ </Suspense>+ </ChunkLoadErrorBoundary>)}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxnew file mode 100644index 000000000000..7ea2adaa718c--- /dev/null+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -0,0 +1,57 @@+import { useMountedLogic, useValues } from 'kea'+import { Slide, ToastContainer } from 'react-toastify'++import { Command } from 'lib/components/Command/Command'+import { globalSetupLogic, useSetupHighlight } from 'lib/components/ProductSetup'+import { FEATURE_FLAGS } from 'lib/constants'+import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'+import { apiStatusLogic } from 'lib/logic/apiStatusLogic'+import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { PostOnboardingModal } from 'scenes/onboarding/PostOnboardingModal'+import { postOnboardingModalLogic } from 'scenes/onboarding/postOnboardingModalLogic'++import { GlobalModals } from '~/layout/GlobalModals'+import { GlobalShortcuts } from '~/layout/GlobalShortcuts'+import { Navigation } from '~/layout/navigation-3000/Navigation'+import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'+import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'++import { sceneLogic } from './sceneLogic'++export default function AuthenticatedShell({ children }: { children: React.ReactNode }): JSX.Element {+ useMountedLogic(apiStatusLogic)+ useMountedLogic(eventIngestionRestrictionLogic)+ useMountedLogic(breadcrumbsLogic)+ useMountedLogic(globalSetupLogic)+ useMountedLogic(postOnboardingModalLogic)+ useSetupHighlight()++ const { sceneConfig } = useValues(sceneLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const { isDarkModeOn } = useValues(themeLogic)++ return (+ <>+ <div className="contents isolate">+ <Navigation sceneConfig={sceneConfig}>{children}</Navigation>+ <GlobalModals />+ <GlobalShortcuts />+ <Command />+ <PostOnboardingModal />+ <ImpersonationNotice />+ {featureFlags[FEATURE_FLAGS.EXPERIMENTS_DW_AA_TEST] === 'test' && (+ <div data-attr="experiments-dw-aa-test-variant" className="hidden" />+ )}+ </div>+ <ToastContainer+ autoClose={6000}+ transition={Slide}+ closeButton={<ToastCloseButton />}+ position="bottom-right"+ theme={isDarkModeOn ? 'dark' : 'light'}+ />+ </>+ )+}diff --git a/frontend/src/scenes/ChunkLoadErrorBoundary.tsx b/frontend/src/scenes/ChunkLoadErrorBoundary.tsxnew file mode 100644index 000000000000..50ca238380ca--- /dev/null+++ b/frontend/src/scenes/ChunkLoadErrorBoundary.tsx@@ -0,0 +1,72 @@+import { Component, type ReactNode } from 'react'++const RELOAD_GUARD_KEY = 'posthog-chunk-reload-at'+const RELOAD_GUARD_WINDOW_MS = 20_000++function isChunkLoadError(error: unknown): boolean {+ if (!error || typeof error !== 'object') {+ return false+ }+ const err = error as { name?: string; message?: string }+ return (+ err.name === 'ChunkLoadError' ||+ (typeof err.message === 'string' && err.message.includes('Failed to fetch dynamically imported module'))+ )+}++interface State {+ error: unknown+ surface: boolean+}++/**+ * Catches chunk-load failures from `React.lazy(() => import(...))` boundaries.+ * On a stale-deploy chunk-hash mismatch we reload once; if a reload was already+ * attempted in the last 20s we let the error bubble to the outer ErrorBoundary+ * rather than spinning forever. Non-chunk errors are re-thrown so the regular+ * error UI still renders.+ */+export class ChunkLoadErrorBoundary extends Component<{ children: ReactNode }, State> {+ override state: State = { error: null, surface: false }++ static getDerivedStateFromError(error: unknown): Partial<State> {+ return { error }+ }++ override componentDidCatch(error: unknown): void {+ if (!isChunkLoadError(error)) {+ return+ }+ let lastReload = 0+ try {+ lastReload = Number(window.localStorage.getItem(RELOAD_GUARD_KEY) ?? 0)+ } catch {+ // localStorage may be unavailable (e.g. Safari private mode) - treat as no prior reload+ }+ if (lastReload && Date.now() - lastReload < RELOAD_GUARD_WINDOW_MS) {+ console.error('[ChunkLoadErrorBoundary] Recently reloaded; surfacing error instead of looping.')+ this.setState({ surface: true })+ return+ }+ console.warn('[ChunkLoadErrorBoundary] Chunk-load failure (likely stale deploy); reloading.')+ try {+ window.localStorage.setItem(RELOAD_GUARD_KEY, String(Date.now()))+ } catch {+ // localStorage may throw QuotaExceededError (Safari private mode, full storage).+ // Skip the guard and reload anyway - without the timestamp the worst case is+ // a reload loop, which only happens if the chunk itself keeps failing.+ }+ window.location.reload()+ }++ override render(): ReactNode {+ const { error, surface } = this.state+ if (error && (!isChunkLoadError(error) || surface)) {+ throw error+ }+ if (error && isChunkLoadError(error)) {+ return null+ }+ return this.props.children+ }+}