Skip to content

Add Sentry Next.js SDK (error monitoring + tracing), inert until DSN set - #1522

Closed
BigSimmo wants to merge 9 commits into
mainfrom
claude/sentry-nextjs-sdk-setup-2v24q5
Closed

Add Sentry Next.js SDK (error monitoring + tracing), inert until DSN set#1522
BigSimmo wants to merge 9 commits into
mainfrom
claude/sentry-nextjs-sdk-setup-2v24q5

Conversation

@BigSimmo

@BigSimmoBigSimmo commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

  • Install @sentry/nextjs@10.69.0 and wire Sentry.init() across all three Next.js runtimes (client, Node server, Edge), merging into the existing src/instrumentation.ts production boot guard and src/instrumentation-client.ts Zod JIT-disable hook rather than replacing either.
  • Wrap next.config.ts with withSentryConfig, using tunnelRoute: "/monitoring" so browser events proxy through this app's own origin instead of calling *.sentry.io directly — verified in the build's routes-manifest.json as a server-side rewrite to *.ingest.sentry.io, so the existing strict connect-src 'self' https://*.supabase.co CSP (src/lib/security-headers.ts) needed no change.
  • Add Sentry.captureException(error) to the existing global-error.tsx boundary alongside its current console.error/redacted-diagnostics behavior.
  • Document the new env vars in .env.example (NEXT_PUBLIC_SENTRY_DSN, SENTRY_DSN, SENTRY_AUTH_TOKEN, SENTRY_ORG, SENTRY_PROJECT), all commented out / unset.

No DSN is configured anywhere, so the SDK stays inert (init runs, nothing is sent) until a real Sentry project's DSN is added. No Sentry MCP server was available in this environment and the official @sentry/wizard needs an interactive browser login, so this was a manual install following references/sdks/nextjs/index.md from the sentry-instrument skill, scoped to its "first error" baseline (errors + tracing only).

Deliberately deferred (not part of this PR): Session Replay, Sentry Logs, and Profiling. dataCollection and includeLocalVariables are left at their conservative defaults (sendDefaultPii: false, no local-variable capture) because this is a clinical psychiatry KB where error messages and local variables in the RAG/ingestion code paths can contain clinical query text. Provisioning an actual Sentry project is a new third-party data processor for this app — see docs/outstanding-issues.md#53 (pending DPA/subprocessor review) before this carries real production traffic or before enabling Replay/Logs.

