Skip to content

An open-source, faster Devin alternative

TypeScript

fix(web): auto-recover from stale code-split chunks after a deploy

Igor Zalutskif8f31d3dbf87
diff --git a/web/src/components/error-boundary.tsx b/web/src/components/error-boundary.tsx
index 593ebcd9..4ef9baa5 100644
--- a/web/src/components/error-boundary.tsx
+++ b/web/src/components/error-boundary.tsx
@@ -2,6 +2,7 @@ import { Component, type ReactNode } from 'react'
import { TriangleAlert } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { EmptyState } from '@/components/empty-state'
+import { isChunkLoadError, reloadForStaleChunk } from '@/lib/chunk-reload'
interface Props {
children: ReactNode
@@ -11,6 +12,8 @@ interface Props {
interface State {
error: Error | null
+ /** A chunk-load error we're recovering from by reloading — render nothing. */
+ recovering: boolean
}
/**
@@ -19,19 +22,30 @@ interface State {
* route pathname) to auto-reset on navigation.
*/
export class ErrorBoundary extends Component<Props, State> {
- state: State = { error: null }
+ state: State = { error: null, recovering: false }
static getDerivedStateFromError(error: Error): State {
- return { error }
+ // A failed dynamic import (usually a stale code-split chunk after a deploy)
+ // is recoverable by reloading. Mark it so render shows nothing until
+ // componentDidCatch decides — avoids flashing the error UI before reload.
+ return { error, recovering: isChunkLoadError(error) }
}
componentDidCatch(error: Error, info: { componentStack?: string | null }) {
+ if (isChunkLoadError(error)) {
+ // Backstop for import failures the main.tsx vite:preloadError handler
+ // misses. Reload once; if the guard declines (already reloaded — likely a
+ // real failure, not a stale chunk), fall through to the error UI.
+ if (reloadForStaleChunk()) return
+ this.setState({ recovering: false })
+ }
console.error('Unhandled UI error:', error, info.componentStack)
}
- reset = () => this.setState({ error: null })
+ reset = () => this.setState({ error: null, recovering: false })
render() {
+ if (this.state.recovering) return null
if (this.state.error) {
return this.props.fallback ? (
this.props.fallback(this.reset)
diff --git a/web/src/lib/chunk-reload.ts b/web/src/lib/chunk-reload.ts
new file mode 100644
index 00000000..992f46c9
--- /dev/null
+++ b/web/src/lib/chunk-reload.ts
@@ -0,0 +1,47 @@
+// Recovery for stale code-split chunks after a deploy.
+//
+// Each build emits content-hashed route chunks (e.g. Billing-a1b2.js). A deploy
+// replaces them, so a tab opened before the deploy still holds an index.html
+// that references chunk URLs which no longer exist. Navigating to a
+// not-yet-loaded route then fails the dynamic import() — and because the CF
+// assets binding uses not_found_handling="single-page-application", the missing
+// .js is answered with index.html (HTML), so the browser gets a document where
+// it expected a module. React.lazy rethrows that rejection and the route
+// ErrorBoundary shows "Something went wrong".
+//
+// The fix is to reload once: a fresh index.html references the current chunk
+// hashes. A short time window guards against a reload loop when the failure is
+// not a stale chunk (a genuinely broken/unreachable build), in which case the
+// error surfaces normally for a manual retry.
+
+const RELOAD_AT_KEY = 'oc:chunk-reload-at'
+const RELOAD_WINDOW_MS = 10_000
+
+// Messages browsers/Vite use when a dynamic import() can't load or parse a
+// module: stale chunk, network miss, or HTML served where a module was expected.
+const CHUNK_ERROR_RE =
+ /Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|module script failed|expected a JavaScript module|ChunkLoadError|Loading chunk [\w-]+ failed/i
+
+export function isChunkLoadError(error: unknown): boolean {
+ return error instanceof Error && CHUNK_ERROR_RE.test(error.message)
+}
+
+/**
+ * Reload the page to recover a stale chunk, at most once per RELOAD_WINDOW_MS so
+ * a persistently-broken deploy can't reload-loop. Returns true if a reload was
+ * started (the caller should stop and render nothing), false if it declined (the
+ * caller should surface the error normally).
+ */
+export function reloadForStaleChunk(): boolean {
+ try {
+ const last = Number(sessionStorage.getItem(RELOAD_AT_KEY)) || 0
+ if (Date.now() - last < RELOAD_WINDOW_MS) return false
+ sessionStorage.setItem(RELOAD_AT_KEY, String(Date.now()))
+ } catch {
+ // sessionStorage blocked (private mode / partitioned storage) — can't guard
+ // against a loop, so don't auto-reload; let the error surface instead.
+ return false
+ }
+ window.location.reload()
+ return true
+}
diff --git a/web/src/main.tsx b/web/src/main.tsx
index 904c5351..dd6455b4 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -10,6 +10,7 @@ import {
ErrorBoundary,
DefaultErrorFallback,
} from './components/error-boundary'
+import { reloadForStaleChunk } from './lib/chunk-reload'
import './index.css'
const queryClient = new QueryClient({
@@ -31,6 +32,15 @@ if (PH_TOKEN) {
})
}
+// After a deploy, an open tab still references the previous build's hashed route
+// chunks; navigating to a not-yet-loaded route fails the dynamic import and Vite
+// dispatches `vite:preloadError`. Reload once to pick up the new build instead
+// of surfacing it as a render error. If the guard declines (a recent reload —
+// likely a real failure), let it throw so the ErrorBoundary handles it.
+window.addEventListener('vite:preloadError', (event) => {
+ if (reloadForStaleChunk()) event.preventDefault()
+})
+
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<PostHogProvider client={posthog}>