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.

feat(perf): lazy-load app bundle with preload hints and critical css (#67564)

Fernando Gomesc9dac3f6d1a5
diff --git a/frontend/build.mjs b/frontend/build.mjs
index 5655a7716820..ade89485f024 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
@@ -18,6 +19,9 @@ import { getToolbarBuildConfig } from './toolbar-config.mjs'
export const __dirname = path.dirname(fileURLToPath(import.meta.url))
+// Chunks below this size aren't worth a preload tag in the HTML document
+const PRELOAD_MIN_CHUNK_BYTES = 50 * 1024
+
startDevServer(__dirname)
copyPublicFolder(path.resolve(__dirname, 'public'), path.resolve(__dirname, 'dist'))
@@ -123,6 +127,7 @@ await buildInParallel(
}
if (!isDev) {
reportTopChunks(buildResponse.outputs, { label: 'PostHog App chunks' })
+ writePreloadManifest(buildResponse.outputs)
}
writeIndexHtml(chunks, entrypoints)
}
@@ -143,6 +148,59 @@ await buildInParallel(
}
)
+/**
+ * Write dist/preload-manifest.json, read by the Django backend (posthog/utils.py) to emit
+ * <link rel="preload"/"modulepreload"> tags so the boot chain (CSS, font, App and
+ * AuthenticatedShell chunks) is fetched in parallel instead of discovered as a waterfall.
+ * Paths are URL suffixes appended to `JS_URL + '/'`.
+ */
+export function writePreloadManifest(outputs = {}) {
+ const distDir = path.resolve(__dirname, 'dist')
+ // esbuild metafile paths are relative to absWorkingDir (= __dirname), not the invoking cwd
+ const toUrl = (outputPath) => `static/${path.relative(distDir, path.resolve(__dirname, outputPath))}`
+
+ const findEntryJs = (entryPoint) =>
+ Object.entries(outputs).find(([out, meta]) => meta.entryPoint === entryPoint && out.endsWith('.js'))
+
+ const collectChunkUrls = (entryPoint) => {
+ const found = findEntryJs(entryPoint)
+ if (!found) {
+ return []
+ }
+ const [outputPath, meta] = found
+ const urls = [toUrl(outputPath)]
+ for (const imp of meta.imports || []) {
+ if (imp.kind === 'import-statement' && (outputs[imp.path]?.bytes || 0) > PRELOAD_MIN_CHUNK_BYTES) {
+ urls.push(toUrl(imp.path))
+ }
+ }
+ return urls
+ }
+
+ const cssOutput = Object.keys(outputs).find((out) => /\/index(-[^./-]+)?\.css$/.test(out))
+ const fontOutput = Object.keys(outputs).find((out) => /\/Inter(-[^./-]+)?\.woff2$/.test(out))
+
+ const dedupe = (urls) => [...new Set(urls)]
+ const manifest = {
+ css: cssOutput ? toUrl(cssOutput) : '',
+ font: fontOutput ? toUrl(fontOutput) : '',
+ // Entry first: its modulepreload starts the fetch at preload-scan time, before the
+ // loader script at the end of <head> gets to import() it.
+ js: dedupe([...collectChunkUrls('src/index.tsx'), ...collectChunkUrls('src/scenes/App.tsx')]),
+ // The backend emits these only for authenticated requests
+ authenticatedJs: dedupe(collectChunkUrls('src/scenes/AuthenticatedShell.tsx')),
+ }
+ // An empty field means an entry point, chunk, or asset name drifted from the lookups above —
+ // failing the build beats shipping green with the optimization silently off.
+ for (const [key, value] of Object.entries(manifest)) {
+ if (value.length === 0) {
+ console.error(`preload-manifest.json field "${key}" resolved empty.`)
+ throw new Error(`preload-manifest.json field "${key}" resolved empty.`)
+ }
+ }
+ fs.writeFileSync(path.resolve(distDir, 'preload-manifest.json'), JSON.stringify(manifest, null, 2))
+}
+
export function writeIndexHtml(chunks = {}, entrypoints = []) {
copyIndexHtml(__dirname, 'src/index.html', 'dist/index.html', 'index', chunks, entrypoints)
copyIndexHtml(__dirname, 'src/layout.html', 'dist/layout.html', 'index', chunks, entrypoints)
diff --git a/frontend/src/RootErrorBoundary.test.tsx b/frontend/src/RootErrorBoundary.test.tsx
new file mode 100644
index 000000000000..7ba43713c839
--- /dev/null
+++ b/frontend/src/RootErrorBoundary.test.tsx
@@ -0,0 +1,91 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { RootErrorBoundary } from './RootErrorBoundary'
+
+function ThrowRenderError(): JSX.Element {
+ throw new Error('boot render kaboom')
+}
+
+function ThrowChunkError(): JSX.Element {
+ throw new TypeError('Failed to fetch dynamically imported module: /static/chunk-App.js')
+}
+
+describe('RootErrorBoundary', () => {
+ let consoleErrorSpy: jest.SpyInstance
+ let sendBeacon: jest.Mock
+
+ beforeEach(() => {
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
+ sendBeacon = jest.fn().mockReturnValue(true)
+ Object.defineProperty(window.navigator, 'sendBeacon', {
+ value: sendBeacon,
+ configurable: true,
+ writable: true,
+ })
+ window.JS_POSTHOG_API_KEY = 'test-api-key'
+ window.JS_POSTHOG_HOST = 'https://us.example.com'
+ })
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore()
+ delete window.JS_POSTHOG_API_KEY
+ delete window.JS_POSTHOG_HOST
+ cleanup()
+ })
+
+ it('renders children and reports nothing when nothing throws', () => {
+ render(
+ <RootErrorBoundary>
+ <div>app content</div>
+ </RootErrorBoundary>
+ )
+
+ expect(screen.getByText('app content')).toBeInTheDocument()
+ expect(sendBeacon).not.toHaveBeenCalled()
+ })
+
+ it('reports render crashes to the capture API and shows crash copy', () => {
+ render(
+ <RootErrorBoundary>
+ <ThrowRenderError />
+ </RootErrorBoundary>
+ )
+
+ expect(screen.getByRole('alert')).toHaveTextContent('PostHog crashed while starting.')
+ expect(sendBeacon).toHaveBeenCalledTimes(1)
+ const [url, body] = sendBeacon.mock.calls[0]
+ expect(url).toBe('https://us.example.com/e/')
+ const event = JSON.parse(body)
+ expect(event.api_key).toBe('test-api-key')
+ expect(event.event).toBe('$exception')
+ expect(event.distinct_id).toEqual(expect.any(String))
+ expect(event.properties.$exception_list[0].value).toBe('boot render kaboom')
+ expect(event.properties.chunk_load_error).toBe(false)
+ })
+
+ it('shows load-failure copy for chunk-load errors', () => {
+ render(
+ <RootErrorBoundary>
+ <ThrowChunkError />
+ </RootErrorBoundary>
+ )
+
+ expect(screen.getByRole('alert')).toHaveTextContent('PostHog failed to load.')
+ expect(JSON.parse(sendBeacon.mock.calls[0][1]).properties.chunk_load_error).toBe(true)
+ })
+
+ it('does not report when capture is opted out', () => {
+ delete window.JS_POSTHOG_API_KEY
+
+ render(
+ <RootErrorBoundary>
+ <ThrowRenderError />
+ </RootErrorBoundary>
+ )
+
+ expect(screen.getByRole('alert')).toBeInTheDocument()
+ expect(sendBeacon).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/RootErrorBoundary.tsx b/frontend/src/RootErrorBoundary.tsx
new file mode 100644
index 000000000000..8a95bf2d68cc
--- /dev/null
+++ b/frontend/src/RootErrorBoundary.tsx
@@ -0,0 +1,95 @@
+import React from 'react'
+
+import { isChunkLoadError } from 'lib/utils/isChunkLoadError'
+
+/**
+ * Report a boot failure straight to the capture API. posthog-js lives inside the App chunk —
+ * the very chunk this boundary guards — so when boot fails there is no SDK to report through,
+ * and without this beacon a broken deploy would be invisible to error tracking.
+ * Fire-and-forget: reporting must never make a boot failure worse.
+ */
+function reportBootFailure(error: unknown): void {
+ try {
+ const apiKey = window.JS_POSTHOG_API_KEY
+ if (!apiKey) {
+ return // capture is opted out for this instance
+ }
+ const host = window.JS_POSTHOG_HOST || window.location.origin
+ let distinctId: string | undefined
+ try {
+ // posthog-js persistence — absent on a first visit or under cookie-only persistence
+ distinctId = JSON.parse(window.localStorage.getItem(`ph_${apiKey}_posthog`) || '{}').distinct_id
+ } catch {
+ // storage unavailable or corrupt — report anonymously
+ }
+ const err = error instanceof Error ? error : new Error(String(error))
+ const payload = JSON.stringify({
+ api_key: apiKey,
+ event: '$exception',
+ distinct_id: distinctId || `boot-failure-${Date.now()}`,
+ properties: {
+ // Personless event: don't create person profiles from anonymous boot beacons
+ $process_person_profile: false,
+ $current_url: window.location.href,
+ $exception_level: 'fatal',
+ $exception_list: [
+ {
+ type: err.name || 'Error',
+ value: err.message,
+ mechanism: { handled: true, synthetic: false },
+ },
+ ],
+ stack: err.stack,
+ chunk_load_error: isChunkLoadError(error),
+ },
+ })
+ // A string body goes out as text/plain: CORS-safelisted (no preflight) and accepted by
+ // the capture endpoints. sendBeacon delivery survives the page unloading under a reload.
+ const url = `${host}/e/`
+ if (!(typeof navigator.sendBeacon === 'function' && navigator.sendBeacon(url, payload))) {
+ void fetch(url, { method: 'POST', body: payload, keepalive: true }).catch(() => {})
+ }
+ } catch {
+ // best-effort only
+ }
+}
+
+interface RootErrorBoundaryState {
+ error: unknown
+}
+
+/**
+ * Dependency-free last-resort boundary around the whole app. Everything inside the App chunk
+ * (posthog-js, the full ErrorBoundary, all UI) can fail to load or crash on boot — this
+ * boundary is what remains, so it reports the failure itself and offers a manual reload.
+ * Stale-deploy chunk errors auto-reload once via the ChunkLoadErrorBoundary nested inside it
+ * (see index.tsx); only errors that survive that recovery surface here.
+ */
+export class RootErrorBoundary extends React.Component<{ children: React.ReactNode }, RootErrorBoundaryState> {
+ override state: RootErrorBoundaryState = { error: null }
+
+ static getDerivedStateFromError(error: unknown): RootErrorBoundaryState {
+ return { error }
+ }
+
+ override componentDidCatch(error: unknown, errorInfo: React.ErrorInfo): void {
+ console.error('[PostHog] App failed to start:', error, errorInfo.componentStack)
+ reportBootFailure(error)
+ }
+
+ override render(): React.ReactNode {
+ if (this.state.error) {
+ return (
+ <div className="Preloader" role="alert">
+ <div>
+ {isChunkLoadError(this.state.error)
+ ? 'PostHog failed to load. '
+ : 'PostHog crashed while starting. '}
+ <button onClick={() => window.location.reload()}>Reload the page</button> to try again.
+ </div>
+ </div>
+ )
+ }
+ return this.props.children
+ }
+}
diff --git a/frontend/src/index.html b/frontend/src/index.html
index 620c78168fe2..475a88c55493 100644
--- a/frontend/src/index.html
+++ b/frontend/src/index.html
@@ -1,7 +1,44 @@
<!doctype html>
-<html lang="en">
+{# boot_theme mirrors themeLogic.isDarkModeOn (posthog/utils.py): "dark", "system", or "light" #}
+<html lang="en" data-boot-theme="{{ boot_theme|default:'light' }}">
<head>
+ {# head.html first: it carries <meta charset>, which must stay within the first 1024 bytes #}
+ {# so the browser's encoding prescan finds it #}
{% include "head.html" %}
+ {# Critical CSS for the pre-React shell (background, spinner, boot-failure message), so the #}
+ {# page doesn't flash white. Everything visual is scoped to #root:empty and .Preloader — the #}
+ {# app never styles <body> background itself, so an unscoped rule here would persist after #}
+ {# boot and bleed through the themed app. These selectors stop matching once React renders #}
+ {# real content. #}
+ <style>
+ html,body,#root{height:100%;margin:0;padding:0}
+ *,:after,:before{box-sizing:border-box}
+ #root:empty,.Preloader{background:#f3f4ef;color:#111;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:14px;line-height:1.4}
+ [data-boot-theme=dark] #root:empty,[data-boot-theme=dark] .Preloader{background:#1d1f27;color:#fff}
+ @media (prefers-color-scheme:dark){[data-boot-theme=system] #root:empty,[data-boot-theme=system] .Preloader{background:#1d1f27;color:#fff}}
+ .Preloader{display:flex;align-items:center;justify-content:center;height:100%;min-height:200px;width:100%}
+ .Preloader__inner{width:25px;height:25px;border:5px solid rgba(245,78,0,.333);border-top-color:#f54e00;border-radius:50%;animation:preloader-spin 1s linear infinite}
+ .Preloader button{border:0;padding:0;background:none;font:inherit;color:inherit;text-decoration:underline;cursor:pointer}
+ @keyframes preloader-spin{to{transform:rotate(360deg)}}
+ </style>
+ {# Resource hints so the boot chain (font, CSS, entry -> App chunks) is fetched in parallel #}
+ {# instead of discovered as a waterfall. Empty in dev mode and when no build manifest exists. #}
+ {% if js_url %}
+ <link rel="preconnect" href="{{ js_url }}" crossorigin>
+ {% endif %}
+ {% if preload_font_url %}
+ <link rel="preload" href="{{ js_url }}/{{ preload_font_url }}" as="font" type="font/woff2" crossorigin>
+ {% endif %}
+ {% if preload_css_url %}
+ {# Preload only — the loader script injected at the end of <head> appends the actual #}
+ {# stylesheet link (with its hashless fallback). Applying the stylesheet there keeps a #}
+ {# slow CSS fetch from blocking the parser-inserted boot scripts, and keeps the CSSOM #}
+ {# to a single copy. crossorigin matches the loader's fetch mode so one response is reused. #}
+ <link rel="preload" href="{{ js_url }}/{{ preload_css_url }}" as="style" crossorigin="anonymous">
+ {% endif %}
+ {% for url in preload_js_urls %}
+ <link rel="modulepreload" href="{{ js_url }}/{{ url }}">
+ {% endfor %}
</head>
<body>
{% include "overlays.html" %}
diff --git a/frontend/src/index.tsx b/frontend/src/index.tsx
index 2b1ffc733cbb..59ec28a1f15e 100644
--- a/frontend/src/index.tsx
+++ b/frontend/src/index.tsx
@@ -2,75 +2,48 @@ import '~/styles'
import './buffer-polyfill'
-import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'
-import { polyfillCountryFlagEmojis } from 'country-flag-emoji-polyfill'
-import { getContext } from 'kea'
-import posthog from 'posthog-js'
+import { Suspense, lazy } from 'react'
import { createRoot } from 'react-dom/client'
-import { PostHogProvider } from '@posthog/react'
+import { retryImport } from 'lib/utils/retryImport'
-import { App } from 'scenes/App'
+import { RootErrorBoundary } from './RootErrorBoundary'
+import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'
-import { initKea } from './initKea'
-import { ErrorBoundary } from './layout/ErrorBoundary'
-import { loadPostHogJS } from './loadPostHogJS'
-
-loadPostHogJS()
-initKea()
-
-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.
-//
-// NOTE: The first argument is the name of the polyfill to use. This is used to set the font family in our CSS.
-// Make sure to update the font family in the CSS if you change this.
-//
-// The polyfill runs canvas-based feature detection (getImageData) which can throw on some browser
-// states (e.g. Safari/macOS). It's purely cosmetic and best-effort, so swallow any failure.
-try {
- polyfillCountryFlagEmojis('Emoji Flags Polyfill')
-} catch (error) {
- console.warn('[index] Country flag emoji polyfill detection failed:', error)
-}
-
-// Expose `window.getReduxState()` to make snapshots to storybook easy
-if (typeof window !== 'undefined') {
- // Disabled in production to prevent leaking secret data, personal API keys, etc
- if (process.env.NODE_ENV === 'development') {
- ;(window as any).getReduxState = () => getContext().store.getState()
- } else {
- ;(window as any).getReduxState = () => 'Disabled outside development!'
- }
-}
+// 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.
+const App = lazy(() =>
+ retryImport(() => import('scenes/App')).then((mod) => {
+ mod.bootApp()
+ return { default: mod.App }
+ })
+)
function renderApp(): void {
const root = document.getElementById('root')
- if (root) {
- createRoot(root).render(
- <ErrorBoundary>
- <PostHogProvider client={posthog}>
- <BaseTooltip.Provider delay={500} closeDelay={0} timeout={400}>
- <App />
- </BaseTooltip.Provider>
- </PostHogProvider>
- </ErrorBoundary>
- )
- } else {
+ if (!root) {
console.error('Attempted, but could not render PostHog app because <div id="root" /> is not found.')
+ return
}
+ createRoot(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. */}
+ <ChunkLoadErrorBoundary>
+ <Suspense
+ fallback={
+ <div className="Preloader" role="status" aria-label="Loading PostHog">
+ <div className="Preloader__inner" />
+ </div>
+ }
+ >
+ <App />
+ </Suspense>
+ </ChunkLoadErrorBoundary>
+ </RootErrorBoundary>
+ )
}
// Render react only when DOM has loaded - javascript might be cached and loaded before the page is ready.
diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsx
index e4de27d94296..2c1c6b5c7c30 100644
--- a/frontend/src/scenes/App.tsx
+++ b/frontend/src/scenes/App.tsx
@@ -1,11 +1,14 @@
+import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'
import { BindLogic, useMountedLogic, useValues } from 'kea'
+import posthog from 'posthog-js'
import React, { Suspense, useEffect } from 'react'
import { Slide, ToastContainer } from 'react-toastify'
+import { PostHogProvider } from '@posthog/react'
+
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 { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'
@@ -20,12 +23,57 @@ 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()
+
+ 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
@@ -49,6 +97,15 @@ function SceneAnimationRoot({ children }: { children: React.ReactNode }): JSX.El
)
}
+/** Lazy-loaded Kea devtools panel, only rendered in dev mode with dev tools open */
+function KeaDevtoolsLoader(): JSX.Element | null {
+ const [DevTools, setDevTools] = React.useState<React.ComponentType | null>(null)
+ React.useEffect(() => {
+ import('lib/KeaDevTools').then((mod) => setDevTools(() => mod.KeaDevtools)).catch(() => {})
+ }, [])
+ return DevTools ? <DevTools /> : null
+}
+
export function App(): JSX.Element | null {
const { showApp, showingDelayedSpinner, showingDevTools } = useValues(appLogic)
@@ -74,19 +131,33 @@ export function App(): JSX.Element | null {
// A cloud OAuth redirect lands at /oauth/callback on the local origin. Render the exchange
// screen here (oauthLogic's urlToAction performs the token exchange), before normal routing.
if (window.location.pathname === '/oauth/callback') {
- return <OAuthCallback />
- }
-
- if (showApp) {
return (
- <>
- <AppScene />
- {showingDevTools ? <KeaDevtools /> : null}
- </>
+ <ErrorBoundary>
+ <PostHogProvider client={posthog}>
+ <OAuthCallback />
+ </PostHogProvider>
+ </ErrorBoundary>
)
}
- return <SpinnerOverlay sceneLevel visible={showingDelayedSpinner} />
+ const sceneContent = (
+ <ErrorBoundary>
+ <PostHogProvider client={posthog}>
+ <BaseTooltip.Provider delay={500} closeDelay={0} timeout={400}>
+ {showApp ? (
+ <>
+ <AppScene />
+ {showingDevTools ? <KeaDevtoolsLoader /> : null}
+ </>
+ ) : (
+ <SpinnerOverlay sceneLevel visible={showingDelayedSpinner} />
+ )}
+ </BaseTooltip.Provider>
+ </PostHogProvider>
+ </ErrorBoundary>
+ )
+
+ return sceneContent
}
function AppScene(): JSX.Element | null {
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 2c3cb31cc99e..6c33bf1a923e 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -67,6 +67,8 @@ export default defineConfig(({ mode }) => {
storybook: resolve(__dirname, '../.storybook'),
// Just for Vite: we copy public assets to src/assets, we need to alias it to the correct path
public: resolve(__dirname, 'src/assets'),
+ // Required for production builds — @posthog/icons is in the pnpm store, not node_modules root
+ '@posthog/icons': resolve(__dirname, 'node_modules/@posthog/icons'),
products: resolve(__dirname, '../products'),
'@posthog/shared-onboarding': resolve(__dirname, '../docs/onboarding'),
'@posthog/shared-onboarding/*': resolve(__dirname, '../docs/onboarding/*'),
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index ca69c410c7bd..0af8e1f35a3a 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTest
from unittest import mock
from unittest.mock import MagicMock
+from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpResponse
from django.test import RequestFactory
@@ -68,3 +69,25 @@ class TestGetContextForTemplate(APIBaseTest):
app_context = json.loads(actual["posthog_app_context"])
assert app_context["homepage"] == (stored_homepage or None)
+
+ @parameterized.expand(
+ [
+ ("anonymous_is_always_light", None, "light"),
+ ("missing_theme_mode_means_light", "", "light"),
+ ("dark", "dark", "dark"),
+ ("system_defers_to_the_os", "system", "system"),
+ ]
+ )
+ def test_boot_theme_mirrors_theme_logic(self, _name, theme_mode, expected):
+ request = RequestFactory().get("/")
+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)
+ if theme_mode is None:
+ request.user = AnonymousUser()
+ else:
+ self.user.theme_mode = theme_mode or None
+ self.user.save()
+ request.user = self.user
+
+ actual = get_context_for_template("index.html", request)
+
+ assert actual["boot_theme"] == expected
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 27d3428f2931..540a7d6f33bf 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -1,6 +1,7 @@
import os
import json
import base64
+import tempfile
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, cast
from zoneinfo import ZoneInfo
@@ -13,7 +14,7 @@ from unittest.mock import call, patch
from django.core.cache import cache
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpRequest
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
from django.test.client import RequestFactory
from django.utils.timezone import now
@@ -33,6 +34,7 @@ from posthog.utils import (
HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS,
PotentialSecurityProblemException,
_build_flag_provider,
+ _read_preload_manifest,
absolute_uri,
base64_decode,
filters_override_requested_by_client,
@@ -1298,3 +1300,59 @@ class TestBuildFlagProvider(TestCase):
os.environ.pop("POSTHOG_SELF_TEAM_ID", None)
assert _build_flag_provider()._resolve_team_id() == 2
+
+
+VALID_PRELOAD_MANIFEST = {
+ "css": "static/index-ABC123.css",
+ "font": "static/assets/Inter-DEF456.woff2",
+ "js": ["static/index-GHI789.js", "static/chunk-APP111.js"],
+ "authenticatedJs": ["static/chunk-SHELL222.js", "static/chunk-APP111.js"],
+}
+
+
+class TestReadPreloadManifest(SimpleTestCase):
+ def setUp(self):
+ super().setUp()
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.tmp_dir = tmp.name
+
+ def _write_manifest(self, content: str) -> str:
+ path = os.path.join(self.tmp_dir, "preload-manifest.json")
+ with open(path, "w") as f:
+ f.write(content)
+ return path
+
+ def test_resolves_unauthenticated_urls_as_written_by_the_build(self):
+ path = self._write_manifest(json.dumps(VALID_PRELOAD_MANIFEST))
+
+ assert _read_preload_manifest(path, include_authenticated_shell=False) == (
+ "static/index-ABC123.css",
+ ("static/index-GHI789.js", "static/chunk-APP111.js"),
+ "static/assets/Inter-DEF456.woff2",
+ )
+
+ def test_appends_authenticated_chunks_deduplicated(self):
+ path = self._write_manifest(json.dumps(VALID_PRELOAD_MANIFEST))
+
+ _, js_urls, _ = _read_preload_manifest(path, include_authenticated_shell=True)
+
+ assert js_urls == ("static/index-GHI789.js", "static/chunk-APP111.js", "static/chunk-SHELL222.js")
+
+ def test_missing_manifest_resolves_empty(self):
+ missing = os.path.join(self.tmp_dir, "missing.json")
+
+ assert _read_preload_manifest(missing, include_authenticated_shell=True) == ("", (), "")
+
+ @parameterized.expand(
+ [
+ ("corrupt_json", '{"css": "static/index.css", "js": ['),
+ ("js_not_a_list", json.dumps({**VALID_PRELOAD_MANIFEST, "js": "static/index.js"})),
+ ("js_entry_not_a_string", json.dumps({**VALID_PRELOAD_MANIFEST, "js": [{"file": "chunk.js"}]})),
+ ("css_not_a_string", json.dumps({**VALID_PRELOAD_MANIFEST, "css": ["static/index.css"]})),
+ ]
+ )
+ def test_malformed_manifest_resolves_empty_instead_of_garbage(self, _name: str, content: str) -> None:
+ path = self._write_manifest(content)
+
+ assert _read_preload_manifest(path, include_authenticated_shell=True) == ("", (), "")
diff --git a/posthog/utils.py b/posthog/utils.py
index 360088837d44..7f0d8a0928db 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -403,6 +403,62 @@ def get_js_url(request: HttpRequest) -> str:
return settings.JS_URL
+@lru_cache(maxsize=2)
+def _resolve_entry_assets(include_authenticated_shell: bool) -> tuple[str, tuple[str, ...], str]:
+ """
+ Return (css_url, js_preload_urls, font_url) for <head> preload tags, relative to JS_URL.
+ Preloading lets the browser fetch the boot chain (entry -> App -> AuthenticatedShell chunks,
+ the CSS bundle, and the Inter font, which is otherwise discovered only once the CSS is parsed)
+ in parallel instead of as a waterfall.
+
+ Reads the esbuild preload manifest (see writePreloadManifest in frontend/build.mjs). Returns
+ empty values in debug/test mode and when no manifest exists (e.g. a Vite build, which isn't
+ wired for production serving). Cached per process: manifests are immutable within a deploy.
+ """
+ if settings.DEBUG or settings.TEST:
+ return ("", (), "")
+ return _read_preload_manifest(
+ os.path.join(settings.BASE_DIR, "frontend", "dist", "preload-manifest.json"),
+ include_authenticated_shell,
+ )
+
+
+def _read_preload_manifest(manifest_path: str, include_authenticated_shell: bool) -> tuple[str, tuple[str, ...], str]:
+ """
+ Parse preload-manifest.json defensively: hints are an optimization, so any failure must
+ degrade to "no hints" rather than break page rendering — but loudly, because the caller
+ caches the result for the process lifetime, so a silent failure would turn the
+ optimization off fleet-wide until the next deploy.
+ """
+ try:
+ if not os.path.isfile(manifest_path):
+ return ("", (), "")
+ with open(manifest_path) as f:
+ manifest = json.load(f)
+ css = manifest.get("css", "")
+ font = manifest.get("font", "")
+ js = manifest.get("js", [])
+ authenticated_js = manifest.get("authenticatedJs", []) if include_authenticated_shell else []
+ if not (
+ isinstance(css, str)
+ and isinstance(font, str)
+ and isinstance(js, list)
+ and isinstance(authenticated_js, list)
+ ):
+ raise ValueError("preload manifest fields have unexpected types")
+ js_urls: list[str] = []
+ for url in [*js, *authenticated_js]:
+ if not isinstance(url, str):
+ raise ValueError("preload manifest fields have unexpected types")
+ if url not in js_urls:
+ js_urls.append(url)
+ return (css, tuple(js_urls), font)
+ except Exception as e:
+ logger.warning("preload_manifest_unreadable", manifest_path=manifest_path, error=str(e))
+ capture_exception(e)
+ return ("", (), "")
+
+
@tracer.start_as_current_span("template.context")
def get_context_for_template(
template_name: str,
@@ -628,6 +684,19 @@ def _build_template_context(
context["posthog_js_uuid_version"] = settings.POSTHOG_JS_UUID_VERSION
+ # Only the SPA shell references these; other templates (exporter, layout, ...) load different bundles
+ if template_name == "index.html":
+ context["preload_css_url"], context["preload_js_urls"], context["preload_font_url"] = _resolve_entry_assets(
+ bool(request.user and request.user.is_authenticated)
+ )
+ # Theme for the pre-React shell (critical CSS in index.html), mirroring the app's
+ # themeLogic.isDarkModeOn: anonymous pages are always light, a missing theme_mode
+ # means light, and only "system" defers to prefers-color-scheme.
+ user_theme_mode = (
+ getattr(request.user, "theme_mode", None) if request.user and request.user.is_authenticated else None
+ )
+ context["boot_theme"] = user_theme_mode or "light"
+
if posthog_distinct_id:
from posthog.models.instance_setting import get_instance_setting