Sentry Integration Guide

Technology: sentry · Category: monitoring · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/sentry

Insight:

Sentry is codeAmani's monitoring standard — errors, traces, logs, replays, crons, and AI-agent spans in one place. On SDK v11 the single most important line is an explicit dataCollection: sendDefaultPii is gone, and an unset dataCollection now ships IPs, cookies, headers, request bodies, prompts and stack locals. Every Sentry.init imports the shared privacy baseline.

███████╗███████╗███╗   ██╗████████╗██████╗ ██╗   ██╗
██╔════╝██╔════╝████╗  ██║╚══██╔══╝██╔══██╗╚██╗ ██╔╝
███████╗█████╗  ██╔██╗ ██║   ██║   ██████╔╝ ╚████╔╝
╚════██║██╔══╝  ██║╚██╗██║   ██║   ██╔══██╗  ╚██╔╝
███████║███████╗██║ ╚████║   ██║   ██║  ██║   ██║
╚══════╝╚══════╝╚═╝  ╚═══╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝

Sentry Integration Guide

Focus: @sentry/nextjs 11.x on Next.js 16 (App Router), privacy-first dataCollection, source maps, logs, tracing + AI agent monitoring, Session Replay, cron monitors, and Claude Code triage through the official Sentry MCP server and Seer.

Overview

Sentry is codeAmani's monitoring standard: one SDK captures errors, spans, structured logs, metrics, session replays, cron check-ins, and AI (gen_ai) spans, all linked by trace. The hosted MCP server at https://mcp.sentry.dev/mcp lets Claude Code read issues/traces/logs, run Seer root-cause analysis, and (if you grant the skill) triage.

Pinned versions (verified 2026-10-20 via npm view / PyPI):

Package Version Notes
@sentry/nextjs 11.8.0 (latest) v10 line: 10.76.2 (v10 dist-tag). Peer: next ^14 || ^15 || ^16. Node >=20.19.0. TypeScript >=5.0.4.
@sentry/cli 3.8.0 3.0 removed releases files … / files … and API-key auth.
@sentry/mcp-server 0.42.0 Only for the stdio / self-hosted MCP transport.
sentry-sdk (Python) 2.72.0 stable 3.0.0a7 is alpha — 3.x also swaps send_default_pii for data_collection.
next 16.4.2 Next 16 renamed middleware.ts → proxy.ts.
flowchart LR
    A["App throws error<br/>e.g. M-Pesa callback"] --> B["Sentry SDK v11<br/>dataCollection baseline"]
    B --> C["Sentry platform<br/>issue + trace + logs"]
    C --> D["Seer<br/>root cause + fix"]
    C --> E["MCP server<br/>inspect / seer / triage"]
    D --> E
    E --> F["Claude Code<br/>triage + propose fix"]

Official Documentation

Resource URL
Next.js SDK https://docs.sentry.io/platforms/javascript/guides/nextjs/
Manual setup (Next 15+/16, Turbopack) https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
v10 → v11 migration https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/
dataCollection option https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
Build options (withSentryConfig) https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/build/
Agent tracing (AI SDK, Anthropic, …) https://docs.sentry.io/platforms/javascript/guides/nextjs/agent-tracing/
Sentry MCP server https://mcp.sentry.dev/
Seer https://docs.sentry.io/product/ai-in-sentry/seer/
Pricing & quotas https://docs.sentry.io/pricing/
sentry-cli https://docs.sentry.io/cli/

SDK v11 — what changed (read before copying any old snippet)

v10 v11 (current) Action
sendDefaultPii: false (restrictive default) Removed. dataCollection — unset = collect everything Import PRIVACY_BASELINE in every Sentry.init (leaving sendDefaultPii is now a type error)
enableLogs: true Removed. Logs send whenever you call Sentry.logger.* or add a log integration Delete the flag; scrub with beforeSendLog
Transactions + beforeSendTransaction / ignoreTransactions Span streaming is default; transactions no longer exist Use beforeSendSpan (StreamedSpanJSON: name, attributes) and ignoreSpans
Scope tags on transactions Tags reach errors only; spans/logs/metrics use attributes Sentry.setAttribute(s) for span-searchable context
import { withSentryConfig } from "@sentry/nextjs" import { withSentryConfig } from "@sentry/nextjs/config" Update next.config.ts
AI SDK / Anthropic needed manual setup vercelAIIntegration, anthropicAIIntegration are default when tracing is on (server only) Set dataCollection.genAI to keep prompts out
captureMessage had no stack Stack traces attached by default (attachStacktrace) Expect new issue groups after upgrade
inboundFiltersIntegration EventFilters (export removed) Rename filters by integration name

