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): recover and report when the app stylesheet fails or stalls (#96875)

Rafael Audibert25c9b88c3735
diff --git a/common/esbuilder/cssLoader.mjs b/common/esbuilder/cssLoader.mjs
new file mode 100644
index 000000000000..24bbbe148f0c
--- /dev/null
+++ b/common/esbuilder/cssLoader.mjs
@@ -0,0 +1,129 @@
+/**
+ * The app stylesheet is attached at runtime instead of as a parser-blocking `<link>` in `<head>`,
+ * so a slow CSS fetch does not hold up the boot scripts and the CSSOM keeps a single copy.
+ *
+ * That trade-off gives up the recovery a parser-inserted link gets for free, and the page has
+ * nothing to fall back on: the critical CSS in index.html only covers the pre-React shell, so an
+ * app that renders without this stylesheet paints raw markup at natural size. The failure is also
+ * silent, because a `<link>` that fails or hangs raises no JavaScript error.
+ *
+ * This loader therefore treats the stylesheet as something that can fail. Each attempt has its own
+ * timeout, because a stalled request fires no `error` event. `load` counts as success only when the
+ * sheet applied, because a response that is not CSS fires `load` and leaves `link.sheet` null. A
+ * failed attempt starts the next URL in the ladder: a stale CDN can refuse the hashed file but
+ * serve the hashless copy, and a fresh query defeats a poisoned cache entry or a hung connection.
+ * Each failure also sends an `$exception` beacon by hand, because posthog-js is not loaded this
+ * early, the same way RootErrorBoundary reports boot failures.
+ *
+ * `window.ESBUILD_CSS_READY` resolves `true` once a stylesheet applies, and `false` once every
+ * attempt has failed. The app entry waits on it before its first render (frontend/src/index.tsx).
+ */
+
+export const CSS_READY_GLOBAL = 'ESBUILD_CSS_READY'
+
+/** How long one stylesheet request may hang before the loader gives up on it and tries the next. */
+export const CSS_ATTEMPT_TIMEOUT_MS = 10000
+
+export const STYLESHEET_ERROR_TYPE = 'StylesheetLoadError'
+
+/**
+ * Inline loader script. `cssFile` is the hashed stylesheet and `cssFileFallback` the hashless copy
+ * with a build-id query. Dev builds pass the same path for both, and then the ladder is the file
+ * plus its cache-busting retry.
+ */
+export function cssLoaderScript(cssFile, cssFileFallback) {
+ const paths = cssFileFallback && cssFileFallback !== cssFile ? [cssFile, cssFileFallback] : [cssFile]
+ return `
+ (function () {
+ var paths = ${JSON.stringify(paths)};
+ var lastPath = paths[paths.length - 1];
+ paths.push(lastPath + (lastPath.indexOf('?') === -1 ? '?' : '&') + 'retry=' + Date.now());
+
+ var resolveReady;
+ window.${CSS_READY_GLOBAL} = new Promise(function (resolve) { resolveReady = resolve; });
+ var isReady = false;
+ function settle(applied) {
+ if (isReady) { return; }
+ isReady = true;
+ resolveReady(applied);
+ }
+
+ function report(reason, href, attempt) {
+ console.error('[PostHog] App stylesheet ' + reason + ': ' + href);
+ try {
+ var apiKey = window.JS_POSTHOG_API_KEY;
+ if (!apiKey) { return; }
+ var host = window.JS_POSTHOG_HOST || window.location.origin;
+ var distinctId;
+ try {
+ distinctId = JSON.parse(window.localStorage.getItem('ph_' + apiKey + '_posthog') || '{}').distinct_id;
+ } catch (e) {
+ // storage unavailable or corrupt, so report anonymously
+ }
+ var payload = JSON.stringify({
+ api_key: apiKey,
+ event: '$exception',
+ distinct_id: distinctId || ('stylesheet-failure-' + Date.now()),
+ properties: {
+ $process_person_profile: false,
+ // Origin only. This loader also runs on exporter.html, where the path
+ // carries the share token (/shared/<token>, /interview/<token>), and it
+ // runs before the exporter can redact it. stylesheet_href already says
+ // which build and which page type failed.
+ $current_url: window.location.origin,
+ $exception_level: attempt === paths.length ? 'fatal' : 'error',
+ $exception_list: [{
+ type: ${JSON.stringify(STYLESHEET_ERROR_TYPE)},
+ value: 'App stylesheet ' + reason,
+ mechanism: { handled: true, synthetic: true }
+ }],
+ stylesheet_href: href,
+ stylesheet_attempt: attempt,
+ stylesheet_attempts: paths.length
+ }
+ });
+ // A string body goes out as text/plain: CORS-safelisted and accepted by capture.
+ var url = host + '/e/';
+ if (!(typeof navigator.sendBeacon === 'function' && navigator.sendBeacon(url, payload))) {
+ fetch(url, { method: 'POST', body: payload, keepalive: true }).catch(function () {});
+ }
+ } catch (e) {
+ // reporting a failure must never make the failure worse
+ }
+ }
+
+ function attempt(index) {
+ var href = (window.JS_URL || '') + '/static/' + paths[index];
+ var link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.crossOrigin = "anonymous";
+ link.href = href;
+ var isDone = false;
+ var timer = setTimeout(function () { fail('stalled'); }, ${CSS_ATTEMPT_TIMEOUT_MS});
+ function fail(reason) {
+ if (isDone) { return; }
+ isDone = true;
+ clearTimeout(timer);
+ report(reason, href, index + 1);
+ if (index + 1 < paths.length) {
+ attempt(index + 1);
+ } else {
+ settle(false);
+ }
+ }
+ link.addEventListener("load", function () {
+ if (!link.sheet) { fail('loaded but did not apply'); return; }
+ isDone = true;
+ clearTimeout(timer);
+ // A link left behind by an earlier timeout can still land and style the page,
+ // so a late load counts too.
+ settle(true);
+ });
+ link.addEventListener("error", function () { fail('failed to load'); });
+ document.head.appendChild(link);
+ }
+
+ attempt(0);
+ })();
+ `
+}
diff --git a/common/esbuilder/cssLoader.test.ts b/common/esbuilder/cssLoader.test.ts
new file mode 100644
index 000000000000..52a7befe742a
--- /dev/null
+++ b/common/esbuilder/cssLoader.test.ts
@@ -0,0 +1,153 @@
+import { CSS_ATTEMPT_TIMEOUT_MS, cssLoaderScript } from './cssLoader.mjs'
+
+const CSS_FILE = 'index-ABCD1234.css'
+const CSS_FALLBACK = 'index.css?t=99'
+const STATIC = 'https://cdn.example.com/static/'
+
+type FakeLink = {
+ rel?: string
+ crossOrigin?: string
+ href?: string
+ sheet?: object | null
+ addEventListener: (type: string, listener: () => void) => void
+ dispatch: (type: string) => void
+}
+
+function makeLink(): FakeLink {
+ const listeners: Record<string, (() => void)[]> = {}
+ return {
+ sheet: null,
+ addEventListener: (type: string, listener: () => void) => {
+ ;(listeners[type] ??= []).push(listener)
+ },
+ dispatch: (type: string) => listeners[type]?.forEach((listener) => listener()),
+ }
+}
+
+function runLoader({ cssFileFallback = CSS_FALLBACK, apiKey = 'phc_test' as string | null } = {}): {
+ ready: Promise<boolean>
+ links: FakeLink[]
+ beacons: Record<string, any>[]
+} {
+ const links: FakeLink[] = []
+ const beacons: Record<string, any>[] = []
+ const win: Record<string, any> = {
+ JS_URL: 'https://cdn.example.com',
+ JS_POSTHOG_API_KEY: apiKey,
+ JS_POSTHOG_HOST: 'https://capture.example.com',
+ // A share path, because this loader also runs on exporter.html.
+ location: { origin: 'https://app.example.com', href: 'https://app.example.com/shared/sh4r3-t0k3n' },
+ localStorage: { getItem: () => null },
+ }
+ const doc = {
+ createElement: (): FakeLink => makeLink(),
+ head: { appendChild: (link: FakeLink) => links.push(link) },
+ }
+ const nav = {
+ sendBeacon: (_url: string, body: string) => {
+ beacons.push(JSON.parse(body))
+ return true
+ },
+ }
+ // The inline loader runs in the page as a classic script: these are all globals there.
+ new Function(
+ 'window',
+ 'document',
+ 'navigator',
+ 'console',
+ 'fetch',
+ cssLoaderScript(CSS_FILE, cssFileFallback)
+ )(win, doc, nav, { error: () => {} }, () => Promise.resolve())
+ return { ready: win.ESBUILD_CSS_READY, links, beacons }
+}
+
+/** A stylesheet that really applied has a `sheet`; a response that is not CSS fires `load` without one. */
+function applyStylesheet(link: FakeLink): void {
+ link.sheet = {}
+ link.dispatch('load')
+}
+
+describe('css loader script', () => {
+ beforeEach(() => jest.useFakeTimers())
+ afterEach(() => jest.useRealTimers())
+
+ it('attaches the hashed stylesheet for CORS and reports ready once it applies', async () => {
+ const { ready, links, beacons } = runLoader()
+ expect(links).toHaveLength(1)
+ expect(links[0]).toMatchObject({ rel: 'stylesheet', crossOrigin: 'anonymous', href: `${STATIC}${CSS_FILE}` })
+
+ applyStylesheet(links[0])
+
+ await expect(ready).resolves.toBe(true)
+ expect(beacons).toHaveLength(0)
+ })
+
+ it.each([
+ ['fails', 'failed to load', (link: FakeLink) => link.dispatch('error')],
+ ['stalls', 'stalled', () => jest.advanceTimersByTime(CSS_ATTEMPT_TIMEOUT_MS)],
+ ['serves a response that is not CSS', 'loaded but did not apply', (link: FakeLink) => link.dispatch('load')],
+ ])('loads the hashless copy and reports when the hashed stylesheet %s', (_case, reason, fail) => {
+ const { links, beacons } = runLoader()
+ fail(links[0])
+
+ expect(links).toHaveLength(2)
+ expect(links[1].href).toBe(`${STATIC}${CSS_FALLBACK}`)
+ expect(beacons).toHaveLength(1)
+ expect(beacons[0].properties.$exception_list[0]).toMatchObject({
+ type: 'StylesheetLoadError',
+ value: `App stylesheet ${reason}`,
+ })
+ expect(beacons[0].properties).toMatchObject({
+ stylesheet_href: `${STATIC}${CSS_FILE}`,
+ stylesheet_attempt: 1,
+ $exception_level: 'error',
+ $process_person_profile: false,
+ })
+ // The path can carry a share token, so the beacon must keep the origin only.
+ expect(JSON.stringify(beacons[0])).not.toContain('sh4r3-t0k3n')
+ })
+
+ it('retries with a fresh query, then reports the page unstyled once every attempt fails', async () => {
+ const { ready, links, beacons } = runLoader()
+ for (let attempt = 0; attempt < 3; attempt++) {
+ jest.advanceTimersByTime(CSS_ATTEMPT_TIMEOUT_MS)
+ }
+
+ // The last attempt asks for the same file with a query no cache entry and no hung
+ // connection has seen.
+ expect(links).toHaveLength(3)
+ expect(links[2].href).toMatch(new RegExp(`^${STATIC}index\\.css\\?t=99&retry=\\d+$`))
+
+ await expect(ready).resolves.toBe(false)
+ expect(beacons).toHaveLength(3)
+ expect(beacons[2].properties.$exception_level).toBe('fatal')
+ })
+
+ it('reports ready when a stylesheet abandoned by a timeout lands late', async () => {
+ const { ready, links } = runLoader()
+ jest.advanceTimersByTime(CSS_ATTEMPT_TIMEOUT_MS)
+ expect(links).toHaveLength(2)
+
+ applyStylesheet(links[0])
+
+ await expect(ready).resolves.toBe(true)
+ })
+
+ it('recovers without a beacon when capture is opted out', () => {
+ const { links, beacons } = runLoader({ apiKey: null })
+ links[0].dispatch('error')
+
+ expect(links).toHaveLength(2)
+ expect(beacons).toHaveLength(0)
+ })
+
+ it('still has a retry to fall back on in a dev build with no hashless copy', () => {
+ const { links } = runLoader({ cssFileFallback: CSS_FILE })
+ links[0].dispatch('error')
+
+ expect(links).toHaveLength(2)
+ expect(links[1].href).toMatch(new RegExp(`^${STATIC}index-ABCD1234\\.css\\?retry=\\d+$`))
+ links[1].dispatch('error')
+ expect(links).toHaveLength(2)
+ })
+})
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 6ccd964f071d..49eb73f0482b 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -17,6 +17,7 @@ import postcssPresetEnv from 'postcss-preset-env'
import ts from 'typescript'
import { chunkLoaderScript, chunkMapFileContents, chunkMapFileName } from './chunkLoader.mjs'
+import { cssLoaderScript } from './cssLoader.mjs'
// Re-exported for one-shot builds outside buildInParallel (e.g. the toolbar loader, which is
// built after the toolbar app build so it can embed the hashed entry filename). Consumers
@@ -123,53 +124,21 @@ export function copyIndexHtml(
}
const chunkCode = Object.keys(chunks).length > 0 ? chunkLoaderScript(chunksToServe, chunkMapFile) : ''
- // Fallback to non-hashed CSS (with cache-busting build ID) when the hashed
- // version fails to load (e.g. CDN returns 403). Mirrors the JS fallback above.
+ // Fallback to non-hashed CSS (with cache-busting build ID) when the hashed version fails or
+ // stalls (e.g. CDN returns 403, or the request hangs). Mirrors the JS fallback above.
const cssFileFallback = `${entry}.css?t=${buildId}`
- const needsCssFallback = cssFile !== cssFileFallback
- const cssLoader = `
- const link = document.createElement("link");
- link.rel = "stylesheet";
- link.crossOrigin = "anonymous";
- link.href = (window.JS_URL || '') + "/static/" + ${JSON.stringify(cssFile)};
- ${
- needsCssFallback
- ? `link.onerror = function() {
- link.onerror = null;
- console.warn('Failed to load stylesheet "' + ${JSON.stringify(cssFile)} + '", trying fallback');
- var fallbackLink = document.createElement("link");
- fallbackLink.rel = "stylesheet";
- fallbackLink.crossOrigin = "anonymous";
- fallbackLink.href = (window.JS_URL || '') + "/static/" + ${JSON.stringify(cssFileFallback)};
- document.head.appendChild(fallbackLink);
- };`
- : ''
- }
- // Resolves once the boot stylesheet is applied (or failed), so the entry script can hold
- // React's first render until then. The entry JS is small enough to win the race against
- // the stylesheet on slow networks; rendering before the sheet arrives paints the app
- // unstyled for a frame or two.
- window.ESBUILD_CSS_READY = new Promise(function (resolve) {
- link.addEventListener("load", function () { resolve(true) }, { once: true });
- link.addEventListener("error", function () { resolve(false) }, { once: true });
- });
- document.head.appendChild(link)
- `
+ const cssLoader = cssFile ? cssLoaderScript(cssFile, cssFileFallback) : ''
fse.writeFileSync(
path.resolve(absWorkingDir, to),
fse.readFileSync(path.resolve(absWorkingDir, from), { encoding: 'utf-8' }).replace(
'</head>',
` <script nonce="{{ request.csp_nonce }}" type="application/javascript">
- // NOTE: the link for the stylesheet will be added just
- // after this script block. The react code will need the
- // body to have been parsed before it is able to interact
- // with it and add anything to it.
- //
- // Fingers crossed the browser waits for the stylesheet to
- // load such that it's in place when react starts
- // adding elements to the DOM
- ${cssFile ? cssLoader : ''}
+ // The stylesheet link is added just below, at runtime, so a slow CSS fetch does
+ // not hold up these boot scripts. The loader publishes window.ESBUILD_CSS_READY,
+ // and the app entry waits on it before its first render, so React does not paint
+ // real markup that no stylesheet reaches. See cssLoader.mjs.
+ ${cssLoader}
${scriptCode}
${chunkCode}
</script>
diff --git a/frontend/src/index.test.tsx b/frontend/src/index.test.tsx
index ef23f6833a0d..851c0dc57b1c 100644
--- a/frontend/src/index.test.tsx
+++ b/frontend/src/index.test.tsx
@@ -111,15 +111,15 @@ describe('app entry boot', () => {
}
)
- it.each(['loaded', 'failed', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {
+ it.each(['loaded', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {
if (stylesheetState === 'absent') {
delete window.ESBUILD_CSS_READY
}
await loadEntry()
await act(async () => {
- if (stylesheetState === 'loaded' || stylesheetState === 'failed') {
- stylesheet.resolve(stylesheetState === 'loaded')
+ if (stylesheetState === 'loaded') {
+ stylesheet.resolve(true)
}
})
@@ -127,6 +127,21 @@ describe('app entry boot', () => {
expect(bootApp).toHaveBeenCalledTimes(1)
})
+ it.each([
+ ['within the render gate', 0],
+ ['after a stall let the app render', 6000],
+ ])('offers a reload instead of an unstyled app when every stylesheet URL fails %s', async (_case, stallMs) => {
+ await loadEntry()
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(stallMs)
+ })
+
+ await act(async () => stylesheet.resolve(false))
+
+ expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog failed to load its styles.')
+ expect(document.querySelector('[data-attr="boot-test-app"]')).not.toBeInTheDocument()
+ })
+
it('boots after five seconds if the stylesheet stays pending', async () => {
await loadEntry()
await act(async () => {
diff --git a/frontend/src/index.tsx b/frontend/src/index.tsx
index dcfc0ba5f6c2..ba6e8a6b1baa 100644
--- a/frontend/src/index.tsx
+++ b/frontend/src/index.tsx
@@ -42,17 +42,20 @@ declare global {
}
}
-function renderApp(): void {
+function getAppRoot(): Root | null {
const rootElement = document.getElementById('root')
if (!rootElement) {
console.error('Attempted, but could not render PostHog app because <div id="root" /> is not found.')
- return
+ return null
}
// 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(
+ return (window.__posthogAppRoot ??= createRoot(rootElement))
+}
+
+function renderApp(): void {
+ getAppRoot()?.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. */}
@@ -71,23 +74,52 @@ function renderApp(): void {
)
}
+function renderStylesheetFailure(): void {
+ getAppRoot()?.render(
+ <div className="Preloader" role="alert">
+ <div>
+ PostHog failed to load its styles.{' '}
+ <button onClick={() => window.location.reload()}>Reload the page</button> to try again.
+ </div>
+ </div>
+ )
+}
+
// The boot stylesheet is attached by the loader script in the HTML, and this entry can finish
// before the sheet arrives. Rendering then paints the app unstyled until the sheet lands, so wait
-// for it, but only briefly: a stylesheet the CDN refuses must not block the app (the loader has
-// its own fallback link for that case).
+// for it, but only briefly: a stylesheet that is merely slow must not hold the app back, and the
+// loader keeps working on it in the background.
const CSS_READY_TIMEOUT_MS = 5000
-function whenBootStylesheetReady(): Promise<unknown> {
- const cssReady = window.ESBUILD_CSS_READY
+function whenBootStylesheetReady(cssReady: Promise<boolean> | undefined): Promise<boolean | null> {
if (!cssReady) {
- return Promise.resolve()
+ return Promise.resolve(null)
}
- return Promise.race([cssReady, new Promise((resolve) => setTimeout(resolve, CSS_READY_TIMEOUT_MS))])
+ return Promise.race([
+ cssReady,
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), CSS_READY_TIMEOUT_MS)),
+ ])
}
function boot(): void {
// Observe early failures until React mounts its boundaries, without replacing the rejected promise.
void loadAppModules().catch(() => {})
- void whenBootStylesheetReady().then(renderApp)
+ const cssReady = window.ESBUILD_CSS_READY
+ // `false` means the loader ran out of stylesheet URLs, so every one of them failed. The app has
+ // no styles of its own, so it would paint raw markup at natural size. Offer a reload instead.
+ // A stalled attempt can hold the loader well past the render gate below, so this replaces the
+ // app whenever the verdict arrives, not only when it beats the gate.
+ void cssReady?.then((applied) => {
+ if (!applied) {
+ renderStylesheetFailure()
+ }
+ })
+ void whenBootStylesheetReady(cssReady).then((applied) => {
+ // `null` is the gate expiring on a sheet that is only slow. The loader keeps working on it
+ // in the background, so render now rather than hold the app back.
+ if (applied !== false) {
+ renderApp()
+ }
+ })
}
// Render react only when DOM has loaded - javascript might be cached and loaded before the page is ready.
diff --git a/playwright/e2e/shared-dashboard-styling.spec.ts b/playwright/e2e/shared-dashboard-styling.spec.ts
index 2350faa44318..f9573800d6ed 100644
--- a/playwright/e2e/shared-dashboard-styling.spec.ts
+++ b/playwright/e2e/shared-dashboard-styling.spec.ts
@@ -79,10 +79,10 @@ test.describe('Shared dashboard styling', () => {
}
})
- let fallbackWarningLogged = false
+ let fallbackFailureLogged = false
page.on('console', (msg) => {
- if (msg.type() === 'warning' && msg.text().includes('Failed to load stylesheet')) {
- fallbackWarningLogged = true
+ if (msg.type() === 'error' && msg.text().includes('App stylesheet failed to load')) {
+ fallbackFailureLogged = true
}
})
@@ -90,7 +90,7 @@ test.describe('Shared dashboard styling', () => {
await expect(page.locator('[data-attr="insights-graph"]')).toBeVisible({ timeout: 30000 })
expect(fallbackCssLoaded).toBe(true)
- expect(fallbackWarningLogged).toBe(true)
+ expect(fallbackFailureLogged).toBe(true)
await expect(page.locator('body.ExporterBody')).toBeVisible()
})
})