Files
karaoke-gen/frontend/lib/client-error-setup.ts
T
Andrew Beveridge ☄️andClaude Opus 4.7 4b1fd68b14 fix(frontend): crash reporting covers admin routes (move to root layout) (#728)
@coderabbitai ignore

Follow-up to #725 / #726 — found during post-deploy verification.
Test-throwing from \`/admin/crash-test\` showed the default Next.js
"Application error" screen instead of the CrashReport card, and no
pattern landed in Firestore. Root cause: the error-handling
infrastructure was scoped to \`app/[locale]/\`, so routes outside that
tree (\`/admin/*\`) had no coverage.

## Fix

- Move \`ClientErrorInit\` mount from \`app/[locale]/layout.tsx\` to
\`app/layout.tsx\` (root). \`DefaultIntlProvider\` at root already
provides \`crashReport\` translations for admin pages.
- Drop the \`locale\` prop from \`ClientErrorInit\`;
\`client-error-setup\` now auto-detects locale from
\`window.location.pathname\` (first segment, whitelisted against known
locales, falls back to \`"en"\`).
- Add \`app/error.tsx\` and \`app/global-error.tsx\` at root — any
uncaught React error anywhere in the app now renders the CrashReport
card.
- Remove the redundant \`app/[locale]/error.tsx\` and
\`global-error.tsx\` (root covers them; Next.js picks the closest
boundary, so removing avoids duplication).

## Tests

20/20 frontend unit tests pass. Build emits \`out/admin/crash-test/\`
correctly.

## Test plan

- [ ] Deploy, visit \`https://gen.nomadkaraoke.com/admin/crash-test/\`
as admin.
- [ ] Click "Render-time throw" → expect the CrashReport card (not the
default Next.js screen).
- [ ] Click "Async throw" + "Unhandled rejection" → expect two new
\`service=frontend\` patterns in Firestore.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 01:45:27 +00:00

90 lines
3.1 KiB
TypeScript

'use client'
import { reportClientError } from '@/lib/crash-reporter'
import { hardReload, isChunkLoadError, isStale, startAmbientVersionPoll } from '@/lib/version-check'
let installed = false
// Known locale prefixes — matches next-intl routing config. Any route whose
// first segment isn't in this set (e.g. /admin, /app) falls through to 'en'.
const KNOWN_LOCALES = new Set([
'ar', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'fi', 'fr', 'he', 'hi', 'hr',
'hu', 'id', 'it', 'ja', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv',
'th', 'tl', 'tr', 'uk', 'vi', 'zh',
])
function detectLocale(): string {
if (typeof window === 'undefined') return 'en'
const first = window.location.pathname.split('/').filter(Boolean)[0]
if (first && KNOWN_LOCALES.has(first)) return first
return 'en'
}
function buildContext(userEmail: string | null) {
return {
href: typeof window !== 'undefined' ? window.location.href : '',
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
innerWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,
innerHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,
locale: detectLocale(),
userEmail,
}
}
export function installGlobalErrorHandlers(getUserEmail: () => string | null) {
if (installed) return
if (typeof window === 'undefined') return
installed = true
const maybeReloadForChunkError = async (err: unknown): Promise<boolean> => {
if (!isChunkLoadError(err)) return false
const staleResult = await isStale().catch(() => null)
// If the bundle is stale OR we can't verify, still reload — ChunkLoadError
// by itself is strong signal of post-deploy mismatch.
const triggered = hardReload(staleResult?.latestSha)
return triggered
}
window.addEventListener('error', (event) => {
const err = event.error ?? new Error(event.message || 'Unknown window error')
void (async () => {
const reloaded = await maybeReloadForChunkError(err)
if (reloaded) return
void reportClientError({
error: err,
source: 'window.onerror',
context: buildContext(getUserEmail()),
extra: {
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
},
})
})()
})
window.addEventListener('unhandledrejection', (event) => {
const err = event.reason instanceof Error ? event.reason : new Error(String(event.reason))
void (async () => {
const reloaded = await maybeReloadForChunkError(err)
if (reloaded) return
void reportClientError({
error: err,
source: 'unhandledrejection',
context: buildContext(getUserEmail()),
})
})()
})
// Ambient poll: every 10 min, if stale, stash info for UI to pick up via
// a CustomEvent. We do NOT auto-reload here — that's reserved for crashes.
startAmbientVersionPoll((r) => {
try {
sessionStorage.setItem('karaoke_latest_sha', r.latestSha)
window.dispatchEvent(new CustomEvent('karaoke:stale-version', { detail: r }))
} catch {
/* ignore */
}
})
}