mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
When a lazy-loaded JS/CSS chunk fails to load (flaky or mobile
networks), users land on the global error screen and stay there until
they refresh by hand. This reloads the page once instead, in both
runtimes.
A reload is the only reliable recovery: WebKit (Safari and every iOS
browser) caches a failed module fetch in the document's module map, so
every later `import()` of that URL fails instantly until the page is
replaced. TanStack's `lazyRouteComponent` already reloads once for route
chunks, but it keys its guard on the error message, and Safari's message
("Importing a module script failed.") is the same for every chunk and
survives reloads, so after the first time in a tab it never reloads
again. Non-route lazy imports (`next/dynamic`, `React.lazy`, Monaco) had
no recovery at all.
**Added:**
- `lib/chunk-load-error.ts`: `isChunkLoadError` (Chrome, Firefox,
WebKit, webpack `ChunkLoadError` and Vite's CSS preload wording) and a
reload guard
- The guard is time-based (`sessionStorage`, 30s window), not
message-based: a second failure within 30s of a reload shows the normal
error screen instead of looping. It's also capped at 3 automatic reloads
per tab, and the guard is read back after writing it. If storage is
unavailable, or silently drops the write, it never reloads
- Unit tests for every message form, the guard window, the per-tab cap,
and broken, missing or write-dropping storage
**Changed:**
- The global error boundary in `pages/_app.tsx` and `routes/__root.tsx`,
plus TanStack's root `errorComponent`, reload once for chunk-load errors
and render nothing while the reload is in flight. Fallbacks only peek at
the guard during render; the reload is claimed after commit
(`useChunkLoadReload`), so a discarded render can't use up the guard
- Chunk-load errors that a reload recovers from are no longer reported
to Sentry. One that recurs within the guard window (the user actually
saw the error screen) is reported, tagged `chunkLoadError: true`
No `vite:preloadError` listener: it also fires for hover/intent route
preloads, so reloading on it would refresh the page under someone who
only hovered a link.
## To test
- On the preview, open DevTools → Network, block one route chunk URL
(e.g. the SQL editor's), then navigate to it: the page reloads once and
recovers (unblock after the reload), with no error screen flash
- Keep the chunk blocked: after the one reload you get the normal error
screen, not a reload loop
- Repeat after 30s+ in the same tab: it reloads again
- Sentry: the recovered reload sends no event; the persistent failure
sends one tagged `chunkLoadError`
- Normal navigation and genuine non-chunk errors behave as before
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
196 lines
6.6 KiB
TypeScript
196 lines
6.6 KiB
TypeScript
/**
|
|
* Recovery for failed lazy-loaded JS/CSS chunks (route chunks, `next/dynamic`,
|
|
* `React.lazy`, Monaco, …), which happen on flaky or mobile networks and after
|
|
* deploys that remove old chunks.
|
|
*
|
|
* A page reload is the only reliable recovery: WebKit caches a failed module
|
|
* fetch in the document's module map, so every later `import()` of the same
|
|
* URL fails instantly until the document is replaced.
|
|
*/
|
|
|
|
import { z } from 'zod'
|
|
|
|
export const CHUNK_LOAD_RELOAD_STORAGE_KEY = 'supabase-studio:chunk-load-reload'
|
|
|
|
/**
|
|
* Minimum time between two automatic reloads in the same tab. A chunk that
|
|
* fails again within this window after a reload is treated as persistent
|
|
* (offline, chunk deleted by a deploy) and falls through to the error UI
|
|
* instead of looping. It's longer than a cold boot on a slow mobile
|
|
* connection, so a reload that itself takes a while to boot can't loop; a
|
|
* fresh flake after the window gets its own reload.
|
|
*/
|
|
export const CHUNK_LOAD_RELOAD_GUARD_MS = 30_000
|
|
|
|
/**
|
|
* Hard cap on automatic reloads per tab, so a chunk that keeps failing on a
|
|
* page that takes longer than the guard window to boot can't reload forever.
|
|
*/
|
|
export const CHUNK_LOAD_RELOAD_MAX_PER_TAB = 3
|
|
|
|
const reloadStateSchema = z.object({
|
|
at: z.number().finite(),
|
|
count: z.number().int().nonnegative(),
|
|
})
|
|
|
|
type ReloadState = z.infer<typeof reloadStateSchema>
|
|
|
|
const CHUNK_LOAD_ERROR_PATTERNS = [
|
|
// Chrome / Chromium
|
|
/Failed to fetch dynamically imported module/i,
|
|
// Firefox
|
|
/error loading dynamically imported module/i,
|
|
// Safari / WebKit (incl. every iOS browser); carries no URL
|
|
/Importing a module script failed/i,
|
|
// Vite's dynamic-import dependency preloader
|
|
/Unable to preload CSS/i,
|
|
// Next.js / webpack (JS and CSS chunks)
|
|
/Loading (CSS )?chunk [^\s]+ failed/i,
|
|
]
|
|
|
|
export function isChunkLoadError(error: unknown): boolean {
|
|
if (typeof error !== 'object' || error === null) return false
|
|
|
|
const name = 'name' in error && typeof error.name === 'string' ? error.name : ''
|
|
if (name === 'ChunkLoadError') return true
|
|
|
|
const message = 'message' in error && typeof error.message === 'string' ? error.message : ''
|
|
return CHUNK_LOAD_ERROR_PATTERNS.some((pattern) => pattern.test(message))
|
|
}
|
|
|
|
/**
|
|
* The guard is keyed on time, not on the error message: WebKit's message is
|
|
* identical for every chunk and sessionStorage outlives reloads, so a
|
|
* message-keyed guard (as in TanStack's `lazyRouteComponent`) only ever
|
|
* reloads once per tab.
|
|
*/
|
|
export function shouldReloadForChunkError({
|
|
now,
|
|
lastReloadAt,
|
|
guardMs = CHUNK_LOAD_RELOAD_GUARD_MS,
|
|
}: {
|
|
now: number
|
|
lastReloadAt: number | null
|
|
guardMs?: number
|
|
}): boolean {
|
|
if (lastReloadAt === null) return true
|
|
// A timestamp in the future means the clock moved backwards; don't trust it
|
|
if (lastReloadAt > now) return false
|
|
return now - lastReloadAt >= guardMs
|
|
}
|
|
|
|
type ChunkReloadStorage = Pick<Storage, 'getItem' | 'setItem'>
|
|
|
|
function parseReloadState(raw: string): ReloadState | undefined {
|
|
try {
|
|
const result = reloadStateSchema.safeParse(JSON.parse(raw))
|
|
return result.success ? result.data : undefined
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns `undefined` when there's no usable value, and `null` when storage
|
|
* itself can't be read (private mode, blocked site data, SSR).
|
|
*/
|
|
function readReloadState(storage: ChunkReloadStorage): ReloadState | undefined | null {
|
|
try {
|
|
const raw = storage.getItem(CHUNK_LOAD_RELOAD_STORAGE_KEY)
|
|
return raw === null ? undefined : parseReloadState(raw)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reads the value back after writing it: a storage that silently drops
|
|
* writes would otherwise look empty on every boot and reload forever.
|
|
*/
|
|
function writeReloadState(storage: ChunkReloadStorage, state: ReloadState): boolean {
|
|
const value = JSON.stringify(state)
|
|
try {
|
|
storage.setItem(CHUNK_LOAD_RELOAD_STORAGE_KEY, value)
|
|
return storage.getItem(CHUNK_LOAD_RELOAD_STORAGE_KEY) === value
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
function getSessionStorage(): ChunkReloadStorage | undefined {
|
|
if (typeof window === 'undefined') return undefined
|
|
try {
|
|
return window.sessionStorage
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
type ChunkReloadOptions = { storage?: ChunkReloadStorage; now?: number }
|
|
|
|
/** The guard state to record if `error` may reload now, without writing it. */
|
|
function getNextReloadState(
|
|
error: unknown,
|
|
storage: ChunkReloadStorage,
|
|
now: number
|
|
): ReloadState | undefined {
|
|
if (!isChunkLoadError(error)) return undefined
|
|
|
|
const state = readReloadState(storage)
|
|
if (state === null) return undefined
|
|
|
|
const count = state?.count ?? 0
|
|
if (count >= CHUNK_LOAD_RELOAD_MAX_PER_TAB) return undefined
|
|
if (!shouldReloadForChunkError({ now, lastReloadAt: state?.at ?? null })) return undefined
|
|
|
|
return { at: now, count: count + 1 }
|
|
}
|
|
|
|
/**
|
|
* Decides whether `error` should trigger a page reload, recording the reload
|
|
* in the guard when it should. Without a working storage there's no loop
|
|
* guard, so it never reloads.
|
|
*/
|
|
export function claimChunkLoadReload(
|
|
error: unknown,
|
|
{ storage = getSessionStorage(), now = Date.now() }: ChunkReloadOptions = {}
|
|
): boolean {
|
|
if (!storage) return false
|
|
const next = getNextReloadState(error, storage, now)
|
|
return next !== undefined && writeReloadState(storage, next)
|
|
}
|
|
|
|
const claimedErrors = new WeakSet<object>()
|
|
|
|
/**
|
|
* Whether `error` has claimed, or could claim, a reload, without touching the
|
|
* guard. Safe to call during render, where a claim could be discarded along
|
|
* with the render and use up the guard without a reload ever happening.
|
|
*/
|
|
export function peekChunkLoadReload(
|
|
error: unknown,
|
|
{ storage = getSessionStorage(), now = Date.now() }: ChunkReloadOptions = {}
|
|
): boolean {
|
|
if (typeof error === 'object' && error !== null && claimedErrors.has(error)) return true
|
|
return storage !== undefined && getNextReloadState(error, storage, now) !== undefined
|
|
}
|
|
|
|
/**
|
|
* Claims a reload for `error`. Call it after commit (an effect or an error
|
|
* boundary's `onError`), never during render; use `peekChunkLoadReload` there.
|
|
*
|
|
* A claimed reload is remembered per error object, so a boundary's `onError`
|
|
* and its fallback's effect both see it while the guard is only claimed
|
|
* once. A refusal isn't remembered: a retry can rethrow
|
|
* the same error object (`React.lazy` caches its rejected promise), and that
|
|
* retry should get a fresh decision once the guard window has passed.
|
|
*/
|
|
export function getChunkLoadReloadDecision(error: unknown): boolean {
|
|
if (typeof error !== 'object' || error === null) return false
|
|
if (claimedErrors.has(error)) return true
|
|
|
|
const decision = claimChunkLoadReload(error)
|
|
if (decision) claimedErrors.add(error)
|
|
return decision
|
|
}
|