traceLifecycle: "static" (or SENTRY_TRACE_LIFECYCLE=static on Node/Vercel Edge) temporarily restores transaction mode; Sentry says it will be removed in a future major.


Next.js 16 setup (@sentry/nextjs 11.x)

npm install @sentry/nextjs@^11.8.0
# or the wizard (creates the same files):  npx @sentry/wizard@latest -i nextjs

Files (project root, or src/):

File Role
sentry.data-collection.ts codeAmani privacy baseline: the dataCollection object every init imports
instrumentation-client.ts Browser init + onRouterTransitionStart + Session Replay
sentry.server.config.ts Node.js runtime init (beforeSend, beforeSendLog, beforeSendSpan)
sentry.edge.config.ts Edge runtime init
instrumentation.ts register() loads server/edge config; onRequestError = Sentry.captureRequestError
app/global-error.tsx Captures React render errors
next.config.ts withSentryConfig from @sentry/nextjs/config: source maps, tunnel, Vercel crons
proxy.ts Next 16 proxy (ex-middleware), must exclude the tunnel route

All of these live in examples/ and type-check against @sentry/nextjs@11.8.0 + next@16.4.2 under tsc --strict.

1. The privacy baseline (required)

// sentry.data-collection.ts
import type * as Sentry from "@sentry/nextjs";

type SentryInitOptions = NonNullable<Parameters<typeof Sentry.init>[0]>;
export type DataCollectionOptions = NonNullable<SentryInitOptions["dataCollection"]>;

export const EXTRA_DENY_TERMS = [
  "forwarded", "-ip", "remote-", "via", "-user", // Sentry's documented extras
  "phone", "msisdn", "email", "card",            // codeAmani payment data
] as const;

const deny = { deny: [...EXTRA_DENY_TERMS] };

export const PRIVACY_BASELINE = {
  userInfo: false,            // no auto IP/email/username (explicit setUser({ id }) still sends)
  cookies: false,
  httpHeaders: { request: deny, response: deny },
  httpBodies: [],             // never ship request/response bodies
  urlQueryParams: deny,
  graphQL: { document: false, variables: false },
  genAI: { inputs: false, outputs: false }, // keep tokens + latency, drop prompt text
  databaseQueryData: false,
  queues: false,
  stackFrameVariables: false, // locals hold phone numbers / PHI
  frameContextLines: 5,
} satisfies DataCollectionOptions;

The v11 defaults this overrides (from the migration guide): userInfo: true, cookies: true, request+response headers, all request/response bodies, genAI inputs+outputs, databaseQueryData: true, stackFrameVariables: true. Sentry's built-in key denylist (auth, token, secret, password, key, jwt, session, …) still applies on top, but it matches key names only: a phone number in a field called msisdn sails through unless you deny it. dataCollection does not govern Session Replay (see below).

2. Server, edge, client

// sentry.server.config.ts
import * as Sentry from "@sentry/nextjs";
import { PRIVACY_BASELINE } from "./sentry.data-collection";

const REDACT = /(254\d{9})|(sntrys_[\w-]+)|(Bearer\s+[\w.-]+)/gi;
const scrub = (value: string): string => value.replace(REDACT, "[redacted]");

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.VERCEL_ENV ?? process.env.NODE_ENV,
  dataCollection: PRIVACY_BASELINE,
  tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
  ignoreSpans: [{ attributes: { "sentry.op": "http.server", "url.path": "/api/health" } }],
  beforeSend(event) {
    if (event.user) delete event.user.email;
    for (const ex of event.exception?.values ?? []) {
      if (ex.value) ex.value = scrub(ex.value);
    }
    if (event.message) event.message = scrub(event.message);
    return event;
  },
  beforeSendLog(log) {
    if (log.level === "debug" || log.level === "trace") return null;
    log.message = scrub(String(log.message));
    return log;
  },
  beforeSendSpan(span) {
    span.name = scrub(span.name);
    return span;
  },
});

sentry.edge.config.ts is the same minus the hooks (see examples/). The client:

// instrumentation-client.ts
import * as Sentry from "@sentry/nextjs";
import { PRIVACY_BASELINE } from "./sentry.data-collection";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.NEXT_PUBLIC_VERCEL_ENV ?? process.env.NODE_ENV,
  dataCollection: PRIVACY_BASELINE,
  tracesSampleRate: process.env.NODE_ENV === "production" ? 0.1 : 1.0,
  tracePropagationTargets: ["localhost", /^\/(?!\/)/],
  integrations: [
    Sentry.replayIntegration({
      maskAllText: true,
      maskAllInputs: true,
      blockAllMedia: true,
      block: ["[data-payment-form]"],
    }),
  ],
  replaysSessionSampleRate: 0,   // error-only replays
  replaysOnErrorSampleRate: 1.0,
});

