Skip to content

Open source alternative to Semrush and Ahrefs

Stop reporting stale-tab chunk errors while reloading onto a new build (#925)

Carter Smith927e9ad8c52c
diff --git a/src/client/lib/posthog.ts b/src/client/lib/posthog.ts
index 5adb43e7..c6cab591 100644
--- a/src/client/lib/posthog.ts
+++ b/src/client/lib/posthog.ts
@@ -13,6 +13,7 @@ let browserPostHogClientPromise: Promise<BrowserPostHogClient | null> | null =
null;
let browserPostHogInitialized = false;
let analyticsCaptureEnabled = true;
+let clientErrorCaptureStopped = false;
type ExceptionEntry = {
value?: unknown;
@@ -197,11 +198,17 @@ export function startAnalyticsCapture() {
});
}
+// Called right before reloading a stale tab onto a new build. Errors thrown
+// while that reload is pending are side effects of the missing chunks, not bugs.
+export function stopClientErrorCapture() {
+ clientErrorCaptureStopped = true;
+}
+
export function captureClientError(
error: unknown,
properties: Record<string, string | null | undefined> = {},
) {
- if (!analyticsCaptureEnabled) return;
+ if (!analyticsCaptureEnabled || clientErrorCaptureStopped) return;
withPostHogClient((client) =>
client.captureException(error, {
source: "client",
diff --git a/src/router.tsx b/src/router.tsx
index a6726af0..a184b536 100644
--- a/src/router.tsx
+++ b/src/router.tsx
@@ -2,6 +2,7 @@ import { createRouter as createTanStackRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { DefaultCatchBoundary } from "./client/components/DefaultCatchBoundary";
import { NotFound } from "./client/components/NotFound";
+import { stopClientErrorCapture } from "./client/lib/posthog";
const PRELOAD_ERROR_RELOAD_KEY = "vite-preload-error-reloaded-at";
@@ -12,6 +13,10 @@ const PRELOAD_ERROR_RELOAD_KEY = "vite-preload-error-reloaded-at";
// scope, not in a component, so it also catches chunks that fail while
// hydration is still in progress. Vite only emits this event in builds —
// exercise it via `vite preview` or a deploy, never `vite dev`.
+//
+// preventDefault() makes the failed import resolve to undefined, so the lazy
+// route throws "reading 'component'" before the reload lands. Error capture is
+// stopped first so that side effect isn't reported.
if (typeof window !== "undefined") {
window.addEventListener("vite:preloadError", (event) => {
try {
@@ -28,6 +33,7 @@ if (typeof window !== "undefined") {
// error surface instead of risking a reload loop.
return;
}
+ stopClientErrorCapture();
event.preventDefault();
window.location.reload();
});