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(frontend): move bootApp out of App.tsx to restore fast refresh (#70628)

Sam Penningtondd09e6b47841
diff --git a/frontend/src/index.tsx b/frontend/src/index.tsx
index 59ec28a1f15e..c959bab4c0a3 100644
--- a/frontend/src/index.tsx
+++ b/frontend/src/index.tsx
@@ -3,7 +3,7 @@ import '~/styles'
import './buffer-polyfill'
import { Suspense, lazy } from 'react'
-import { createRoot } from 'react-dom/client'
+import { createRoot, type Root } from 'react-dom/client'
import { retryImport } from 'lib/utils/retryImport'
@@ -12,22 +12,35 @@ import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'
// Lazy-load App so the entry chunk stays minimal: the entire transitive dependency
// graph (kea, posthog-js, scene logic, UI components) is only fetched when it renders.
-// bootApp() runs the chunk's one-time boot side effects (posthog-js, kea) after the
-// chunk loads and before <App /> first renders.
+// bootApp() runs the one-time boot side effects (posthog-js, kea) after the chunks
+// load and before <App /> first renders. It lives in its own module so scenes/App
+// keeps component-only exports and stays a React Fast Refresh boundary.
const App = lazy(() =>
- retryImport(() => import('scenes/App')).then((mod) => {
- mod.bootApp()
- return { default: mod.App }
- })
+ Promise.all([retryImport(() => import('scenes/App')), retryImport(() => import('scenes/bootApp'))]).then(
+ ([appModule, bootModule]) => {
+ bootModule.bootApp()
+ return { default: appModule.App }
+ }
+ )
)
+declare global {
+ interface Window {
+ __posthogAppRoot?: Root
+ }
+}
+
function renderApp(): void {
- const root = document.getElementById('root')
- if (!root) {
+ const rootElement = document.getElementById('root')
+ if (!rootElement) {
console.error('Attempted, but could not render PostHog app because <div id="root" /> is not found.')
return
}
- createRoot(root).render(
+ // Vite 8 can serve this entry module twice after an HMR invalidation reaches it (the script
+ // tag's bare URL plus a timestamped copy), and a second createRoot on an already-rooted
+ // container crashes React. Reuse one root so a repeat execution re-renders instead.
+ const root = (window.__posthogAppRoot ??= createRoot(rootElement))
+ root.render(
<RootErrorBoundary>
{/* Auto-reloads once on a chunk-load failure (stale deploy). Repeated or non-chunk
errors bubble to RootErrorBoundary, which reports them and shows the failure UI. */}
diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsx
index 58be93600a2b..94ebd7311d10 100644
--- a/frontend/src/scenes/App.tsx
+++ b/frontend/src/scenes/App.tsx
@@ -17,67 +17,18 @@ import { oauthLogic } from 'lib/oauth/oauthLogic'
import { retryImport } from 'lib/utils/retryImport'
import { appLogic } from 'scenes/appLogic'
import { appScenes } from 'scenes/appScenes'
-import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'
import { sceneLogic } from 'scenes/sceneLogic'
import { userLogic } from 'scenes/userLogic'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { initKea } from '../initKea'
-import { loadPostHogJS } from '../loadPostHogJS'
import { ChunkLoadErrorBoundary } from './ChunkLoadErrorBoundary'
const AuthenticatedShell = React.lazy(() => retryImport(() => import('./AuthenticatedShell')))
window.process = MOCK_NODE_PROCESS
-let appBooted = false
-
-/**
- * One-time boot side effects for the app chunk, called from the entry's lazy factory
- * (frontend/src/index.tsx) after the chunk loads and before <App /> first renders.
- * A function rather than module-scope statements so that merely importing scenes/App
- * (storybook stories, jest) stays side-effect-free — the test harnesses manage their
- * own kea context, and an import-time initKea() would wipe it.
- */
-export function bootApp(): void {
- if (appBooted) {
- return
- }
- appBooted = true
-
- loadPostHogJS()
- // Kea must initialize before any component mounts
- initKea()
- // Link resolves its drag-to-notebook behavior through a seam so bundles without
- // notebooks (toolbar, exporter) don't ship them; the app opts in here
- registerNotebookLinkDrag()
-
- const idle =
- typeof window.requestIdleCallback === 'function'
- ? window.requestIdleCallback.bind(window)
- : (cb: () => void) => setTimeout(cb, 200)
-
- idle(() => {
- void import('./session-recordings/player/snapshot-processing/DecompressionWorkerManager')
- .then(({ preWarmDecompression }) => preWarmDecompression())
- .catch((error) => {
- console.warn('[App] Failed to load DecompressionWorkerManager for pre-warm:', error)
- })
-
- // On Chrome + Windows, the country flag emojis don't render correctly. This polyfill fixes that.
- // NOTE: The first argument sets the polyfill's font family name, which our CSS references —
- // keep the two in sync. Detection is canvas-based and can throw on some browser states
- // (e.g. Safari/macOS); it's purely cosmetic and best-effort.
- void import('country-flag-emoji-polyfill')
- .then(({ polyfillCountryFlagEmojis }) => polyfillCountryFlagEmojis('Emoji Flags Polyfill'))
- .catch((error) => {
- console.warn('[App] Country flag emoji polyfill failed:', error)
- })
- })
-}
-
/**
* Wraps each rendered scene so that when the scene unmounts (on tab change
* or scene swap), every running CSS / Web Animation under it is cancelled
diff --git a/frontend/src/scenes/bootApp.ts b/frontend/src/scenes/bootApp.ts
new file mode 100644
index 000000000000..1a5543f17af2
--- /dev/null
+++ b/frontend/src/scenes/bootApp.ts
@@ -0,0 +1,53 @@
+import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'
+
+import { initKea } from '../initKea'
+import { loadPostHogJS } from '../loadPostHogJS'
+
+let appBooted = false
+
+/**
+ * One-time boot side effects for the app, called from the entry's lazy factory
+ * (frontend/src/index.tsx) after the app chunk loads and before <App /> first renders.
+ * A function rather than module-scope statements so that merely importing it
+ * (storybook stories, jest) stays side-effect-free — the test harnesses manage their
+ * own kea context, and an import-time initKea() would wipe it.
+ * Lives outside App.tsx so scenes/App keeps component-only exports and stays a React
+ * Fast Refresh boundary; with a mixed-export App.tsx, HMR invalidations cascade into
+ * src/index.tsx and force a full page reload on routine edits.
+ */
+export function bootApp(): void {
+ if (appBooted) {
+ return
+ }
+ appBooted = true
+
+ loadPostHogJS()
+ // Kea must initialize before any component mounts
+ initKea()
+ // Link resolves its drag-to-notebook behavior through a seam so bundles without
+ // notebooks (toolbar, exporter) don't ship them; the app opts in here
+ registerNotebookLinkDrag()
+
+ const idle =
+ typeof window.requestIdleCallback === 'function'
+ ? window.requestIdleCallback.bind(window)
+ : (cb: () => void) => setTimeout(cb, 200)
+
+ idle(() => {
+ void import('./session-recordings/player/snapshot-processing/DecompressionWorkerManager')
+ .then(({ preWarmDecompression }) => preWarmDecompression())
+ .catch((error) => {
+ console.warn('[App] Failed to load DecompressionWorkerManager for pre-warm:', error)
+ })
+
+ // On Chrome + Windows, the country flag emojis don't render correctly. This polyfill fixes that.
+ // NOTE: The first argument sets the polyfill's font family name, which our CSS references —
+ // keep the two in sync. Detection is canvas-based and can throw on some browser states
+ // (e.g. Safari/macOS); it's purely cosmetic and best-effort.
+ void import('country-flag-emoji-polyfill')
+ .then(({ polyfillCountryFlagEmojis }) => polyfillCountryFlagEmojis('Emoji Flags Polyfill'))
+ .catch((error) => {
+ console.warn('[App] Country flag emoji polyfill failed:', error)
+ })
+ })
+}