export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
// instrumentation.ts
import * as Sentry from "@sentry/nextjs";

export async function register(): Promise<void> {
  if (process.env.NEXT_RUNTIME === "nodejs") await import("./sentry.server.config");
  if (process.env.NEXT_RUNTIME === "edge") await import("./sentry.edge.config");
}

export const onRequestError = Sentry.captureRequestError;

3. withSentryConfig + tunnel route

// next.config.ts
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs/config"; // v11 subpath

const nextConfig: NextConfig = {};

export default withSentryConfig(nextConfig, {
  org: process.env.SENTRY_ORG,
  project: process.env.SENTRY_PROJECT,
  authToken: process.env.SENTRY_AUTH_TOKEN, // build env only
  widenClientFileUpload: true,
  sourcemaps: { deleteSourcemapsAfterUpload: true },
  tunnelRoute: "/monitoring",
  _experimental: { vercelCronsMonitoring: true },
  bundleSizeOptimizations: { excludeDebugStatements: true },
  silent: !process.env.CI,
});

Tunnel route: tunnelRoute proxies browser envelopes through your own origin so ad-blockers don't drop them (adds server load; doesn't work with self-hosted Sentry). Use a fixed string, not true (random per deploy). On Turbopack (Next 16 default) Sentry cannot auto-skip the tunnel inside your proxy, so exclude it in proxy.ts:

// proxy.ts (Next 16; was middleware.ts in Next 15)
export const config = {
  matcher: ["/((?!monitoring|_next/static|_next/image|favicon.ico).*)"],
};

Source maps

npx @sentry/cli@3 sourcemaps inject ./dist
npx @sentry/cli@3 sourcemaps upload --release "$VERSION" ./dist

Logs

Logs are on by default in v11, with no flag. Anything you send with Sentry.logger.* (or capture via consoleLoggingIntegration, pinoIntegration, createSentryWinstonTransport, createConsolaReporter) is billed per GB.

import * as Sentry from "@sentry/nextjs";

Sentry.logger.info("Checkout completed", { order_id: orderId, cart_value: 99.99 });
Sentry.logger.info(Sentry.logger.fmt`User ${userId} purchased ${productName}`);
Sentry.setAttributes({ user_tier: "pro" }); // shared by logs, metrics, spans

Prefer one wide event per operation over many thin logs. Never log raw M-Pesa or Stripe payloads; beforeSendLog (see server config) is the scrub/drop hook. If you add consoleLoggingIntegration, every console.* at the chosen levels ships to Sentry.


Tracing (span streaming)

await Sentry.startSpan({ name: "stripe.checkout.create", op: "http.client" }, async () =>
  stripe.checkout.sessions.create(params),
);

Server Actions: wrap with Sentry.withServerActionInstrumentation("name", { headers: await headers() }, fn). Don't pass formData / recordResponse: true unless you have scrubbed them, because they attach user input to the event.

AI / agent monitoring (AI SDK + Anthropic)

As of SDK 11.0.0 the AI integrations are default whenever tracing is enabled, with no wrapper and no experimental_telemetry flag:

Integration Library Versions Instrumented calls
vercelAIIntegration ai >=3.0.0 <=7 generateText, streamText, embed, embedMany, rerank, ToolLoopAgent.generate/stream, experimental_decide (SDK ≥11.7.0 + AI SDK ≥7.0.128); generateObject/streamObject only on AI SDK ≤6
anthropicAIIntegration @anthropic-ai/sdk >=0.19.2 <1.0.0 messages.create, messages.stream, beta.messages.create, legacy completions.create

Also default: OpenAI, Google Gen AI, LangChain, LangGraph, Mistral, Groq, Together AI.

Rules:

See examples/app/api/chat/route.ts.

Session Replay privacy

Replay is not controlled by dataCollection. Defaults mask all text (maskAllText), all inputs (maskAllInputs) and block all media (blockAllMedia). codeAmani rules:

Cron monitors

await Sentry.withMonitor("nightly-payment-reconcile", reconcilePayments, {
  schedule: { type: "crontab", value: "0 3 * * *" },
  checkinMargin: 5,
  maxRuntime: 10,
  timezone: "America/New_York",
});

MCP Server (Claude Code)

# Remote, OAuth (recommended)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# Scoped to one org / project (hides find_organizations / find_projects)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp/{organizationSlug}/{projectSlug}