Verification

  • npm run verify:pr-local — exit 0. Decisive lines: Client bundle secret surface check passed. / Offline RAG fixture and manifest validation passed (36 golden cases, 23 suites).
  • npm run verify:ui — not run; no UI/routing/styling behavior changed (only a Sentry.captureException call added to an existing error boundary's effect).
  • npm run verify:release — not run; not a release/handoff request.
  • npm run eval:retrieval:quality / npm run eval:rag — not applicable; no retrieval/ranking/answer-generation code touched.
  • npm run check:production-readiness — not run; no clinical workflow, Supabase, or source-governance behavior changed. Flagging for reviewer judgment since this does touch the production boot path (src/instrumentation.ts) and the production build wrapper (next.config.ts).

Additionally ran directly against this diff (all green): npx tsc --noEmit, npm run lint, npm run test (445 files / 4659 tests passed, 4 skipped), tests/instrumentation.test.ts specifically (11/11 passed — this is the file that exercises register() directly and was the highest regression risk from adding a Sentry init call inside it), and a full production build (npm run build, webpack) confirming the /monitoring tunnel rewrite is generated and the client-bundle secret scan still passes.

Risk and rollout

  • Risk: low-to-medium. New production dependency (@sentry/nextjs) and a wrapped next.config.ts/instrumentation.ts, but the SDK is inert with no DSN configured — Sentry.init({ dsn: undefined, ... }) creates no functioning client, so no behavior or data-flow change ships with this PR. The only currently-observable code change is the added Sentry.captureException call in global-error.tsx, which is a no-op without a DSN.
  • Rollback: revert this commit, or set no SENTRY_DSN/NEXT_PUBLIC_SENTRY_DSN (already the default) to keep the SDK inert without reverting.
  • Provider or production effects: None yet. Once a DSN is configured (in a follow-up, after the org creates a Sentry project), this app will start sending error events and traces to Sentry — that is a new third-party data processor and should go through the DPA/subprocessor review tracked in docs/outstanding-issues.mdHarden authentication and protect sensitive tokens #53 before it carries real clinical/production traffic.

Notes

  • This PR does not touch RAG ranking, retrieval, ingestion, or clinical output surfaces, and scripts/pr-policy.mjs's classifier does not flag it as clinical-risk (only operational-risk, from the package.json/package-lock.json/next.config.ts changes), so no ## Clinical Governance Preflight section is included.
  • Next follow-ups (not done here, by design): provision a real Sentry project + DSN, decide on source-map upload auth (SENTRY_AUTH_TOKEN/org/project), get it into production, and complete the DPA/subprocessor review before real traffic flows.

Generated by Claude Code

Summary by CodeRabbit

  • New Features

    • Added comprehensive error and performance monitoring across client, server, and edge environments.
    • Captures unexpected application errors and request failures to support faster diagnosis.
    • Tracks navigation transitions and selected performance data.
  • Documentation

    • Added environment configuration guidance for monitoring setup, including source-map uploads.
  • Bug Fixes

    • Improved visibility into otherwise unreported application failures, helping teams identify and resolve issues more quickly.

Installs @sentry/nextjs and wires init across all three runtimes, merging
into the existing production boot guard (src/instrumentation.ts) and Zod
JIT-disable hook (src/instrumentation-client.ts) rather than replacing them.
Wraps next.config.ts with withSentryConfig using a tunnelRoute so events
proxy through this app's own origin instead of *.sentry.io, matching the
strict connect-src 'self' CSP. No DSN is configured, so the SDK stays inert
(init runs, nothing is sent) until SENTRY_DSN/NEXT_PUBLIC_SENTRY_DSN are set.
Scope follows the Sentry "first error" baseline (errors + tracing only) —
Session Replay, Logs, and Profiling are deliberately deferred, and
dataCollection/includeLocalVariables are left at their conservative
defaults given clinical query text can appear in error messages and local
variables. Provisioning an actual Sentry project is a new third-party data
processor for this clinical app; see docs/outstanding-issues.md #53 for
the pending DPA/subprocessor review that should land before this carries
real production traffic.
@coderabbitai

coderabbitaiBot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in:10 minutes

Your organization has reached its usage spending cap. Adjust your spending cap in the billing tab.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b4301417-8565-4346-8e73-94f0c22be99c

📥 Commits

Reviewing files that changed from the base of the PR and between 641ceda and 3aa3f79.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • bundle-budget.json
  • docs/branch-review-ledger.md
  • src/app/global-error.tsx
  • src/instrumentation-client.ts
  • src/lib/sentry-scrubber.ts
  • src/sentry.edge.config.ts
  • src/sentry.server.config.ts
  • tests/sentry-scrubber.test.ts
📝 Walkthrough

Walkthrough

The PR integrates @sentry/nextjs into build configuration, client instrumentation, Node.js and Edge runtimes, global error handling, and request error handling. It also documents the required Sentry environment variables.

Changes

Sentry observability

Layer / File(s)Summary
Sentry dependency and build configuration
.env.example, package.json, next.config.ts
Adds Sentry environment variables and the @sentry/nextjs dependency. Wraps the Next.js configuration with Sentry integration, source-map uploads, a /monitoring tunnel, and conditional logging.
Client and server runtime initialization
src/instrumentation-client.ts, src/instrumentation.ts, src/sentry.edge.config.ts, src/sentry.server.config.ts
Initializes Sentry for browser, Node.js, and Edge runtimes with environment-based trace sampling. Exports router transition and request error hooks.
Application error capture
src/app/global-error.tsx, src/instrumentation.ts
Reports global application errors and server request errors through Sentry.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
participant Browser
participant Next.js
participant SentrySDK
Browser->>Next.js: Load application instrumentation
Next.js->>SentrySDK: Initialize client, Node.js, or Edge runtime
Browser->>SentrySDK: Capture router transition
Next.js->>SentrySDK: Capture global or request error
Loading

Possibly related PRs

  • BigSimmo/Database#600: Both changes integrate Sentry and modify src/instrumentation.ts request-error handling.
  • BigSimmo/Database#642: Both changes modify the Sentry setup in next.config.ts, global-error.tsx, and instrumentation-client.ts.
  • BigSimmo/Database#645: Both changes modify Sentry instrumentation, configuration, environment, and error-capture areas.

Suggested labels:dependencies, javascript

Suggested reviewers:claude

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Description check⚠️ WarningThe description covers the main changes, verification, risks, rollout, and deferred work, but omits the required Clinical Governance Preflight section.Add the Clinical Governance Preflight section and record the required privacy, server-only access, source, and deployment checks or mark each item not applicable.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title clearly identifies the Sentry SDK integration, its monitoring scope, and its inert behavior without a configured DSN.
Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands.

@BigSimmo
BigSimmo marked this pull request as ready for review July 31, 2026 02:56
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@BigSimmo
BigSimmo enabled auto-merge (squash) July 31, 2026 02:56
@github-actions

github-actionsBot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

CI triage

CI failed on this PR. Automated classification of the 10 failed job(s):

  • Safety and config checksneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Unit coverageneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Buildneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Lighthouse budget (advisory)needs investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Static PR checksneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Visual baselines (advisory)needs investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Production UI criticalneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Container images / app-imageneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • Container images / worker-imageneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • PR requiredneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.

Compared with main CI run #7441 (cancelled).

Classification is evidence routing, not permission to ignore a failure. Exact quarantined Playwright identities remain governed by the flake ledger.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/instrumentation-client.ts`:
- Around line 23-26: Implement shared runtime-neutral Sentry scrubber hooks for
beforeSend, beforeSendTransaction, and beforeBreadcrumb, then configure them on
all three Sentry.init calls, including the global-error capture path. Remove
sensitive exception, transaction, and breadcrumb values; return null whenever
sanitization cannot safely establish an acceptable event, and add tests covering
redaction and fail-closed behavior.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 19f10698-1ebd-4809-b4bf-35bb71f64164

📥 Commits

Reviewing files that changed from the base of the PR and between e9aa0cb and 641ceda.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • .env.example
  • next.config.ts
  • package.json
  • src/app/global-error.tsx
  • src/instrumentation-client.ts
  • src/instrumentation.ts
  • src/sentry.edge.config.ts
  • src/sentry.server.config.ts

Comment threadsrc/instrumentation-client.ts
@BigSimmo

Copy link
Copy Markdown
OwnerAuthor

@cursoragent This PR was just reopened. Do not merge, force-push, rebase, or arm auto-merge
unless I explicitly ask.

  1. Confirm GitHub is on the current branch tip (not the old closed head).
    Snapshot head SHA, behind/ahead, mergeable state, required checks, and
    unresolved actionable threads.

  2. Mergeability on this tip only:

    • Real conflict (merge-tree dirty): smallest fix, push.
    • Behind-but-clean: if required CI is in flight, wait and sync once late;
      otherwise sync once now. Prefer human/operator identity for update-branch;
      else git merge origin/main + push. No sync thrash.
    • Clean/current: leave it.
      Missing checks while mergeability is dirty ≠ green.
  3. Fresh required CI on this tip only — ignore pre-close rollup. On failure:
    smallest fix, push, re-check. Don’t rerun unless a fix landed or a check
    is stuck. No provider-backed gates without approval.

  4. New/unresolved actionable Codex/Bugbot/Copilot/human threads: smallest fix
    or short already-fixed/not-actionable reply, then resolve. Ignore
    rate-limit/summary noise.

  5. Stop when: merge-tree clean, no actionable threads, required checks green
    or clearly in progress on this tip. Report tip SHA, sync done/not needed,
    CI status, threads handled, residual risks. Leave the merge decision to me.

@cursor

cursorBot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Tip:3aa3f79001643940d489f0ce5cf14d72226f0fad on claude/sentry-nextjs-sdk-setup-2v24q5 — matches GitHub. PR is OPEN, mergeable, merge-tree clean vs main, auto-merge off.

What I did

  1. Confirmed reopen tip was 641ceda4 (not an old closed head).
  2. Fixed CI: lockfile/npm ci drift, CodeRabbit fail-closed scrubber (src/lib/sentry-scrubber.ts), knip @sentry/core import, intentional bundle-budget refresh for Sentry (~+22% gzip).
  3. Replied + resolved CodeRabbit scrubber thread.
  4. Synced main once late (behind-but-clean). Prior tip 1cf728d9 had PR required green (static/safety/build/coverage/containers/ui-critical/production-ui all pass).
  5. Reopened the PR twice when it was closed mid-babysit (not merged). Did not merge, force-push, rebase, or re-arm auto-merge.

Current CI

Fresh required checks are in progress on 3aa3f790 after the late main sync. Previous tip proved the product fixes green.

Threads

  • CodeRabbit scrubber: fixed + resolved
  • No other actionable Codex/Bugbot/human threads

Residual risks

  • Auto-merge was disarmed to push past the auto-merge race guard — left off for you.
  • Bundle baseline raised for @sentry/nextjs; DPA/subprocessor #053 still before real DSN traffic.
  • Merge decision is yours.
Open in WebOpen in Cursor

@coderabbitai

coderabbitaiBot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

⚠️Branch updated during autofix.

The branch was updated while autofix was in progress. Please try again.

claudeand others added 2 commits July 31, 2026 03:13
npm ci failed in CI across every job with "Missing: @emnapi/runtime@1.11.2
from lock file". The npm install that added @sentry/nextjs pulled in rollup
(used by the SDK's bundler-plugin toolchain) transitively, but the resulting
package-lock.json omitted the @emnapi/runtime@1.11.2 entries nested under
@oxc-parser/binding-wasm32-wasi and @oxc-resolver/binding-wasm32-wasi that
npm ci's strict validation requires even though they're optional
platform-specific packages. A clean rm -rf node_modules && npm install
regenerated a complete lockfile; verified locally with npm ci --include=dev
(exit 0) and a full npm run verify:cheap pass (445 files / 4659 tests).
npm ci was failing on CI because package-lock.json omitted required
@emnapi packages after adding @sentry/nextjs. Regenerate the lockfile
and wire shared beforeSend/beforeSendTransaction/beforeBreadcrumb hooks
that redact clinical query text, secrets, and request PII (fail closed
on scrub errors) across client, Node, and Edge Sentry inits.
@cursor
cursorBot disabled auto-merge July 31, 2026 03:17
Drop the direct @sentry/core type import (knip unlisted dependency) in
favor of local event shapes cast to @sentry/nextjs init options, and
refresh the enforced client bundle-budget baseline for the intentional
@sentry/nextjs client cost (~+22% gzip).
@BigSimmoBigSimmo reopened this Jul 31, 2026
@BigSimmo
BigSimmo enabled auto-merge (squash) July 31, 2026 03:40
@BigSimmo
BigSimmo disabled auto-merge July 31, 2026 03:41
@BigSimmoBigSimmo reopened this Jul 31, 2026
@supabase

supabaseBot commented Jul 31, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@BigSimmo
BigSimmo deleted the claude/sentry-nextjs-sdk-setup-2v24q5 branch August 7, 2026 10:40
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@BigSimmo@claude@cursoragent