Complete Sentry integration skill pack with 30 skills covering error monitoring, performance tracking, session replay, and observability. Flagship+ tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install sentry-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
Skills (30)
Advanced Sentry troubleshooting for complex SDK issues, silent event drops, source map failures, distributed tracing gaps, and SDK conflicts.
Sentry Advanced Troubleshooting
Overview
This skill addresses complex Sentry issues that go beyond basic setup: events that silently drop, source maps that refuse to resolve, distributed traces with gaps between services, SDK memory leaks, conflicts with other observability libraries, and network-level DSN blocking. Each section provides a systematic diagnosis path with concrete commands and code to identify root causes.
Prerequisites
- Sentry SDK v8 installed and initialized (see
sentry-install-authskill) - Access to application logs, Sentry dashboard, and project settings
- Sentry CLI installed (
npm install -g @sentry/cli) for source map debugging - Network diagnostic tools available (curl, dig)
debug: trueenabled in SDK init for verbose console output during troubleshooting
Instructions
Step 1 — Diagnose Silently Dropped Events
Events can vanish at multiple points between your code and the Sentry dashboard. Work through each layer systematically.
Enable debug mode to see SDK internals:
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
debug: true, // Prints all SDK decisions to console
// Wrap transport to log every outbound envelope
transport: (options) => {
const transport = Sentry.makeNodeTransport(options);
return {
...transport,
send: async (envelope) => {
const [header, items] = envelope;
console.log('[Sentry Transport] Outbound envelope:', {
event_id: header.event_id,
sent_at: header.sent_at,
item_count: items?.length,
});
const result = await transport.send(envelope);
console.log('[Sentry Transport] Response:', result);
return result;
},
};
},
});
Systematic event-drop diagnosis:
async function diagnoseEventDrop(): Promise<void> {
// Layer 1: Is the client alive?
const client = Sentry.getClient();
if (!client) {
console.error('FAIL: Sentry client is null — SDK never initialized');
console.error('Check: Is instrument.mjs loaded via --import flag?');
return;
}
// Layer 2: Is the DSN valid and reachable?
const dsn = client.getDsn();
if (!dsn) {
console.error('FAIL: DSN is null — check SENTRY_DSN env var');
return;
}
console.log('DSN:', `${dsn.protocol}://${dsn.host}/${dsn.projectId}`);
// Layer 3: Is beforeSend silently dropping events?
const opts = client.getOptions();
if (opts.beforeSend) {
console.warn('WARN: beforeSend is configured — it may be returning null');
console.warn('Test by temporarily removing beforeSend to isolate');
}
// Layer 4: Is sampling dropping eventsConfigure Sentry error tracking and performance monitoring for different application architectures.
Sentry Architecture Variants
Overview
Choose the right Sentry SDK, project layout, and tracing strategy for each
application architecture. Every pattern below uses Sentry SDK v8 APIs —
@sentry/node, @sentry/browser, @sentry/react, @sentry/react-native,
@sentry/aws-serverless, and @sentry/google-cloud-serverless. The goal is
one coherent trace from the user's device through every backend hop, regardless
of how many runtimes or deployment targets sit in between.
Deep-dive references for each pattern:
Monolith |
Mobile |
Hybrid |
Prerequisites
- Node.js 18+ (or target platform runtime)
- Sentry organization with at least one project created at sentry.io
SENTRY_DSNavailable as an environment variable (one per Sentry project)- Application architecture documented — service inventory, deployment targets, team ownership mapped
- For distributed tracing: all inter-service transports identified (HTTP, gRPC, Kafka, SQS)
Instructions
Step 1 — Identify Your Architecture and Select SDK Packages
Map every runtime in your system to the correct Sentry SDK package and project layout.
| Architecture | SDK Package | Sentry Projects | Key Integration | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Monolith | @sentry/node |
1 project, env tags | Module tags + ownership rules | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Microservices | @sentry/node (per service) |
1 project per service | Distributed tracing via headers | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Serverless (Lambda) | @sentry/aws-serverless |
1 per function group | Sentry.wrapHandler() + auto-flush |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Serverless (GCP) | @sentry/google-cloud-serverless |
1 per function group | Sentry.wrapCloudEventFunction() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Event-driven (Kafka/SQS) | @sentry/node |
1 per consumer group | continueTrace() from message headers |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Frontend SPA | @sentry/browser or @sentry/react |
1 frontend project | browserTracingIntegration() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Mo
Integrate Sentry into CI/CD pipelines for automated release creation, source map uploads, and deploy notifications.
ReadWriteEditBash(gh:*)Bash(sentry-cli:*)Bash(npm:*)Bash(npx:*)GrepGlob
Sentry CI IntegrationOverviewSentry releases connect errors to the code that caused them. Automating release creation in CI/CD ensures every deploy has commit association (suspect commits), source maps for readable stack traces, and deployment tracking across environments. This skill covers Prerequisites
InstructionsStep 1 — Configure Environment Variables and Auth TokenSet up the three required environment variables in your CI platform. Every
For build tool plugins ( Verify your token works locally before committing CI configuration:
Step 2 — Create the CI Release PipelineTroubleshoot common Sentry integration issues and fixes.
ReadGrepBash(npm:*)Bash(node:*)Bash(curl:*)Bash(npx:*)Bash(sentry-cli:*)Bash(python3:*)
Sentry Common ErrorsOverviewDiagnose and fix the most frequently encountered Sentry SDK integration issues across Node.js, browser, and Python environments. Covers DSN validation, missing events, source map failures, rate limiting, SDK initialization ordering, serverless flush patterns, CORS configuration, and environment tagging. Prerequisites
InstructionsStep 1 — Detect the installed SDK and current configuration! ! ! Grep the project for Sentry initialization to identify the current configuration:
Step 2 — DSN not set or invalid DSN formatThe DSN (Data Source Name) tells the SDK where to send events. Format: Symptoms: No events arrive. SDK silently does nothing.
Python equivalent:
Step 3 — Events not appearing in dashboardSymptoms: Root causes and fixes:
Optimize Sentry costs, reduce event volume, and manage quota spend.
ReadWriteEditGrepGlobBash(curl:*)Bash(node:*)Bash(npx:*)
Sentry Cost TuningReduce Sentry spend by 60-95% through SDK-level sampling, server-side inbound filters, Prerequisites
InstructionsStep 1 — Audit Current Usage via the Stats APIQuery the Sentry Usage Stats API to understand where volume comes from before making changes. This endpoint returns event counts grouped by category over any time period.
Record the baseline numbers. You need these to measure savings after optimization. Step 2 — Configure Error Sampling with
|
| Role | Capabilities | Typical Use |
|---|---|---|
| Owner | Full control: billing, auth, members, all settings. Irremovable. | Founding eng, CTO |
| Manager | Manage all teams, projects, and members. No billing access. | Engineering managers |
| Admin | Manage integrations, projects, teams. No member management. | Tech leads, DevOps |
| Member | View data, act on issues, join/leave teams. Default for new users. | Individual contributors |
| Billing | Payment and subscription management only. No technical access. | Finance team |
Team-level roles (Business/Enterprise only) add granularity within teams:
| Team Role | Additional Capabilities |
|---|---|
| Team Admin | Manage team membership, add/remove projects from the team |
| Contributor | View and act on issues in the team's projects |
A member's effective permissions are the union of their org-level role and all team-level roles they hold. A Member with Team Admin on "payments-team" can manage that team but cannot touch org-wide settings.
Create the team structure:
Implement advanced error capture and context enrichment with Sentry.
Sentry Error Capture
Overview
Capture errors and enrich them with structured context so your team can diagnose production issues in seconds instead of hours. Covers captureException, captureMessage, scoped context (withScope / push_scope), breadcrumbs, custom fingerprinting, and beforeSend filtering using @sentry/node v8 and sentry-sdk v2 APIs.
Prerequisites
- Sentry SDK installed and initialized (
@sentry/nodev8+ orsentry-sdkv2+) - A valid DSN configured via environment variable (
SENTRY_DSN) - Understanding of try/catch (JS) or try/except (Python) error handling
- A Sentry project created at sentry.io
Instructions
Step 1 -- Capture Exceptions with Full Stack Traces
Always pass real Error objects (or Python exception instances), never plain strings. Plain strings lose the stack trace, making debugging far harder.
TypeScript (@sentry/node)
import * as Sentry from '@sentry/node';
// CORRECT -- full stack trace preserved
try {
await riskyOperation();
} catch (error) {
Sentry.captureException(error);
}
// WRONG -- no stack trace, hard to debug
Sentry.captureException('something went wrong');
// Wrapping non-Error values into proper Error objects
Sentry.captureException(new Error(`API returned ${statusCode}: ${body}`));
// Capture with inline context (no scope needed for simple cases)
Sentry.captureException(error, {
tags: { transaction: 'purchase' },
extra: { orderId, amount },
});
Python (sentry-sdk)
import sentry_sdk
# CORRECT -- full traceback preserved
try:
risky_operation()
except Exception as e:
sentry_sdk.capture_exception(e)
# Capture current exception implicitly (inside except block)
try:
risky_operation()
except Exception:
sentry_sdk.capture_exception() # captures sys.exc_info() automatically
Step 2 -- Capture Messages for Non-Exception Events
Use captureMessage for events that are not exceptions but still worth tracking: deprecation warnings, capacity thresholds, business logic anomalies.
TypeScript
// Severity levels: 'fatal' | 'error' | 'warning' | 'info' | 'debug' | 'log'
Sentry.captureMessage('Payment processed successfully', 'info');
Sentry.captureMessage('Deprecated API endpoint accessed', 'warning');
Sentry.captureMessage('Database connection pool exhausted', 'fatal');
Python
sentry_sdk.capture_mCapture your first test error with Sentry and verify it appears in the dashboard.
Sentry Hello World
Overview
Send your first test events to Sentry — a captured message, a captured exception, and a fully-enriched error with user context, tags, and breadcrumbs — then verify each one appears in the Sentry dashboard. This skill covers both Node.js (@sentry/node) and Python (sentry-sdk).
Prerequisites
- Completed
sentry-install-authsetup (SDK installed, DSN configured) - Valid
SENTRY_DSNin environment variables instrument.mjsloaded before app code (Node.js) orsentry_sdk.init()called (Python)- Network access to
*.ingest.sentry.io
Instructions
Step 1 — Verify the SDK Is Active
Before sending test events, confirm the SDK initialized correctly. If getClient() returns undefined, the SDK was never initialized — go back to sentry-install-auth.
TypeScript (Node.js):
import * as Sentry from '@sentry/node';
const client = Sentry.getClient();
if (!client) {
console.error('Sentry SDK not initialized. Ensure instrument.mjs is loaded first.');
console.error('Run with: node --import ./instrument.mjs your-script.mjs');
process.exit(1);
}
console.log('Sentry SDK active — DSN configured');
Python:
import sentry_sdk
client = sentry_sdk.Hub.current.client
if client is None or client.dsn is None:
print("Sentry SDK not initialized. Call sentry_sdk.init() first.")
exit(1)
print("Sentry SDK active — DSN configured")
Step 2 — Capture a Test Message
captureMessage sends an informational event without a stack trace. Use it to verify basic connectivity between your app and Sentry.
TypeScript:
import * as Sentry from '@sentry/node';
// captureMessage returns the event ID (a 32-char hex string)
const eventId = Sentry.captureMessage('Hello Sentry! SDK verification test.', 'info');
console.log(`Message sent — Event ID: ${eventId}`);
// Also test 'warning' level — appears with yellow indicator in dashboard
Sentry.captureMessage('Warning-level test message', 'warning');
// IMPORTANT: flush before process exits or events may be lost
await Sentry.flush(2000);
Python:
import sentry_sdk
event_id = sentry_sdk.capture_message("Hello Sentry! SDK verification test.", level="info")
print(f"Message sent — Event ID: {event_id}")
sentry_sdk.capture_message("Warning-level test message", level="warning")
# Flush to ensure delivery before process exits
sentry_sdk.flush()
Execute incident response procedures using Sentry error monitoring.
Sentry Incident Runbook
Overview
Structured incident response framework built on Sentry's error monitoring platform. Covers the full lifecycle from alert detection through severity classification, root cause investigation using Sentry's breadcrumbs and stack traces, Discover queries for impact analysis, stakeholder communication, resolution via the Sentry API, and postmortem documentation with Sentry data exports.
Prerequisites
- Sentry account with project-level access and auth token (
SENTRYAUTHTOKEN) - Organization slug (
SENTRYORG) and project slug (SENTRYPROJECT) configured @sentry/node(v8+) or equivalent SDK installed in the application- Alert rules configured for critical error thresholds
- Notification channels connected (Slack integration or PagerDuty)
Instructions
Step 1 — Classify Severity
Assign a severity level based on error frequency and user impact. This determines response time and escalation path.
| Severity | Error Criteria | User Impact | Response Time | Escalation |
|---|---|---|---|---|
| P0 — Critical | Crash-free rate below 95% or unhandled exception spike >500/min | Core flow blocked for all users, data loss risk | 15 minutes | PagerDuty page to on-call engineer |
| P1 — Major | New issue affecting >100 unique users per hour | Key feature degraded, no workaround | 1 hour | Slack #incidents channel, tag team lead |
| P2 — Minor | New issue affecting <100 unique users per hour | Feature degraded but workaround exists | Same business day | Slack #alerts-production |
| P3 — Low | Edge case, cosmetic error, staging-only issue | Minimal or no user-facing impact | Next sprint | Add to backlog, assign owner |
Decision logic for classification:
Alert fires →
├── Check crash-free rate (Project Settings → Crash Free Sessions)
│ └── Below 95%? → P0
├── Check unique users affected (Issue Details → Users tab)
│ ├── >100/hr on core flow? → P1
│ └── <100/hr or workaround exists? → P2
└── Staging-only or edge case? → P3
Step 2 — Triage and Investigate
Execute this checklist within the first 15 minutes of a P0/P1 alert.
Initial triage (Sentry UI):
- Open the Sentry issue link from the alert notification
- Check the error frequency graph — determine if the rate is spiking, steady, or declining
- Read the "First Seen" and "Last Seen" timestamps to determine if this is new or a regression
- Check the "Users" count on the issue
Install and configure Sentry SDK authentication with DSN setup.
Sentry Install & Auth
Overview
Install the Sentry SDK, configure DSN-based authentication, and verify error tracking is operational. Covers Node.js (@sentry/node), browser (@sentry/browser), and Python (sentry-sdk) with environment-based configuration and auth token setup for CLI/CI workflows.
Prerequisites
- Node.js 18.19+ or 20.6+ (required for ESM support in Sentry SDK v8)
- Package manager: npm, pnpm, or pip
- Sentry account with a project created at https://sentry.io
- DSN from Project Settings > Client Keys (DSN)
- For CLI/CI: auth token from https://sentry.io/settings/auth-tokens/
Instructions
Step 1 — Install the SDK
Node.js / TypeScript:
npm install @sentry/node
# For profiling support (optional):
npm install @sentry/profiling-node
Browser / Framework-specific:
npm install @sentry/browser
# Or pick your framework:
npm install @sentry/react # React
npm install @sentry/nextjs # Next.js
npm install @sentry/vue # Vue
Python:
pip install sentry-sdk
Step 2 — Store the DSN securely
The DSN (Data Source Name) tells the SDK where to send events. It looks like https://. Never hardcode it — use environment variables.
# .env (add this file to .gitignore)
SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
SENTRY_ENVIRONMENT=development
SENTRY_RELEASE=1.0.0
For production, store the DSN in your secret manager (AWS Secrets Manager, GCP Secret Manager, Vault, etc.) and inject it at deploy time.
Step 3 — Initialize the SDK
Node.js (ESM) — create instrument.mjs at project root:
This file MUST be imported before any other modules. The --import flag ensures Sentry instruments HTTP, database, and framework integrations via monkey-patching at load time.
// instrument.mjs — import BEFORE your app code
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.SENTRY_ENVIRONMENT || 'development',
release: process.env.SENTRY_RELEASE,
// Performance: 100% in dev, 10-20% in production
tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
// Debug mode — disable in production
debug: process.env.NODE_ENV !== 'production',
// Never send PII by default
sendDefaultPii: false,
integrations: [
// Built-in integrations (httpIntegration, expressIntegration)
// are auto-detected — no manual registration needed
],
});
Start your app with th
Identify and fix common Sentry SDK pitfalls that cause silent data loss, cost overruns, and missed alerts.
Sentry Known Pitfalls
Overview
Ten production-grade Sentry SDK anti-patterns that silently break error tracking, inflate costs, or leave teams blind to failures. Each pitfall includes the broken pattern, root cause, and production-ready fix.
For extended code samples and audit scripts, see configuration pitfalls, error capture pitfalls, SDK initialization pitfalls, integration pitfalls, and monitoring pitfalls.
Prerequisites
- Active Sentry project with
@sentry/node>= 8.x or@sentry/browser>= 8.x - Access to the codebase containing
Sentry.init()configuration - Environment variable management (
.env, secrets manager, or CI/CD vars)
Instructions
Step 1: Scan for Existing Pitfalls
# Hardcoded DSNs (Pitfall 1)
grep -rn "ingest\.sentry\.io" --include="*.ts" --include="*.js" src/
# 100% sample rates (Pitfall 2)
grep -rn "sampleRate.*1\.0" --include="*.ts" --include="*.js" src/
# Missing flush calls (Pitfall 3)
grep -rn "Sentry\.flush\|Sentry\.close" --include="*.ts" --include="*.js" src/
# Wrong SDK imports (Pitfall 8)
grep -rn "@sentry/node" --include="*.tsx" --include="*.jsx" src/
Step 2: Pitfall 1 — Hardcoding DSN in Source Code
DSN in source ships in client bundles and cannot be rotated without a deploy. Attackers flood your project with garbage events.
// WRONG
Sentry.init({
dsn: 'https://abc123@o123456.ingest.us.sentry.io/7890123',
});
// RIGHT — environment variable
Sentry.init({ dsn: process.env.SENTRY_DSN });
// RIGHT — browser apps: build-time injection (Vite)
// vite.config.ts: define: { __SENTRY_DSN__: JSON.stringify(process.env.SENTRY_DSN) }
// app.ts: Sentry.init({ dsn: __SENTRY_DSN__ });
Step 3: Pitfall 2 — sampleRate: 1.0 in Production
100% sampling sends every trace. At 500K requests/day, overage is ~$371/month.
// WRONG
Sentry.init({ tracesSampleRate: 1.0 });
// RIGHT — endpoint-specific sampling
Sentry.init({
tracesSampler: ({ name, parentSampled }) => {
if (typeof parentSampled === 'boolean') return parentSampled;
if (name?.match(/\/(health|ping|ready)/)) return 0;
if (name?.includes('/checkout')) return 0.25;
return 0.01; // 1% default
},
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
Step 4: Pitfall 3 — Not Calling flush() in Serverless/CLI
Scale Sentry for high-traffic applications handling millions of events per day.
Sentry Load & Scale
Configure Sentry for applications processing 1M+ requests/day without sacrificing error visibility, burning through quota, or adding measurable SDK overhead. Covers adaptive sampling, connection pooling, multi-region tagging, quota management, SDK benchmarking, batch submission, load testing, and self-hosted deployment considerations.
Prerequisites
- Application handling sustained high traffic (>10K requests/min or >1M events/day)
- Sentry organization with quota and billing access (Settings > Subscription)
@sentry/nodev8+ installed (npm ls @sentry/node)- Performance baseline established (p50/p95/p99 latency without Sentry)
- Event volume estimates calculated per category (errors, transactions, replays, attachments)
Instructions
Step 1 — Implement Adaptive Sampling
Static tracesSampleRate wastes quota at scale because it treats a health check the same as a checkout. Replace it with a traffic-aware tracesSampler that adjusts rates based on endpoint criticality and current load.
Traffic-aware tracesSampler:
import * as Sentry from '@sentry/node';
// Track request volume per endpoint for adaptive rate adjustment
const endpointVolume = new Map<string, { count: number; resetAt: number }>();
const WINDOW_MS = 60_000;
function getAdaptiveRate(name: string, baseRate: number): number {
const now = Date.now();
let entry = endpointVolume.get(name);
if (!entry || now > entry.resetAt) {
entry = { count: 0, resetAt: now + WINDOW_MS };
endpointVolume.set(name, entry);
}
entry.count++;
// Scale down sampling as volume increases within window
// 0-100 req/min: full base rate
// 100-1000: halve it
// 1000+: quarter it
if (entry.count > 1000) return baseRate * 0.25;
if (entry.count > 100) return baseRate * 0.5;
return baseRate;
}
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampler: (samplingContext) => {
const { name, parentSampled } = samplingContext;
// Always respect parent decision for distributed tracing consistency
if (parentSampled !== undefined) return parentSampled ? 1.0 : 0;
// Tier 0: Never sample — high-frequency, zero diagnostic value
if (name?.match(/\/(health|ready|alive|ping|metrics|favicon)/)) return 0;
if (name?.match(/\.(css|js|png|jpg|svg|woff2?|ico)$/)) return 0;
// Tier 1: Always sample — business-critical, low volume
if (name?.includes('/payment') || name?.includes('/checkout')) return 1.0;
if (name?.includes('/auth/login')) return getAdaptiveRate('auth', 0.5);
// Tier 2: Moderate sampling — API mutations (higher signal)
if (name?.startsWith('POST /api/')) return getAdaptiveRate(name, 0.05);
if (name?.startsWith('PUT /api/')) return getAdaptiveRConfigure Sentry for local development with environment-aware settings.
Sentry Local Dev Loop
Overview
Configure Sentry for local development with environment-aware DSN routing, debug-mode verbosity, full-capture sample rates, beforeSend inspection, Sentry Spotlight for offline event viewing, and sentry-cli source map verification. All configuration uses environment variables so nothing leaks into commits.
Prerequisites
@sentry/nodev8+ installed (TypeScript/Node) orsentry-sdkv2+ installed (Python)- Separate Sentry project created for development (different DSN from production)
.envfile withSENTRYDSNDEVandNODE_ENV=development- Network access to
*.ingest.sentry.io(or use Spotlight for fully offline work)
Instructions
Step 1 -- Environment-Aware Configuration
Create an initialization file that routes events to the correct Sentry project based on environment, enables debug logging in dev, and captures 100% of traces locally:
// instrument.mjs — import via: node --import ./instrument.mjs app.mjs
import * as Sentry from '@sentry/node';
const env = process.env.NODE_ENV || 'development';
const isDev = env !== 'production';
Sentry.init({
// Route to dev project locally, prod project in production
dsn: isDev
? process.env.SENTRY_DSN_DEV
: process.env.SENTRY_DSN,
environment: env,
release: isDev ? 'dev-local' : process.env.SENTRY_RELEASE,
// Full capture in dev — you need every event for debugging
tracesSampleRate: isDev ? 1.0 : 0.1,
sampleRate: isDev ? 1.0 : 1.0,
// Verbose SDK output to console in dev
debug: isDev,
// Include PII locally for easier debugging (never in prod)
sendDefaultPii: isDev,
// Sentry Spotlight — shows events in local browser UI
// Install: npx @spotlightjs/spotlight
spotlight: isDev,
beforeSend(event, hint) {
if (isDev) {
const exc = event.exception?.values?.[0];
const label = exc
? `${exc.type}: ${exc.value}`
: event.message || 'event';
console.log(`[Sentry Dev] ${label}`);
console.log(` Tags: ${JSON.stringify(event.tags || {})}`);
}
return event;
},
beforeSendTransaction(event) {
if (isDev) {
const duration = event.timestamp && event.start_timestamp
? ((event.timestamp - event.start_timestamp) * 1000).toFixed(0)
: '?';
console.log(`[Sentry Dev] Transaction: ${event.transaction} (${duration}ms)`);
}
return event;
},
});
Set up environment files to keep DSNs out of source:
# .env.development
SENTRY_DSN_DEV=https://examplePublicKey@o0.ingest.sentry.io/0
SENTRY_ENVIRONMENT=development
NODE_ENV=development
# .env.production
SENTRY_DSN=https://prodPublicKey@o0.ingest.sentry.io/0
SENTRY_ENVIRONMENT=producMigrate to Sentry from other error tracking tools like Rollbar, Bugsnag, or New Relic.
Sentry Migration Deep Dive
Overview
Replace an existing error tracking tool (Rollbar, Bugsnag, New Relic, Raygun, Airbrake) with Sentry using a phased migration that runs both tools in parallel before cutover. This skill covers concept mapping between providers, SDK swap patterns, alert rule migration, team training, and rollback strategy.
Current State
!npm list 2>/dev/null | command grep -iE "sentry|rollbar|bugsnag|raygun|airbrake|honeybadger|newrelic" || echo 'No error tracking packages found'
Prerequisites
- Admin access to the current error tracking tool (API keys, alert rule access)
- Sentry project created with DSN available in environment variables
- Source maps or debug symbols configured for stack trace resolution
- Parallel run timeline agreed with team (2-4 weeks recommended)
- Inventory of current alert rules, integrations, and custom filters
Instructions
Step 1: Map Concepts Between Providers
Build a translation table mapping the current tool's terminology and API surface to Sentry equivalents. Scan the codebase for all calls to the existing SDK.
| Concept | Rollbar | Bugsnag | New Relic | Sentry | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Capture error | rollbar.error(err) |
Bugsnag.notify(err) |
newrelic.noticeError(err) |
Sentry.captureException(err) |
|||||||||||||
| Log message | rollbar.info(msg) |
Bugsnag.notify(msg) |
newrelic.recordCustomEvent() |
Sentry.captureMessage(msg) |
|||||||||||||
| User context | rollbar.configure({ person: {...} }) |
Bugsnag.setUser(id, email) |
newrelic.setUserID(id) |
Sentry.setUser({ id, email }) |
|||||||||||||
| Tags/metadata | rollbar.configure({ custom: {...} }) |
bugsnag.addMetadata(tab, data) |
newrelic.addCustomAttributes() |
Sentry.setTag() / Sentry.setContext() |
|||||||||||||
| Breadcrumbs | rollbar.log(level, msg) |
Bugsnag.leaveBreadcrumb(msg) |
N/A | Sentry.addBreadcrumb({ message }) |
|||||||||||||
| Release tracking | code_version config |
appVersion config |
NEWRELICLABELS |
Sentry.init({ release: 'v1.2.3' }) |
|||||||||||||
| Environment | environment config |
releaseStage config |
NEWRELICAPP_NAME suffix |
Sentry.init({ environment: 'prod' }) |
|||||||||||||
| Error filter | checkIgnore callback |
Configure Sentry across development, staging, and production environments with separate DSNs, environment-specific sample rates, per-environment alert rules, and dashboard filtering.
ReadWriteEditGrepGlobBash(npm:*)Bash(npx:*)Bash(node:*)Bash(sentry-cli:*)
Sentry Multi-Environment SetupOverviewConfigure Sentry to run across development, staging, and production with isolated DSNs, tuned sample rates, environment-aware alert routing, and dashboard filtering. Covers Prerequisites
InstructionsStep 1 — Create Environment-Aware SDK Configuration with Separate DSNsEach environment gets its own DSN pointing to a dedicated Sentry project. This prevents dev noise from inflating production quotas and allows independent rate limits per environment. Set up
TypeScript — environment-aware init with typed config: Integrate Sentry with your observability stack — logging, metrics, APM, and dashboards.
ReadWriteEditGrepBash(node:*)Bash(npx:*)Bash(pip:*)
Sentry Observability IntegrationOverviewWire Sentry into your logging, metrics, APM, and dashboard toolchain so every error carries full context and every metric correlates back to root-cause events. This skill covers three integration layers: structured logging (winston, pino, structlog) with Sentry event ID correlation, business metrics with error-rate tracking, and cross-tool linking via Sentry Discover, Grafana webhooks, and APM tools. See also: Logging integration details | Metrics patterns | APM tool cross-linking Prerequisites
InstructionsStep 1 — Attach Sentry Event IDs to Structured LogsThe core pattern: every log line that triggers a Sentry event carries the event ID, and every Sentry event carries the log context. This creates a two-way link between your log aggregator and Sentry. Winston (Node.js) — custom transport:
Pino (Node.js) — hooks pattern: Set up performance monitoring and distributed tracing with Sentry.
ReadWriteEditGrepBash(node:*)
Sentry Performance TracingOverviewSentry performance monitoring captures distributed traces across your application stack, measuring latency, identifying bottlenecks, and tracking Web Vitals. The v8 SDK uses a span-based API where Prerequisites
InstructionsStep 1 — Configure Tracing and Profiling in SDK InitSet TypeScript (
Python ( Optimize Sentry performance monitoring for lower overhead and higher signal.
ReadWriteEditGrepGlobBash(npm:*)Bash(npx:*)Bash(node:*)Bash(sentry-cli:*)
Sentry Performance TuningOverviewOptimize Sentry's performance monitoring pipeline to maximize signal quality while minimizing SDK overhead and event volume costs. Covers the v8 SDK API for Prerequisites
InstructionsStep 1 — Replace Static
|
| Plan | API Rate Limit | Notes |
|---|---|---|
| Developer | 50 RPM | Shared quota, no reserved volume |
| Team | 1,000 RPM | Per-organization, includes spike protection |
| Business | 10,000 RPM | Per-organization, custom quotas available |
| Enterprise | Custom | Negotiated per contract |
Quota categories (billed separately):
- Errors — exceptions and log messages
- Transactions — performance monitoring spans
- Replays — session replay recordings
- Attachments — file uploads (crash dumps, minidumps)
- Profiles — continuous profiling data
- Cron monitors — scheduled job check-ins
Rate limit headers returned on 429:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-Sentry-Rate-Limit-Limit: 50
X-Sentry-Rate-Limit-Remaining: 0
X-Sentry-Rate-Limit-Reset: 1711324800
Step 2 — Configure Client-Side Sampling
Sampling is the first line of defense. Set sampleRate for errors and tracesSampleRate for performance transactions.
TypeScript / Node.js:
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
// Error sampling: 0.0 (drop all) to 1.0 (capture all)
sampleRate: 0.25, // Capture 25% of errors
// Transaction sampling: 0.0 to 1.0
tracesSampleRate: 0.1, // Capture 10% of transactions
// Dynamic tranDesign production-grade Sentry architecture for multi-service organizations.
Sentry Reference Architecture
Overview
Enterprise Sentry architecture patterns for multi-service organizations. Covers centralized configuration, project topology, team-based alert routing, distributed tracing, error middleware, source map management, and a production-ready SentryService wrapper.
Prerequisites
- Sentry organization at sentry.io (Business plan+ for team features)
@sentry/nodev8+ installed (npm install @sentry/node @sentry/profiling-node)- Service inventory and team ownership documented
- Node.js 18+ (ESM and native fetch instrumentation)
Instructions
Step 1 — Project Structure Strategy
Pattern A: One Project Per Service (3+ services, recommended)
Organization: acme-corp
├── Team: platform-eng
│ ├── Project: api-gateway (Node/Express)
│ ├── Project: auth-service (Node/Fastify)
│ └── Project: user-service (Node/Express)
├── Team: payments
│ ├── Project: payment-api (Node/Express)
│ └── Project: billing-worker (Node worker)
└── Team: frontend
├── Project: web-app (React/Next.js)
└── Project: mobile-app (React Native)
Benefits: independent quotas, team-scoped alerts, per-service rate limits, isolated release tracking.
Pattern B: Shared Project (< 3 services, single team) — one project with Environment tags (production/staging/dev). Simpler setup; outgrow when alert noise exceeds one team.
Step 2 — Centralized Config Module
Create lib/sentry.ts imported by every service to enforce org-wide defaults:
// lib/sentry.ts
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
export interface SentryServiceConfig {
serviceName: string;
dsn: string;
environment?: string;
version?: string;
tracesSampleRate?: number;
ignoredTransactions?: string[];
}
export function initSentry(config: SentryServiceConfig): void {
const env = config.environment || process.env.NODE_ENV || 'development';
Sentry.init({
dsn: config.dsn,
environment: env,
release: `${config.serviceName}@${config.version || 'unknown'}`,
serverName: config.serviceName,
tracesSampleRate: config.tracesSampleRate ?? (env === 'production' ? 0.1 : 1.0),
sendDefaultPii: false,
maxBreadcrumbs: 50,
integrations: [nodeProfilingIntegration()],
ignoreErrors: [
'ResizeObserver loop completed with undelivered notifications',
/Loading chunk \d+ failed/,
'AbortError',
],
tracesSampler: ({ name, parentSampled }) => {
if (parentSampled !== undefined) return parentSampled;
const ignored = config.ignoredTransactions || [
'GET /heaManage Sentry releases with versioning, commit association, and source map uploads.
Sentry Release Management
Overview
Manage the full Sentry release lifecycle: create versioned releases, associate commits for suspect commit detection, upload source maps for readable stack traces, and monitor release health with crash-free rates and adoption metrics. Every production deploy should create a Sentry release so errors are grouped by version and regressions are caught immediately.
Prerequisites
- Sentry CLI installed:
npm install -g @sentry/cli(v2.x) or usenpx @sentry/cli - Auth token with
project:releasesandorg:readscopes from sentry.io/settings/auth-tokens/ - Environment variables set:
SENTRYAUTHTOKEN,SENTRYORG,SENTRYPROJECT - Source maps generated by your build (e.g.,
tsc --sourceMap, Vitebuild.sourcemap: true) - GitHub/GitLab integration installed in Sentry for automatic commit association (Settings > Integrations)
Instructions
Step 1 — Create a Release and Associate Commits
Choose a release naming convention. Sentry accepts any string, but two patterns dominate production usage:
Semver naming ties releases to your package version:
# Semver: my-app@2.1.0
VERSION="my-app@$(node -p "require('./package.json').version")"
sentry-cli releases new "$VERSION"
Commit SHA naming ties releases to exact deployments:
# SHA: my-app@a1b2c3d (short) or full 40-char SHA
VERSION="my-app@$(git rev-parse --short HEAD)"
sentry-cli releases new "$VERSION"
After creating the release, associate commits. This is what powers suspect commits — Sentry's ability to identify which commit likely caused a new issue by matching error stack frames to recently changed files:
# Auto-detect commits since last release (requires GitHub/GitLab integration)
sentry-cli releases set-commits "$VERSION" --auto
# Or specify a commit range manually
sentry-cli releases set-commits "$VERSION" \
--commit "my-org/my-repo@from_sha..to_sha"
When --auto runs, Sentry walks the git log from the previous release's last commit to the current HEAD. It stores each commit's author, changed files, and message. When a new error arrives, Sentry matches the stack trace file paths against recently changed files and suggests the author as the likely owner.
Step 2 — Upload Source Maps and Release Artifacts
Source maps let Sentry translate minified stack traces into original source code. Upload them
Build reliable Sentry integrations with graceful degradation, circuit breakers, and offline queuing.
Sentry Reliability Patterns
Overview
Build Sentry integrations that never take your application down via three pillars: safe initialization with graceful degradation, a circuit breaker that stops hammering Sentry when unreachable, and an offline event queue that buffers errors during outages. Every pattern prioritizes application uptime over telemetry completeness.
Prerequisites
@sentry/nodev8+ (TypeScript) orsentry-sdkv2+ (Python)- A valid Sentry DSN from project settings at
sentry.io - A fallback logging destination decided (console, file, or external logger)
- Understanding of your application shutdown lifecycle (signal handlers, container orchestration)
Instructions
Step 1 — Safe Initialization with Graceful Degradation
Wrap Sentry.init() in try/catch so an invalid DSN, network error, or SDK bug never crashes the app. Track initialization state with a boolean flag. Protect beforeSend callbacks with their own error boundary.
Create lib/sentry-safe.ts with initSentrySafe() and captureError(). See graceful-degradation.md for full implementation.
Key rules:
- Never let
Sentry.init()crash the process — wrap in try/catch, setsentryAvailable = falseon failure - Verify client creation with
Sentry.getClient()— invalid DSNs silently produce no client - Always log errors locally as baseline before attempting Sentry capture
- Wrap user-supplied
beforeSendhooks in nested try/catch — return raw event on hook failure
Step 2 — Circuit Breaker for Sentry Outages
When Sentry is unreachable, continued attempts waste resources and add latency. Track consecutive failures and trip open after a threshold. After cooldown, enter half-open state and send a single probe.
Implement SentryCircuitBreaker class with closed/open/half-open states. See circuit-breaker-pattern.md for full implementation. Expose state via health-checks.md endpoint.
Key rules:
- Default: 5 failures to trip open, 60-second cooldown before half-open probe
- In open state, skip Sentry calls entirely and log to fallback
- On half-open success, reset to closed with zero failure count
- Expose
getStatus()for health check endpoints and monitoring dashboards
Step 3 — Offline Queue, Custom Transport, and Graceful Shutdown
Buffer events when network is unavailable and replay on reconnect. Use bounded file-based queue to survive restarts. Pair with signal handlers that flush via Sentry.close() before process exit.
Implement thre
Best practices for using Sentry SDK in TypeScript and Python.
Sentry SDK Patterns
Overview
Production patterns for @sentry/node (v8+) and sentry-sdk (Python 2.x+) covering scoped error context, breadcrumb strategies, event filtering with beforeSend, custom fingerprinting for issue grouping, and performance instrumentation with spans. All examples use real Sentry SDK APIs.
Prerequisites
- Sentry SDK v8+ installed (
@sentry/node,@sentry/react, orsentry-sdk) SENTRY_DSNenvironment variable configured- Familiarity with async/await (TypeScript) or context managers (Python)
Instructions
Step 1 -- Structured Error Context with Scopes
Use Sentry.withScope() (TypeScript) or sentrysdk.newscope() (Python) to attach context to individual events without leaking state across requests.
TypeScript -- Scoped error capture:
import * as Sentry from '@sentry/node';
type ErrorSeverity = 'low' | 'medium' | 'high' | 'critical';
interface ErrorOptions {
severity?: ErrorSeverity;
tags?: Record<string, string>;
context?: Record<string, unknown>;
user?: { id: string; email?: string };
fingerprint?: string[];
}
const SEVERITY_MAP: Record<ErrorSeverity, Sentry.SeverityLevel> = {
low: 'info',
medium: 'warning',
high: 'error',
critical: 'fatal',
};
export function captureError(error: Error, options: ErrorOptions = {}) {
Sentry.withScope((scope) => {
scope.setLevel(SEVERITY_MAP[options.severity || 'medium']);
if (options.tags) {
Object.entries(options.tags).forEach(([key, value]) => {
scope.setTag(key, value);
});
}
if (options.context) {
scope.setContext('app', options.context);
}
if (options.user) {
scope.setUser(options.user);
}
if (options.fingerprint) {
scope.setFingerprint(options.fingerprint);
}
Sentry.captureException(error);
});
}
Python -- Scoped error capture:
import sentry_sdk
def capture_error(error, severity="error", tags=None, context=None, user=None):
"""Capture exception with isolated scope context."""
with sentry_sdk.new_scope() as scope:
scope.set_level(severity)
if tags:
for key, value in tags.items():
scope.set_tag(key, value)
if context:
scope.set_context("app", context)
if user:
scope.set_user(user)
sentry_sdk.capture_exception(error)
Key rule: Never call Sentry.setTag() or sentrysdk.settag() at the module level inside request handlers. Those m
Configure Sentry security settings and data protection.
Sentry Security Basics
Overview
Configure Sentry's security posture: PII scrubbing with beforeSend, built-in data scrubbing, IP anonymization, browser SDK URL filtering, DSN vs auth token handling, CSP reporting, and GDPR data deletion. Covers both client-side (SDK) and server-side (dashboard) controls.
Prerequisites
- Sentry project created with Owner or Admin role
@sentry/node>= 8.x or@sentry/browser>= 8.x installed (orsentry-sdk>= 2.x for Python)- Compliance requirements identified (GDPR, SOC 2, HIPAA, CCPA)
- List of sensitive data patterns for your domain (PII fields, API keys, tokens)
Instructions
Step 1 — Understand DSN vs Auth Token Security
The DSN (Data Source Name) is a client-facing identifier — it tells the SDK where to send events. It is NOT a secret.
https://<public-key>@o<org-id>.ingest.us.sentry.io/<project-id>
- The DSN cannot read data, delete events, or modify settings
- It is safe to ship in client-side JavaScript bundles
- Restrict abuse via Allowed Domains (Project Settings > Client Keys > Configure)
Auth tokens ARE secrets — they grant API access to read/write/delete data:
# NEVER commit auth tokens — store in CI secrets or vault
# GitHub Actions: Settings > Secrets > SENTRY_AUTH_TOKEN
# GitLab CI: Settings > CI/CD > Variables (protected + masked)
# Generate tokens with MINIMAL scopes:
# CI releases: project:releases, org:read
# Issue triage: project:read, event:read
# NEVER: org:admin, member:admin in CI
# Rotate tokens quarterly — revoke unused tokens immediately
# Create separate tokens per pipeline (staging vs production)
Step 2 — Disable Default PII Collection
sendDefaultPii defaults to false — but always set it explicitly so intent is clear:
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
sendDefaultPii: false, // explicit: no IPs, no cookies, no user-agent
});
When sendDefaultPii: false (default):
- No IP addresses attached to events
- No cookies sent in request data
- No user-agent strings in request headers
- No request body data captured
- User context must be set manually via
Sentry.setUser()
# Python equivalent
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
send_default_pii=False, # default, but be explicit
)
Step 3 — Client-Side PII Scrubbing with beforeSend
Upgrade Sentry SDK versions and migrate breaking API changes.
Sentry Upgrade Migration
Detect installed Sentry SDK versions, identify breaking API changes, apply automated codemods, and verify the upgrade succeeds with test events and traces.
Current State
!npm list 2>/dev/null | command grep @sentry || echo 'No npm Sentry packages found'
!pip show sentry-sdk 2>/dev/null | command grep -E '^(Name|Version)' || echo 'No Python sentry-sdk found'
!node --version 2>/dev/null || echo 'Node.js not available'
Overview
Sentry SDK upgrades require careful handling of breaking API changes. The v7 to v8 JavaScript migration is the most impactful, removing the Hub pattern, replacing Transaction/Span APIs with startSpan(), converting class-based integrations to functions, and requiring ESM-first initialization. Python SDK v1 to v2 similarly replaces configurescope() with getcurrent_scope(). This skill automates version detection, runs the official @sentry/migr8 codemod, applies manual fixes for patterns the codemod misses, and validates the upgrade with test events.
Prerequisites
- Current Sentry SDK version identified (run DCI above)
- Target version changelog reviewed
- Non-production environment for testing upgrades
- All
@sentry/*packages at the same major version before starting - Node.js >= 18.19.0 or >= 20.6.0 for SDK v8 (ESM support required)
Instructions
Step 1. Identify Current SDK Version and Scan for Deprecated APIs
# JavaScript: list all Sentry packages and their versions
npm ls 2>/dev/null | command grep "@sentry/"
# Python: check installed version
pip show sentry-sdk 2>/dev/null
# Verify all @sentry/* packages are the same major version (critical!)
# Mixed versions cause runtime crashes
npm ls @sentry/core @sentry/node @sentry/browser @sentry/utils 2>/dev/null
Scan the codebase for deprecated patterns that need migration:
# Detect v7 Hub usage (removed in v8)
command grep -rn "getCurrentHub\|configureScope\|hub\.capture" src/ --include="*.ts" --include="*.js"
# Detect v7 Transaction API (replaced in v8)
command grep -rn "startTransaction\|\.startChild\|\.finish()" src/ --include="*.ts" --include="*.js"
# Detect class-based integrations (replaced in v8)
command grep -rn "new Sentry\.\|new BrowserTracing\|new Integrations\." src/ --include="*.ts" --include="*.js"
# Detect @sentry/tracing imports (package removed in v8)
command grep -rn "from '@sentry/tracing'" src/ --include="*.ts" --include="*.js"
# Python: detect v1 scope API (replaced in v2)
command grep -rn "configure_scope\|push_scope" src/ --include="*.py"
Ready to use sentry-pack?
Related Plugins
ansible-playbook-creator
Create Ansible playbooks for configuration management
auto-scaling-configurator
Configure auto-scaling policies for applications and infrastructure
backup-strategy-implementor
Implement backup strategies for databases and applications
ci-cd-pipeline-builder
Build CI/CD pipelines for GitHub Actions, GitLab CI, Jenkins, and more
cloud-cost-optimizer
Optimize cloud costs and generate cost reports
compliance-checker
Check infrastructure compliance (SOC2, HIPAA, PCI-DSS)