Run /mcp to finish OAuth if the browser flow doesn't open. Sentry also publishes a Claude Code plugin with a sentry-mcp subagent: claude plugin marketplace add getsentry/sentry-mcp then claude plugin install sentry-mcp@sentry-mcp.

Token header (changed): to bypass OAuth with a user auth token, send Authorization: Sentry-Bearer <token>. Plain Bearer is reserved for the MCP's own OAuth tokens and will fail.

{
  "mcpServers": {
    "sentry": {
      "type": "http",
      "url": "https://mcp.sentry.dev/mcp?skills=inspect,seer",
      "headers": { "Authorization": "Sentry-Bearer ${SENTRY_ACCESS_TOKEN}" }
    }
  }
}

Skills (permission bundles)

Skill Default Grants
inspect on Read-only: issues, events, traces, logs, replays, releases, monitors, profiles, dashboards, docs
seer on analyze_issue_with_seer (root cause + fix)
triage off update_issue, add_issue_note, link_issue / unlink_issue
project-management off create/update projects, teams, DSNs, uptime/metric monitors, alert rules
docs off Deprecated (docs tools now live in inspect)

Narrow with ?skills=inspect,triage or ?disable-skills=seer on the URL, or MCP_SKILLS / MCP_DISABLE_SKILLS for stdio. codeAmani default: inspect + seer; add triage only for a deliberate triage session.

Most-used tools: get_sentry_resource (paste any Sentry URL), get_issue_details, search_issues, search_errors, search_traces, search_logs, search_events, get_trace_details, get_span_details, get_event_stacktrace, get_issue_breadcrumbs, search_ai_conversations, analyze_issue_with_seer, find_monitors, get_replay_details, whoami. About 75 tools in total; the full catalog is discoverable via search_sentry_tools / execute_sentry_tool.

