Observability¶
Client-side error tracking, breadcrumbs, sessions, and (light) performance tracing for the Expo app — iOS, Android, and web — using Sentry React Native (SDK ~6.x). Wired up alongside the backend Prometheus + OpenTelemetry stack so frontend and backend issues route through one Discord incident channel.
This page is the engineering reference for what we capture, how the DSN flows
in, the source-map pipeline, and the PII policy. For env-var details see
reference/env-vars.md.
What Sentry captures¶
| Signal | When it fires | Notes |
|---|---|---|
| Unhandled errors | Any unhandled JS exception in the React tree | Wrapped via Sentry.wrap(Layout) in app/_layout.tsx. |
| Manual exceptions | Sentry.captureException(err) in critical paths |
See "Adding captures" below. |
| Breadcrumbs — navigation | Every route change (pathname from expo-router) |
Effect lives in RootLayoutNav in app/_layout.tsx. Dynamic segments are collapsed (/u/:handle). |
| Breadcrumbs — HTTP | Every non-2xx response in utils/api.ts::handleResponse |
Logs status + path (no body). |
| Breadcrumbs — WebSocket | Chat WS close with code ≠ 1000 | Logs close code + scrubbed close reason from services/chatService.ts. |
| Sessions | Auto, via enableAutoSessionTracking: true |
Powers Sentry's release-health dashboard (crash-free users / sessions). |
| Performance traces | 10% sample rate | Matches backend OTel sample rate so the two are statistically comparable. |
Source: frontend/utils/sentry.ts (initSentry) and the breadcrumb call
sites listed above.
How the DSN flows in¶
Sentry's DSN is a public identifier — it identifies the project to report to, not the customer. It's safe to bake into the JS bundle.
GCP Secret Manager Build process Bundle (production)
┌───────────────────────────┐ ┌──────────────────────────┐ ┌─────────────────────┐
│ tomoda-sentry-dsn │ ───gcloud──► │ build-with-secrets.sh │ ─────► │ process.env.EXPO_ │
│ tomoda-sentry-auth-token │ │ exports env, execs build │ bake │ PUBLIC_SENTRY_DSN │
└───────────────────────────┘ └──────────────────────────┘ └─────────────────────┘
GCP Secret Manager is the source of truth. The wrapper script frontend/scripts/release/build-with-secrets.sh pulls both values into env vars and execs the build (expo run:ios|android or expo export --platform web). No secret values touch disk; rotation in GCP SM takes effect on the next build automatically.
Local dev: leave EXPO_PUBLIC_SENTRY_DSN unset (or empty). initSentry() no-ops gracefully — Sentry.init is never called, Sentry.captureException is a silent function, and Sentry.wrap is a passthrough. The app runs fully without any Sentry account, which keeps new-contributor friction at zero.
Staging / prod: a gcloud auth login session that can secretAccessor on the two tomoda-sentry-* secrets is all the build needs. See Manual setup → Step 1 (Sentry) in the DevOps repo for the initial provisioning click path.
Source-map upload¶
Without source maps, every Sentry stack frame looks like index.android.bundle:1:347820 — useless. With them, Sentry symbolicates back to the original TypeScript line.
The pipeline differs slightly per platform:
Native (iOS + Android)¶
The @sentry/react-native/expo config plugin (registered in app.config.js) runs the upload step automatically during the native build. It picks up SENTRY_AUTH_TOKEN, SENTRY_ORG, and SENTRY_PROJECT from the environment — all set by build-with-secrets.sh before it execs expo run:*.
The Sentry bundle phase (sentry-xcode.sh) fails the build when the token is missing unless SENTRY_DISABLE_AUTO_UPLOAD=true. To keep tokenless builds working, the with-sentry-upload-guard plugin defaults that flag to true in ios/.xcode.env (export SENTRY_DISABLE_AUTO_UPLOAD=${SENTRY_DISABLE_AUTO_UPLOAD:-true}), and build-with-secrets.sh exports it false when it has a token. So a plain expo run:ios skips upload; a wrapped release build uploads.
Web¶
The Expo web export does not auto-upload source maps. build-with-secrets.sh web runs the upload step explicitly via sentry-cli:
npx expo export --platform webproduces a minified bundle +.mapfiles indist/.npx sentry-cli releases new <release>registers the release (com.tomoda.app@<package.json version>).npx sentry-cli sourcemaps upload --release <release> --strip-prefix <frontend-dir> dist/uploads bundle + maps.npx sentry-cli releases finalize <release>marks the release ready to associate with events.
All three CLI calls run with SENTRY_AUTH_TOKEN / SENTRY_ORG / SENTRY_PROJECT already exported by the wrapper.
The auth token is a secret
SENTRY_AUTH_TOKEN grants write access to the Sentry project (uploads, releases). It is build-time only — never prefixed with EXPO_PUBLIC_, never committed, never logged. Stored in GCP SM as tomoda-sentry-auth-token; rotate via the Sentry UI + gcloud secrets versions add if leaked.
If the token is absent (or build-with-secrets.sh is bypassed and you run expo directly), the build still succeeds — you just get an artifact without source maps uploaded. Errors will still report, they'll just be hard to read until the next build with a valid token.
End-to-end traces (frontend → backend)¶
tracePropagationTargets in initSentry() lists the API origins (api.tomoda.life, api-dev.tomoda.life) that should receive W3C sentry-trace + baggage headers on every outgoing fetch. The backend's OTel pipeline (W3C TraceContext propagator) reads these headers and continues the trace, so a single trace ID in Tempo shows:
[frontend transaction "POST /api/v1/events"]
└─ [API handler span]
└─ [DB INSERT span]
└─ [SQL query]
To follow a trace from a Sentry event into Tempo:
- Open the Sentry issue, click the affected event.
- Trace section shows the trace ID — click the icon next to it to copy.
- In Grafana → Explore → Tempo → search by trace ID.
For this to work, both the frontend SDK and the backend OTel exporter need to sample the same trace ID. We use tracesSampleRate: 0.1 on both — the propagator passes the sample decision through, so once Sentry decides to sample, the backend inherits the decision.
Session Replay, screenshots and attachments¶
All off. initSentry() registers no replay integration and sets replaysSessionSampleRate and replaysOnErrorSampleRate to 0, attachScreenshot: false and attachViewHierarchy: false. No code path calls addAttachment. The mobile replay integration keeps a screenshot ring buffer running for the whole session to serve an on-error capture, which costs CPU and memory on-device and would record chat threads and friend names. If replay is reintroduced, declare masking explicitly (maskAllText, maskAllImages, maskAllVectors on mobile; maskAllText, maskAllInputs, blockAllMedia on web) and update the PII policy below.
Adding a manual breadcrumb¶
Use breadcrumbs to leave a trail of what was happening before an error. Add them where the user is doing something interesting (state transition, optimistic UI update, retry, etc.):
import * as Sentry from '@sentry/react-native';
Sentry.addBreadcrumb({
category: 'event-creation', // your domain
level: 'info', // 'debug' | 'info' | 'warning' | 'error'
message: 'user submitted new event',
data: { has_location: !!loc }, // metadata only, see PII policy
});
Existing breadcrumb call sites — copy the pattern:
- Navigation:
app/_layout.tsx::RootLayoutNav(categorynavigation) - API failures:
utils/api.ts::handleResponse(categoryhttp) - WebSocket:
services/chatService.ts(categorywebsocket)
Capturing an exception¶
For errors that callers don't already throw to a screen, capture them explicitly so they appear in the Sentry Issues feed:
import * as Sentry from '@sentry/react-native';
try {
await refreshSomething();
} catch (err) {
Sentry.captureException(err);
// ... your existing recovery (toast, fallback, etc.)
}
When not to capture:
- Expected failures from third-party fetches (Klipy GIF search, link previews) — these fail often and aren't actionable.
- 4xx from input validation — the user sees the form error; Sentry doesn't need to know.
- Errors that already surface to the user via a thrown error reaching an error boundary — Sentry's auto-handler catches those.
When to capture (already wired in):
AuthContext::loadStoredAuth— silent AsyncStorage failure means the user is silently logged out.AuthContext::refreshAccessToken— silent refresh failure means an unexpected sign-out.AuthContext::refreshUser— silent failure means stale user data in memory.chatService::onmessageJSON parse — server sent malformed payload, always a bug.chatServicereconnect cap reached — covered indirectly via the WS-close breadcrumb + the error callback path.
PII policy¶
Every event, transaction and breadcrumb passes through the pure scrubbers in frontend/utils/sentryScrub.ts before it leaves the device: scrubEvent (beforeSend), scrubTransaction (beforeSendTransaction) and scrubBreadcrumb (beforeBreadcrumb). sendDefaultPii: false is set explicitly, which also stops IP inference (infer_ip: never), route params on navigation spans and default request bodies and auth headers. Coverage: frontend/__tests__/utils/sentryScrub.test.ts.
What is sent¶
| Field | Shape |
|---|---|
| User | { id, ip_address: null }. The opaque user UUID from Sentry.setUser({ id }) in AuthContext, nothing else. Signed out: { ip_address: null }. |
| Exceptions | Type, stack trace (symbolicated with source maps) and the message after free-text scrubbing. |
| Request | URL only: origin + path with ids collapsed. |
HTTP breadcrumbs (fetch, xhr, http) |
Method, status code, origin + collapsed path. Message is <status> <path>. |
| Navigation and deep-link breadcrumbs | Collapsed route (/u/:handle, /events/:id, /plans/join/:token) and route-pattern names (u/[handle]). |
Other breadcrumbs (WebSocket, app.resume, touch) |
Category, level, scrubbed message and scrubbed data. |
| Transactions and spans | Transaction name collapsed like a route. Span descriptions and url attributes keep method + origin + collapsed path. |
| Device, OS, app contexts and tags | Sent after scrubbing, except the user-assigned device name. |
| Hermes profiles | Stack samples and device metadata; no payload data. |
What is not sent¶
| Data | How |
|---|---|
| Email, username, display name, IP | user is rebuilt to { id, ip_address: null }; email patterns are redacted anywhere in text. |
| Phone numbers | + international, (415) 555-0134 and 090-1234-5678 forms are redacted in text; phone keys are redacted wholesale. |
| Passwords, JWTs, bearer/basic tokens, API keys, OTP codes | JWT, Bearer/Basic/Token values, vendor-prefixed keys and 32+ char mixed-case runs are redacted. Values of token, password, secret, code, otp, key, authorization assignments and query params are redacted. |
| Sensitive object keys | Any key containing token, password, secret, apikey, authorization, credential, or exactly code, otp, key, pin, auth, cookie, email, phone, username, ip, lat/lng: value replaced with [redacted] at any depth in extra, contexts, tags, frame vars and breadcrumb data. |
| Request bodies, headers, cookies, query strings, fragments | Dropped wholesale, never scrubbed. URL userinfo is stripped. |
| Ids and handles in paths | UUID, numeric, long hex and long opaque segments become :id. Known dynamic routes (/u/<handle>, /plans/join/<token>, API /users/<handle>) use their placeholder. |
| Console output | console breadcrumbs are dropped. They carry arbitrary logged objects (API payloads, user records) that pattern scrubbing cannot make safe, and the structured HTTP, navigation and WebSocket breadcrumbs already give the trail. |
| DOM selectors (web) | ui.* breadcrumbs keep category and level only; selectors can carry title or alt text. |
| Chat ids, message bodies, event descriptions | Not put in breadcrumbs or captures. |
| Location coordinates | lat/lng assignments and bare decimal coordinate pairs are redacted. |
| Replay, screenshots, view hierarchy, attachments | Disabled, see above. |
Native crash reports (iOS and Android SDK) are built outside the JS hooks. They carry stack traces, device context and the scope's user id; sendDefaultPii: false reaches the native SDKs. Server-side scrubbing and IP storage are project settings the client cannot assert: Settings → Security & Privacy must have data scrubbing on and Prevent storing of IP addresses checked.
If you add a new capture, breadcrumb, tag or context, pass ids and enums only. When in doubt, exclude, and add a case to the scrubber test.
Querying in Sentry UI¶
Common starting points:
| What you want | Where to look |
|---|---|
| Top crashing issues this week | Issues tab, sort by "Events" descending, filter is:unresolved age:-7d. |
| Crashes for a specific user | Issues tab, search user.id:<uuid>. Email is not sent, so look the id up in the admin user directory first. |
| Release health (% crash-free) | Releases tab — driven by enableAutoSessionTracking. |
| Performance | Performance tab — sampled at 10%, so low-volume routes may have sparse data. |
| All events from one device | Issues → drill into any event → Sessions tab on the user's profile. |
Useful filters:
release:0.0.8— narrow to a specific app version (usesEXPO_PUBLIC_APP_VERSION).environment:prod— exclude dev / staging.dist:42— narrow to a specific build number when you have version-collision noise.
Alert routing to Discord¶
Sentry alerts flow to the same Discord webhook the backend Prometheus/Alertmanager uses, giving us one unified incident channel.
This is configured in the Sentry UI, not in code. In the Sentry project's Settings → Integrations → Discord, add a webhook pointed at the existing Discord incidents channel. Then in Alerts → Create Alert Rule, route new issues / regressions to that webhook with whatever threshold you want (typical: "alert when an issue affects > N users in 1h").
Not configured here:
- The Discord webhook URL itself — lives in the DevOps repo's secret store, same one the backend Alertmanager uses.
- Alert thresholds, on-call rotation, escalation — set up in the Sentry UI.
If you need to set this up from scratch on a new Sentry project, file an issue tagging ops; it's a one-time UI walk-through.
Files of interest¶
frontend/utils/sentry.ts—initSentry()+wrapre-export.frontend/utils/sentryScrub.ts:beforeSend,beforeSendTransactionandbeforeBreadcrumbscrubbers, path collapsing.frontend/app/_layout.tsx— callsinitSentry()at module load, wraps the root component, emits navigation breadcrumbs.frontend/contexts/AuthContext.tsx—Sentry.setUser({ id })/Sentry.setUser(null)on auth state changes; captures for silent auth failures.frontend/utils/api.ts— HTTP failure breadcrumbs inhandleResponse.frontend/services/chatService.ts— WebSocket close breadcrumb + parse-error capture.frontend/app.config.js— Sentry Expo config plugin registration.frontend/scripts/release/build-with-secrets.sh— exportsEXPO_PUBLIC_ENV=prodfor native builds and pulls the Sentry DSN + auth token from GCP Secret Manager; DSN differs per environment.