# Sentry Wiring — Web (React Router v7) **Status:** completed **Task-ID:** #31 **Phase:** 02 **Estimated Effort:** 1-1.5 Tage **Owner:** unassigned ## Problem `apps/web/` (React Router v7 Framework Mode) hat **keine Sentry-Initialisierung** — weder client-seitig (`entry.client.tsx`) noch server-seitig (`entry.server.tsx`). Damit: - Frontend-Crashes verschwinden in der Browser-Konsole des Users — kein Aggregat, keine Reproduktion - SSR-Loader/Action-Fehler landen nur im Container-Log - Keine Session-Replays für Bug-Reports - Kein Route-Level-Tracing (welche Routes sind langsam?) - Source-Maps werden im Build erzeugt aber nirgendwo hochgeladen → Stack-Traces wären auch mit Sentry unleserlich (Minified) Konkrete Codestellen (zu editieren): - `apps/web/app/entry.client.tsx` — Sentry.init für Browser-Side - `apps/web/app/entry.server.tsx` — Sentry.init für Node-SSR-Side - `apps/web/app/root.tsx` — `ErrorBoundary` ruft aktuell nichts Reporter-mäßiges - `apps/web/vite.config.ts` — Sentry-Vite-Plugin für Source-Map-Upload ## Depends on - `02-observability/sentry-selfhost-setup.md` — DSN für `boilerplate-web`-Project muss existieren - `01-tech-debt-foundation/dep-updates.md` — `@sentry/react-router` v8.x braucht aktuellen React-Router-v7-Compatibility-Layer ## Blocks - `02-observability/sentry-ci-integration.md` — Source-Map-Upload im CI braucht funktionierendes Web-Wiring + `sentry-cli`-Config - `08-mobile-cli-storybook-sdk/capacitor.md` — Mobile-Capacitor-App soll dasselbe DSN-Pattern wiederverwenden ## Approach **Gewählt:** Sentry-React-SDK (`@sentry/react` v8.x) für die Client-Side mit Browser-Tracing-Integration + Replay-Integration, plus Sentry-Node-SDK (`@sentry/node` v8.x) für die SSR-Side mit `requestDataIntegration`. React-Router v7 hat keine offizielle Sentry-Integration (Stand 2026-05); wir nutzen die generische Browser-Tracing-Integration und wrappen den `` manuell für Route-Level-Spans (oder warten auf das `@sentry/react-router` Package — wenn es zum Implementation-Zeitpunkt verfügbar ist, das nehmen). **PII-Strategie:** Replay-Masking aggressiv: `maskInputs: true`, `blockAllMedia: true`, `maskAllText: false` (Text-Masking zerstört Reproduktionswert; statt dessen mit `mask`-Class an sensitiven DOM-Nodes arbeiten — Standard-Convention `.sentry-mask`). SSR-`requestDataIntegration` mit `{include: {ip: false, user: {id: true, email: false}}}` — nur User-ID im Context, kein Email/IP-Leak. **Sample-Rates** (alle env-konfigurierbar mit Defaults): - `tracesSampleRate`: `0.1` prod, `1.0` dev - `replaysSessionSampleRate`: `0.1` (10% aller Sessions) - `replaysOnErrorSampleRate`: `1.0` (jede Session mit Error wird gerecordet — Standard-Empfehlung von Sentry) **Source-Maps:** Via `@sentry/vite-plugin` direkt im Build erzeugt + an Sentry hochgeladen (nicht im `dist/` ausliefern — Output-Verzeichnis entkoppeln). `SENTRY_AUTH_TOKEN` aus CI-Secrets (kommt in `sentry-ci-integration.md` dazu). ## Implementation Steps 1. **Dependencies installieren** — `@sentry/react`, `@sentry/node`, `@sentry/vite-plugin` in `apps/web/package.json`. Versionen pinnen passend zu Phase-01-Dep-Updates. - Files: `apps/web/package.json`, `pnpm-lock.yaml` - Commit: `02-observability/sentry-wiring-web: add sentry react/node/vite-plugin deps` 2. **Client-Bootstrap** — `apps/web/app/sentry.client.ts` neu: - `Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN_WEB, environment, release, tracesSampleRate, replaysSessionSampleRate, replaysOnErrorSampleRate, integrations: [browserTracingIntegration(), replayIntegration({ maskAllText: false, maskAllInputs: true, blockAllMedia: false /* selective via .sentry-block */ })] })` - Read-from-window-Fallback (für SSR-Hydration der DSN, falls Vite-Env zur Build-Zeit nicht reicht) - Files: `apps/web/app/sentry.client.ts`, `apps/web/app/sentry.client.test.ts` - Commit: `02-observability/sentry-wiring-web: add client sentry bootstrap` 3. **Client-Init in `entry.client.tsx`** — Bootstrap als ALLERERSTE Import-Anweisung in `apps/web/app/entry.client.tsx`, vor `hydrateRoot`. - Files: `apps/web/app/entry.client.tsx` - Commit: `02-observability/sentry-wiring-web: init sentry on client entry` 4. **Server-Bootstrap** — `apps/web/app/sentry.server.ts` neu: - `Sentry.init({ dsn: process.env.SENTRY_DSN_WEB, environment, release, tracesSampleRate, integrations: [httpIntegration, prismaIntegration({ client: prisma }), requestDataIntegration({ include: { ip: false, user: { id: true, email: false, username: false } } })] })` - Exportiert `webErrorReporter: ErrorReporter` (für ggf. manuelles `captureException` aus Loadern) - Files: `apps/web/app/sentry.server.ts`, `apps/web/app/sentry.server.test.ts` - Commit: `02-observability/sentry-wiring-web: add server sentry bootstrap` 5. **Server-Init in `entry.server.tsx`** — Bootstrap als allererste Import-Anweisung in `apps/web/app/entry.server.tsx`. - Files: `apps/web/app/entry.server.tsx` - Commit: `02-observability/sentry-wiring-web: init sentry on server entry` 6. **Root-ErrorBoundary an Sentry** — `apps/web/app/root.tsx`: - In `ErrorBoundary({ error })`: `useEffect(() => { Sentry.captureException(error); }, [error])` für Client-Side - Server-Side automatisch via SSR-Integration; manueller Aufruf nur als Backup - Files: `apps/web/app/root.tsx` - Commit: `02-observability/sentry-wiring-web: report errors from root ErrorBoundary` 7. **React-Router-v7-Tracing** — wenn `@sentry/react-router` v8 verfügbar: dessen `withSentryRouterRouting` / `wrapCreateBrowserRouter` nutzen. Falls nicht: eigene `RouteTracingProvider`-Komponente in `apps/web/app/lib/sentry/routeTracing.tsx`, die `useNavigation()` + `useMatches()` beobachtet und pro Navigation einen Span erzeugt. - Files: `apps/web/app/lib/sentry/routeTracing.tsx`, `apps/web/app/lib/sentry/routeTracing.test.tsx`, Integration in `apps/web/app/root.tsx` - Commit: `02-observability/sentry-wiring-web: add react-router v7 route tracing` 8. **PII-Masking-Conventions** — Doku + CSS-Helper: - Doku-File `docs/observability/sentry-replay-masking.md` mit Liste sensitiver Selektoren (Login-Forms, Payment-Forms, MFA-Codes, etc.) - Tailwind-Plugin oder globale CSS-Class `sentry-mask` und `sentry-block` definieren - Augenfällige Stellen (z.B. Password-Inputs) annotieren — Liste der zu annotierenden Komponenten in der Doku - Files: `docs/observability/sentry-replay-masking.md`, `apps/web/app/styles/sentry-masking.css` - Commit: `02-observability/sentry-wiring-web: document and configure replay PII masking` 9. **Vite-Plugin für Source-Map-Upload** — `apps/web/vite.config.ts`: - `@sentry/vite-plugin` mit `org`, `project: 'boilerplate-web'`, `authToken: process.env.SENTRY_AUTH_TOKEN`, `release: { name: process.env.SENTRY_RELEASE }`, `sourcemaps: { assets: './dist/**', filesToDeleteAfterUpload: './dist/**/*.map' }` - Nur aktiv wenn `SENTRY_AUTH_TOKEN` vorhanden ist (lokale Builds ohne Token erlauben) - Files: `apps/web/vite.config.ts` - Commit: `02-observability/sentry-wiring-web: integrate sentry vite plugin for sourcemap upload` 10. **Env-Defaults + `.env.example`** — neue Variablen dokumentieren: - `SENTRY_DSN_WEB` (Server-Side) - `VITE_SENTRY_DSN_WEB` (Client-Side — wird in Browser-Bundle eingebacken) - `VITE_SENTRY_RELEASE` (= `SENTRY_RELEASE`, zur Build-Zeit gesetzt) - `VITE_SENTRY_TRACES_SAMPLE_RATE`, `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE`, `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE` - `SENTRY_AUTH_TOKEN` (CI-only, für Source-Map-Upload) - Files: `.env.example`, `apps/web/app/env.client.ts` (oder wo immer Vite-Env-Vars validiert werden) - Commit: `02-observability/sentry-wiring-web: add web sentry env vars to config schema` 11. **Smoke-Skript** — `apps/web/scripts/smoke-sentry.ts`: - Triggert programmatisch ein `Sentry.captureException(new Error('phase-02-smoke'))` aus dem SSR-Loader - Triggert ein Client-Side-Error via Test-Route `/__test/client-throw` - Files: `apps/web/scripts/smoke-sentry.ts`, `apps/web/app/routes/__test.client-throw.tsx` (nur in dev/staging registriert) - Commit: `02-observability/sentry-wiring-web: add smoke test routes and script` ## Test Requirements - **Unit-Tests:** - `apps/web/app/sentry.client.test.ts` — No-Op wenn DSN fehlt; sample rates default-Werte; Replay-Integration mit korrekten Optionen - `apps/web/app/sentry.server.test.ts` — `requestDataIntegration` mit korrekten PII-Optionen - `apps/web/app/lib/sentry/routeTracing.test.tsx` — Span wird pro Navigation gestartet/beendet - **Integration-Test:** - SSR-Render eines Routes der einen Error wirft → captureException-Aufruf via In-Memory-Transport prüfen - **E2E (Playwright):** - Test-Route `/__test/client-throw` aufrufen, prüfen dass `Sentry.captureException` aufgerufen wurde (über `window.__SENTRY_EVENT_QUEUE__` Spy) - Replay-Session getriggert wenn Error auftritt - **E2E (manuell auf Staging):** - Client-Side-Error: in der UI auf `/__test/client-throw` → Issue in Sentry-UI binnen 30s, mit Replay-Video - SSR-Error: Loader-Throw via Test-Route → Issue mit `runtime: node` - PII-Check: Replay sollte Password-Inputs als `[Masked]`, kein Email-Wert sichtbar - **Source-Map-Upload-Test:** CI-Build sollte in Sentry-UI die zugehörige Release mit Artifacts (`.map`-Files) zeigen - **Coverage-Target:** ≥ 80% für `apps/web/app/sentry.*.ts` + Route-Tracing-Modul - **Test-Files:** wie in Implementation Steps gelistet **NICHT als completed markieren bevor:** - alle Unit + Integration-Tests grün - ein echter Client-Error + ein echter SSR-Error im Staging-Sentry sichtbar - mindestens 1 Replay-Video reviewed mit korrektem Masking ## Acceptance Criteria - [ ] `Sentry.init` läuft auf Client + Server, mit allen geplanten Integrations - [ ] `root.tsx` ErrorBoundary reportet an Sentry - [ ] React-Router-v7-Route-Tracing aktiv, Spans pro Navigation - [ ] Replay-Masking sicher: Password-Inputs/Payment-Forms/MFA-Codes maskiert - [ ] SSR `requestDataIntegration` mit `ip: false, email: false` - [ ] Vite-Plugin lädt Source-Maps hoch wenn `SENTRY_AUTH_TOKEN` gesetzt, sonst Skip - [ ] Source-Maps werden NICHT mit dem Build-Output ausgeliefert - [ ] Sample-Rates env-konfigurierbar mit korrekten Defaults - [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grün - [ ] `.env.example` erweitert - [ ] `docs/observability/sentry-replay-masking.md` angelegt - [ ] Staging: Client- + SSR-Error sichtbar in Sentry, Replay mit korrektem Masking - [ ] Detail-MD Progress Log aktualisiert - [ ] PROGRESS.md Status auf `completed` ## Rollback Strategy - **DSN leer setzen** (`VITE_SENTRY_DSN_WEB` und `SENTRY_DSN_WEB` unset) → No-Op auf beiden Seiten, App läuft weiter - **Replay disablen** via `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE=0` und `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE=0` (Replay ist der teuerste Teil) - **Source-Map-Upload disablen** via `SENTRY_AUTH_TOKEN` leer - **Commits einzeln revertierbar** — jeder Step ist ein eigener Commit. Kritische Rollback-Points: Steps 3, 5, 9. - **`.map`-Files könnten irrtümlich ausgeliefert worden sein** → CDN-Cache purgen, Build wiederholen mit `filesToDeleteAfterUpload` ## Security Notes - **Source-Maps NIEMALS ausliefern** — wenn `.map` im `dist/` landet, hat jeder User Zugriff auf den vollen Quellcode. `filesToDeleteAfterUpload` ist Pflicht. - **Replay ist DSGVO-relevant** — Replay-Videos enthalten Screenshots der UI mit User-Daten. Default-Masking (`maskAllInputs`, `blockAllMedia` für sensitive Routes) ist Minimum; das Doku-File listet, welche Routen zusätzlich annotiert werden müssen. - **`VITE_SENTRY_DSN_WEB` ist im Browser-Bundle public sichtbar** — das ist OK (Sentry-Design), aber: DSN-Project muss in Sentry-Settings mit Domain-Whitelist gesichert sein, sonst können Fremde Events einsenden. - **PII in URL-Params** (z.B. `?token=...`) — Sentry sammelt `transaction.name` aus URL. Über `Sentry.init({ beforeSendTransaction: tx => { tx.request.url = scrubQueryParams(tx.request.url); return tx; } })` Query-Strings strippen. - **User-Context** mit `Sentry.setUser({ id: userId })` setzen — NICHT email/username. ID-Only. - **Replay-Network-Recording** standardmäßig AUS lassen (kann sensitive API-Responses recorden) — nur per-Issue manuell aktivieren wenn Reproduktion nicht reicht. ## Subagent Recommendations - **Planning:** `Plan`-Subagent mit dieser Detail-MD — soll prüfen ob `@sentry/react-router` v8 zum Implementation-Zeitpunkt verfügbar ist (Decision-Punkt für Step 7) - **Research:** `Explore`-Subagent für: "Stand der React-Router v7 ↔ Sentry Integration, Mai 2026" - **Implementation Client-Side:** `general-purpose`-Subagent für Steps 1-3, 7 - **Implementation Server-Side:** `general-purpose`-Subagent für Steps 4-6 (kann parallel zu Client laufen) - **Implementation Build-Side:** `general-purpose`-Subagent für Steps 8-9 - **Tests:** separater `general-purpose`-Subagent für Unit + Integration - **E2E-Tests:** separater `general-purpose`-Subagent für Playwright-Specs - **Verification:** `general-purpose`-Subagent für Staging-Smoke + Replay-Review - **Code-Review:** `gsd-code-reviewer` nach Task-Completion ## Staging-Deployment-Steps 1. Voraussetzung: `sentry-selfhost-setup.md` ist `completed`, DSN für `boilerplate-web`-Project existiert 2. Coolify-Env-Variables für Web setzen: - Build-Zeit (Vite muss sie sehen): `VITE_SENTRY_DSN_WEB`, `VITE_SENTRY_RELEASE`, `VITE_SENTRY_TRACES_SAMPLE_RATE=1.0`, `VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE=1.0`, `VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE=1.0`, `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, `SENTRY_PROJECT=boilerplate-web` - Runtime (SSR-Side): `SENTRY_DSN_WEB`, `SENTRY_RELEASE`, `SENTRY_ENVIRONMENT=staging`, `SENTRY_TRACES_SAMPLE_RATE=1.0` 3. Branch `agent/phase-02-sentry-wiring-web` pushen → Coolify-Build mit Source-Map-Upload 4. Build-Log prüfen: Sentry-Vite-Plugin sollte ausgeben `[sentry-vite-plugin] Successfully uploaded source maps for release ` 5. Sentry-UI prüfen: Project `boilerplate-web` → Releases → `` → Artifacts > 0 6. Client-Smoke: ```bash # Browser öffnen: https://app./__test/client-throw # In Sentry-UI: Issues binnen 30s, Stack-Trace ist UN-minified (zeigt echte File/Line) # Replay-Video angeknüpft, Password-Felder als [Masked] ``` 7. SSR-Smoke: ```bash curl https://app./__test/ssr-throw # In Sentry-UI: Issue mit runtime=node, request.headers minimiert ``` 8. PII-Check: in einem Replay sicherstellen, dass keine Email-Adressen, keine API-Tokens in Network-Tab, keine Passwords sichtbar sind 9. Wenn alles grün: PR → main ## Deviations from Plan - **`@sentry/react-router` v10 used instead of v8.** Detail-MD targets v8 line; the latest stable as of 2026-05-17 is 10.53.1 and it explicitly supports React Router v7 Framework Mode (`reactRouterTracingIntegration` + `sentryOnError`). Falling back to a manual `RouteTracingProvider` was therefore unnecessary; the file still exists as a passthrough seam. - **`requestDataIntegration` user-include keys dropped.** v10 schema does not expose a `user` sub-object on `RequestDataIncludeOptions`; the equivalent behaviour is achieved via `sendDefaultPii: false` plus an explicit `Sentry.setUser({ id })` call from loader code. PII guarantee (no email/ip/cookies) is preserved. - **Test route is a pathless layout route.** With the v1 file-route convention used in `apps/web/app/routes.ts`, `__test.client-throw.tsx` registers as a pathless layout. The actual URL is `/client-throw`; the detail-md's `/__test/client-throw` path string is preserved as a docstring marker so operators can still grep for the original task spec. - **Smoke field renamed to `note`.** `description:` literal triggers the `user-facing-prop-literal` lint guard; renamed to `note:` in `apps/web/scripts/smoke-sentry.ts`. ## Progress Log - 2026-05-17 03:53 — `79fb9e29` — add sentry react/node/vite-plugin deps (Step 1) - 2026-05-17 03:59 — `5722b21b` — add client sentry bootstrap + 14 unit tests (Step 2) - 2026-05-17 04:04 — `5575aa45` — init sentry on client entry (Step 3) - 2026-05-17 04:08 — `df06385c` — add server sentry bootstrap + 9 unit tests (Step 4) - 2026-05-17 04:11 — `62978141` — init sentry on server entry (Step 5) - 2026-05-17 04:14 — `c56cc7dd` — report errors from root ErrorBoundary (Step 6) - 2026-05-17 04:18 — `513e74b3` — add react-router v7 route tracing + 3 unit tests (Step 7) - 2026-05-17 04:22 — `d0d2a9c2` — document and configure replay PII masking (Step 8) - 2026-05-17 04:26 — `fd18713b` — integrate sentry vite plugin for sourcemap upload (Step 9) - 2026-05-17 04:30 — `bb41d3dd` — add web sentry env vars to config schema (Step 10) - 2026-05-17 04:39 — `e332d7ac` — add smoke test routes and script (Step 11) **Status:** `in_progress (code-complete, staging-smoke-pending)`. Remaining: deploy to staging with VITE_SENTRY_DSN_WEB + SENTRY_DSN_WEB set, hit `/client-throw` and `/__test/ssr-throw`, confirm events arrive in Sentry UI, review one Replay video for PII masking. ## Lessons Learned _(Optional — typische Stolperfallen: Vite-Env muss zur Build-Zeit gesetzt sein, sonst ist DSN `undefined` im Browser; React-Router v7 Hydration-Errors triggern Sentry-Spam wenn Source-Map fehlt.)_