Stdio / self-hosted: npx @sentry/mcp-server@latest --access-token=<token> [--host=sentry.example.com]. Its AI-powered search tools need an LLM provider (EMBEDDED_AGENT_PROVIDER = anthropic, openai, azure-openai, or openrouter plus that provider's key).

Seer (AI debugging)


Pricing & quotas (2026-10-20, sentry.io/pricing + docs.sentry.io/pricing)

Plan Price Users Errors Spans Replays Logs Metrics Crons / Uptime Retention
Developer Free 1 5k 5M 50 5 GB 5 GB 1 / 1 30 days
Team $26/mo (annual, default prepaid) Unlimited 50k 5M 50 5 GB 5 GB 1 / 1 up to 90 days
Business $80/mo (annual) Unlimited 50k 5M 50 5 GB 5 GB 1 / 1 up to 90 days + sampled

Overage (Team PAYG): errors from $0.0003625/event (>50k–100k), spans $0.000002/span (>5M–100M), replays $0.00375 (>50–5k), logs and metrics $0.50/GB, cron monitor $0.78, uptime monitor $1.00, continuous profiling $0.0315/hour, UI profiling $0.25/hour, attachments $0.3125/GB over 1 GB. Data past reserved volume + PAYG budget is dropped, not billed. Source maps and releases are free.


Python (sentry-sdk)

Stable is 2.72.0: send_default_pii still exists and defaults to off. Do not set it to True. data_collection is available on 2.x as opt-in, but passing it opts you into its permissive defaults for every key you don't set. 3.0 (alpha 3.0.0a7) removes send_default_pii, makes data_collection always-on, streams spans, and stops scrubbing stack locals by default. When you move to 3.x, set the full baseline:

import os

import sentry_sdk

DENY = {"mode": "denylist", "terms": ["forwarded", "-ip", "remote-", "via", "-user", "phone", "msisdn", "email"]}

sentry_sdk.init(
    dsn=os.environ["SENTRY_DSN"],
    traces_sample_rate=0.1,
    data_collection={
        "user_info": False,
        "http_bodies": [],
        "graphql": {"document": False, "variables": False},
        "gen_ai": {"inputs": False, "outputs": False},
        "mcp": {"inputs": False, "outputs": False},
        "database_query_data": False,
        "queues": False,
        "stack_frame_variables": {"mode": "denylist"},
        "http_headers": {"request": DENY},
        "cookies": DENY,
        "url_query_params": DENY,
    },
)

CLI (sentry-cli 3.x)

npm install -g @sentry/cli@^3.8.0      # or: npx @sentry/cli@3 <cmd>
sentry-cli login                        # auth tokens only (API keys removed in 3.0)
sentry-cli info                         # verify auth + org

sentry-cli releases new "$VERSION"
sentry-cli releases set-commits "$VERSION" --auto
sentry-cli sourcemaps inject ./dist
sentry-cli sourcemaps upload --release "$VERSION" ./dist
sentry-cli releases finalize "$VERSION"
sentry-cli deploys new --release "$VERSION" -e production

sentry-cli issues list -p my-project -s unresolved
sentry-cli monitors list

sentry-cli releases deploys … is now the top-level sentry-cli deploys …. For Next.js apps withSentryConfig already creates + finalizes the release and uploads maps, so only use the CLI for other build targets. Sentry also ships a separate natural-language CLI for agents at https://cli.sentry.dev (not covered here).


Environment Variables

Secrets (store in the vault / Vercel env, never in git):

SENTRY_AUTH_TOKEN=sntrys_...

Non-secret settings:

Variable Where Value
NEXT_PUBLIC_SENTRY_DSN client bundle Project DSN (public by design; it can only send events)
SENTRY_DSN server/edge Same DSN
SENTRY_ORG build Org slug, e.g. codeamani-labs
SENTRY_PROJECT build Project slug
SENTRY_TRACE_LIFECYCLE server (optional) static only as a temporary escape hatch from span streaming

Token scopes: project:releases + org:read for source-map upload. For the MCP with Sentry-Bearer, a user token with org:read, project:read, event:read covers inspect; event:write adds triage.


Automation Workflows

Claude Code slash command: debug a Sentry issue

.claude/commands/sentry.md:

Investigate the Sentry issue: $ARGUMENTS

1. `get_sentry_resource` (or `get_issue_details`) on $ARGUMENTS for the stack trace, tags, user count
2. `analyze_issue_with_seer` for Seer's root cause
3. `search_logs` / `get_trace_details` around the event for context
4. Read the relevant source files and propose a fix as a diff
5. State blast radius (users, events, first/last seen); only call `update_issue` if the triage skill is enabled and I confirm

GitHub Actions: release + source maps for a non-Next build

# .github/workflows/sentry-release.yml
name: Sentry Release
on:
  push:
    tags: ['v*']

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci && npm run build
      - name: Create Sentry release
        env:
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          SENTRY_ORG: ${{ vars.SENTRY_ORG }}
          SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
        run: |
          npx @sentry/cli@3 releases new ${{ github.ref_name }}
          npx @sentry/cli@3 releases set-commits ${{ github.ref_name }} --auto
          npx @sentry/cli@3 sourcemaps inject ./dist
          npx @sentry/cli@3 sourcemaps upload --release ${{ github.ref_name }} ./dist
          npx @sentry/cli@3 releases finalize ${{ github.ref_name }}
          npx @sentry/cli@3 deploys new --release ${{ github.ref_name }} -e production

Pin third-party Actions to a full commit SHA in real repos (see supply-chain/).


codeAmani notes


Common Use Cases

Use case Approach
Debug a production error MCP get_sentry_resource + analyze_issue_with_seer
Triage new issues MCP search_issues → (triage skill) update_issue
Performance investigation MCP search_traces / get_trace_details / get_span_details
AI cost / failure analysis MCP search_ai_conversations; Sentry → Agents dashboard
Missed scheduled job Cron monitor alert; MCP find_monitors / get_monitor_details
Source maps (Next.js) withSentryConfig + SENTRY_AUTH_TOKEN at build
Source maps (other) sentry-cli sourcemaps inject + sourcemaps upload

Troubleshooting

Issue Fix
'sendDefaultPii' does not exist in type … after upgrading Removed in v11. Delete it and pass PRIVACY_BASELINE as dataCollection
'enableLogs' does not exist Removed in v11. Logs are on when you call Sentry.logger.*
withSentryConfig not exported Import from @sentry/nextjs/config
Tags missing on spans / dashboards broke v11 span streaming: use setAttribute; update op/name/attribute filters
beforeSendTransaction never runs Transactions are gone; use beforeSendSpan / ignoreSpans
No AI spans Tracing off, call runs on Edge, or AI SDK registerTelemetry also on (duplicates)
Browser events missing Ad-blocker: set tunnelRoute and exclude it from the proxy.ts matcher
Minified stack traces SENTRY_AUTH_TOKEN missing in build env; try widenClientFileUpload
sentry-cli releases files unknown command Removed in CLI 3.0. Use sourcemaps upload
MCP 401 with token Use Authorization: Sentry-Bearer <token>, not Bearer
MCP has no update_issue triage skill is off by default. Re-auth granting it
Seer unavailable Needs Seer add-on + GitHub/GitLab cloud integration; not on self-hosted

Official docs: