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): stop generic fetch errors triggering a full reload (#100102)

posthog[bot]0a962bc94dc1
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 8197eadf9d4b..40e55a7be4a9 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -14,6 +14,7 @@ import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { themeLogic } from 'lib/logic/themeLogic'
import { accessLevelSatisfied, getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+import { lazyWithRetry } from 'lib/utils/retryImport'
import { BreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'
import {
InsightErrorState,
@@ -76,7 +77,7 @@ export function shouldRenderInsightCardViz({
return isPageVisible || !queryVizDefinitelyRendersToCanvas(query)
}
-const LazyEditAlertModal = React.lazy(() =>
+const LazyEditAlertModal = lazyWithRetry(() =>
import('products/alerts/frontend/views/EditAlertModal').then(({ EditAlertModal }) => ({ default: EditAlertModal }))
)
diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx
index 9cacea2a76e0..d8292098b881 100644
--- a/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx
@@ -1,4 +1,4 @@
-import { KeyboardEvent, Suspense, lazy, useEffect, useState } from 'react'
+import { KeyboardEvent, Suspense, useEffect, useState } from 'react'
import { IconPencil } from '@posthog/icons'
import { LemonButton, LemonLabel, LemonModal, LemonTextArea } from '@posthog/lemon-ui'
@@ -7,13 +7,14 @@ import { PostHogErrorBoundary } from '@posthog/react'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { Spinner } from 'lib/lemon-ui/Spinner'
+import { lazyWithRetry } from 'lib/utils/retryImport'
import { updateNotebookCodeBlockText } from './documentModel'
import { InsertMenuSelectionDirection } from './editorTypes'
import { NotebookBlockNode, NotebookCodeBlockNode, NotebookMode } from './types'
// Loaded on demand so the mermaid library ships in its own chunk rather than the notebook bundle.
-const LazyMermaidDiagram = lazy(() => import('lib/lemon-ui/LemonMarkdown/MermaidDiagram'))
+const LazyMermaidDiagram = lazyWithRetry(() => import('lib/lemon-ui/LemonMarkdown/MermaidDiagram'))
// Wait for a pause in typing before re-rendering the preview, so a burst of keystrokes runs one
// Mermaid render instead of one parse and layout per character.
diff --git a/frontend/src/lib/utils/isChunkLoadError.test.ts b/frontend/src/lib/utils/isChunkLoadError.test.ts
index 0263cf25155d..04ae416fb72e 100644
--- a/frontend/src/lib/utils/isChunkLoadError.test.ts
+++ b/frontend/src/lib/utils/isChunkLoadError.test.ts
@@ -1,4 +1,4 @@
-import { isChunkLoadError } from './isChunkLoadError'
+import { isChunkLoadError, isGenericNetworkTypeError, markAsChunkLoadError } from './isChunkLoadError'
describe('isChunkLoadError', () => {
it.each([
@@ -8,12 +8,6 @@ describe('isChunkLoadError', () => {
{ name: 'TypeError', message: 'Failed to fetch dynamically imported module: /static/chunk.js' },
true,
],
- ['Safari native TypeError: Load failed', { name: 'TypeError', message: 'Load failed' }, true],
- [
- 'Firefox native TypeError: NetworkError',
- { name: 'TypeError', message: 'NetworkError when attempting to fetch resource.' },
- true,
- ],
[
'Firefox dynamic-import failure',
{ name: 'TypeError', message: 'error loading dynamically imported module: /static/chunk.js' },
@@ -32,6 +26,12 @@ describe('isChunkLoadError', () => {
['generic TypeError', { name: 'TypeError', message: 'undefined is not a function' }, false],
['unrelated Error', { name: 'Error', message: 'something else' }, false],
['error with no name or message', {}, false],
+ ['Safari native TypeError: Load failed, unmarked', { name: 'TypeError', message: 'Load failed' }, false],
+ [
+ 'Firefox native TypeError: NetworkError, unmarked',
+ { name: 'TypeError', message: 'NetworkError when attempting to fetch resource.' },
+ false,
+ ],
])('classifies %s', (_label, error, expected) => {
expect(isChunkLoadError(error)).toBe(expected)
})
@@ -44,4 +44,27 @@ describe('isChunkLoadError', () => {
])('returns false for non-object %s', (_label, value) => {
expect(isChunkLoadError(value)).toBe(false)
})
+
+ it('treats a generic network TypeError as a chunk load error once marked by retryImport', () => {
+ const error = { name: 'TypeError', message: 'Load failed' }
+ expect(isChunkLoadError(error)).toBe(false)
+ markAsChunkLoadError(error)
+ expect(isChunkLoadError(error)).toBe(true)
+ })
+})
+
+describe('isGenericNetworkTypeError', () => {
+ it.each([
+ ['Safari native TypeError: Load failed', { name: 'TypeError', message: 'Load failed' }, true],
+ [
+ 'Firefox native TypeError: NetworkError',
+ { name: 'TypeError', message: 'NetworkError when attempting to fetch resource.' },
+ true,
+ ],
+ ['generic TypeError', { name: 'TypeError', message: 'undefined is not a function' }, false],
+ ['non-TypeError with a matching message', { name: 'Error', message: 'Load failed' }, false],
+ ['error with no name or message', {}, false],
+ ])('classifies %s', (_label, error, expected) => {
+ expect(isGenericNetworkTypeError(error)).toBe(expected)
+ })
})
diff --git a/frontend/src/lib/utils/isChunkLoadError.ts b/frontend/src/lib/utils/isChunkLoadError.ts
index acb4f7033d79..821eff9a42e4 100644
--- a/frontend/src/lib/utils/isChunkLoadError.ts
+++ b/frontend/src/lib/utils/isChunkLoadError.ts
@@ -2,10 +2,12 @@
* Recognizes the various shapes a failed `import(...)` can take across bundlers and browsers:
* - webpack: `Error` with `name === 'ChunkLoadError'`
* - esbuild/Vite: message contains `'Failed to fetch dynamically imported module'`
- * - Safari: native `TypeError: Load failed` (no JS stack — see load-failed.tsx known exception)
- * - Firefox: native `TypeError: NetworkError when attempting to fetch resource.`
* - Firefox: native `TypeError: error loading dynamically imported module: <url>` (deferred import of a now-deleted chunk after a deploy)
* - WebKit/Safari: `Importing a module script failed.` (module script fails to load, e.g. transient network failure)
+ *
+ * Safari's/Firefox's generic network TypeErrors (`isGenericNetworkTypeError`) are also a failed
+ * `import()`'s shape in those browsers, but the message can't tell that apart from an unrelated
+ * failed `fetch()` — so they only count here once `retryImport` has marked them.
*/
const markedChunkLoadErrors = new WeakSet<object>()
@@ -16,20 +18,39 @@ export function markAsChunkLoadError(error: unknown): void {
markedChunkLoadErrors.add(error)
}
-export function isChunkLoadError(error: unknown): boolean {
+/** Extract error name and message safely from an error-like object. */
+function getErrorInfo(error: unknown): { name: string; message: string } | null {
if (!error || typeof error !== 'object') {
- return false
+ return null
}
const err = error as { name?: string; message?: string }
+ const name = err.name ?? ''
const message = typeof err.message === 'string' ? err.message : ''
- const isTypeError = err.name === 'TypeError'
+ return { name, message }
+}
+
+/** Safari's/Firefox's native network TypeError shape — ambiguous between a failed `import()` and an unrelated failed `fetch()`. */
+export function isGenericNetworkTypeError(error: unknown): boolean {
+ const info = getErrorInfo(error)
+ if (!info || info.name !== 'TypeError') {
+ return false
+ }
+ return (
+ info.message.includes('Load failed') || info.message.includes('NetworkError when attempting to fetch resource')
+ )
+}
+
+export function isChunkLoadError(error: unknown): boolean {
+ const info = getErrorInfo(error)
+ if (!info) {
+ return false
+ }
+ const isTypeError = info.name === 'TypeError'
return (
- markedChunkLoadErrors.has(error) ||
- err.name === 'ChunkLoadError' ||
- message.includes('Failed to fetch dynamically imported module') ||
- message.includes('Importing a module script failed') ||
- (isTypeError && message.includes('Load failed')) ||
- (isTypeError && message.includes('NetworkError when attempting to fetch resource')) ||
- (isTypeError && message.includes('error loading dynamically imported module'))
+ markedChunkLoadErrors.has(error as object) ||
+ info.name === 'ChunkLoadError' ||
+ info.message.includes('Failed to fetch dynamically imported module') ||
+ info.message.includes('Importing a module script failed') ||
+ (isTypeError && info.message.includes('error loading dynamically imported module'))
)
}
diff --git a/frontend/src/lib/utils/retryImport.test.ts b/frontend/src/lib/utils/retryImport.test.ts
index ce5da7dac7cf..771ef05cf024 100644
--- a/frontend/src/lib/utils/retryImport.test.ts
+++ b/frontend/src/lib/utils/retryImport.test.ts
@@ -62,4 +62,17 @@ describe('retryImport', () => {
await expect(retryImport(factory)).rejects.toThrow('undefined is not a function')
expect(factory).toHaveBeenCalledTimes(1)
})
+
+ it('retries a generic network TypeError and marks it as a chunk load error once exhausted', async () => {
+ const error = new TypeError('Load failed')
+ const factory = jest.fn().mockRejectedValue(error)
+
+ const promise = retryImport(factory)
+ void promise.catch(() => {})
+ await jest.runAllTimersAsync()
+
+ await expect(promise).rejects.toBe(error)
+ expect(factory).toHaveBeenCalledTimes(3)
+ expect(isChunkLoadError(error)).toBe(true)
+ })
})
diff --git a/frontend/src/lib/utils/retryImport.ts b/frontend/src/lib/utils/retryImport.ts
index 3ca00d8f8079..9007b70b0c76 100644
--- a/frontend/src/lib/utils/retryImport.ts
+++ b/frontend/src/lib/utils/retryImport.ts
@@ -1,6 +1,6 @@
import { ComponentType, LazyExoticComponent, lazy } from 'react'
-import { isChunkLoadError, markAsChunkLoadError } from 'lib/utils/isChunkLoadError'
+import { isChunkLoadError, isGenericNetworkTypeError, markAsChunkLoadError } from 'lib/utils/isChunkLoadError'
function isMinifiedBootModuleEvaluationError(error: unknown): boolean {
if (!error || typeof error !== 'object') {
@@ -27,7 +27,12 @@ export async function retryImport<T>(factory: () => T, retries = 2, baseDelayMs
try {
return await factory()
} catch (error) {
- if (retries <= 0 || !isChunkLoadError(error)) {
+ if (!isChunkLoadError(error) && !isGenericNetworkTypeError(error)) {
+ throw error
+ }
+ // Mark as a chunk load error so downstream boundaries recognize it if retries fail.
+ markAsChunkLoadError(error)
+ if (retries <= 0) {
throw error
}
await new Promise<void>((resolve) => setTimeout(resolve, baseDelayMs))
diff --git a/frontend/src/scenes/ChunkLoadErrorBoundary.test.tsx b/frontend/src/scenes/ChunkLoadErrorBoundary.test.tsx
index 58090093abfa..8af50d32e245 100644
--- a/frontend/src/scenes/ChunkLoadErrorBoundary.test.tsx
+++ b/frontend/src/scenes/ChunkLoadErrorBoundary.test.tsx
@@ -31,6 +31,11 @@ function ThrowRegularError(): JSX.Element {
throw new Error('regular render failure')
}
+function ThrowGenericNetworkError(): JSX.Element {
+ // Same shape a failed import() takes on Safari/Firefox, thrown by an unrelated fetch here.
+ throw new TypeError('Load failed')
+}
+
describe('ChunkLoadErrorBoundary', () => {
let consoleErrorSpy: jest.SpyInstance
let consoleWarnSpy: jest.SpyInstance
@@ -119,4 +124,19 @@ describe('ChunkLoadErrorBoundary', () => {
expect(reload).not.toHaveBeenCalled()
expect(screen.getByText('regular render failure')).toBeInTheDocument()
})
+
+ it('lets an unmarked generic network error bubble instead of reloading', () => {
+ const reload = jest.fn()
+
+ render(
+ <TestErrorBoundary>
+ <ChunkLoadErrorBoundary reload={reload}>
+ <ThrowGenericNetworkError />
+ </ChunkLoadErrorBoundary>
+ </TestErrorBoundary>
+ )
+
+ expect(reload).not.toHaveBeenCalled()
+ expect(screen.getByText('Load failed')).toBeInTheDocument()
+ })
})
diff --git a/frontend/src/scenes/billing/BillingSection.tsx b/frontend/src/scenes/billing/BillingSection.tsx
index 07351fe91960..3e3bc6550a6b 100644
--- a/frontend/src/scenes/billing/BillingSection.tsx
+++ b/frontend/src/scenes/billing/BillingSection.tsx
@@ -2,12 +2,13 @@ import './Billing.scss'
import { useValues } from 'kea'
import { router } from 'kea-router'
-import { Suspense, lazy, useEffect } from 'react'
+import { Suspense, useEffect } from 'react'
import { LemonTabs, Spinner } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { lazyWithRetry } from 'lib/utils/retryImport'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -17,7 +18,7 @@ import { BillingSpendView } from './BillingSpendView'
import { BillingUsage } from './BillingUsage'
import { BillingSectionId } from './types'
-const BillingAlerts = lazy(() =>
+const BillingAlerts = lazyWithRetry(() =>
import('@posthog/products-billing-alerts/frontend/BillingAlerts').then((module) => ({
default: module.BillingAlerts,
}))