sentry-known-pitfalls

2
0
Source

Execute common Sentry pitfalls and how to avoid them. Use when troubleshooting Sentry issues, reviewing configurations, or preventing common mistakes. Trigger with phrases like "sentry mistakes", "sentry pitfalls", "sentry common issues", "sentry anti-patterns".

Install

mkdir -p .claude/skills/sentry-known-pitfalls && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3090" && unzip -o skill.zip -d .claude/skills/sentry-known-pitfalls && rm skill.zip

Installs to .claude/skills/sentry-known-pitfalls

About this skill

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

Sentry queues events in memory. Serverless/CLI processes exit before the queue drains — events never reach Sentry.

// WRONG — Lambda exits, events lost
export const handler = async (event) => {
  try { return await processEvent(event); }
  catch (error) {
    Sentry.captureException(error);
    throw error;  // Queue never drains
  }
};

// RIGHT — flush before exit
export const handler = async (event) => {
  try { return await processEvent(event); }
  catch (error) {
    Sentry.captureException(error);
    await Sentry.flush(2000);
    throw error;
  }
};

// BEST — use @sentry/aws-serverless wrapper
import * as Sentry from '@sentry/aws-serverless';
export const handler = Sentry.wrapHandler(async (event) => {
  return await processEvent(event);
});

Step 5: Pitfall 4 — beforeSend Returning null for All Events

Missing return event causes JavaScript to return undefined, which Sentry treats as "drop." A single missing return kills all tracking.

// WRONG — non-error events silently vanish
Sentry.init({
  beforeSend(event) {
    if (event.level === 'error') return event;
    // Falls through — undefined — ALL non-errors dropped
  },
});

// RIGHT — always return event as the last line
Sentry.init({
  beforeSend(event, hint) {
    const error = hint?.originalException;
    if (error instanceof Error && error.message.match(/^NetworkError/)) {
      return null;  // Explicit drop
    }
    return event;  // Always the last line
  },
});

Step 6: Pitfall 5 — Release Version Mismatch (SDK vs Source Maps)

SDK release must exactly match sentry-cli releases new. A v prefix mismatch means source maps never apply.

// WRONG — "1.2.3" vs "v1.2.3"
Sentry.init({ release: process.env.npm_package_version });
// CLI: sentry-cli releases new "v1.2.3"

// RIGHT — single source of truth
const SENTRY_RELEASE = `myapp@${process.env.GIT_SHA || 'dev'}`;
Sentry.init({ release: SENTRY_RELEASE });
# CI — same variable feeds both SDK and CLI
export SENTRY_RELEASE="myapp@$(git rev-parse --short HEAD)"
npx sentry-cli releases new "$SENTRY_RELEASE"
npx sentry-cli sourcemaps upload --release="$SENTRY_RELEASE" \
  --url-prefix="~/static/js" ./dist/static/js/
npx sentry-cli releases finalize "$SENTRY_RELEASE"

Step 7: Pitfall 6 — Catching Errors Without Re-Throwing

Capturing to Sentry but not re-throwing means the function returns undefined. Downstream code breaks silently.

// WRONG — returns undefined
async function getUser(id: string) {
  try {
    return await fetch(`/api/users/${id}`).then(r => r.json());
  } catch (error) {
    Sentry.captureException(error);
    // Returns undefined — callers get TypeError
  }
}

// RIGHT — capture and re-throw
async function getUser(id: string) {
  try {
    return await fetch(`/api/users/${id}`).then(r => r.json());
  } catch (error) {
    Sentry.captureException(error);
    throw error;
  }
}

Step 8: Pitfall 7 — Missing environment Tag

Without environment, dev errors pollute prod dashboards. Alert rules fire on local noise. Issue counts are inflated.

// WRONG
Sentry.init({ dsn: process.env.SENTRY_DSN });

// RIGHT
Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.NODE_ENV || 'development',
});

// For Vercel/Railway preview environments:
function getSentryEnvironment(): string {
  if (process.env.VERCEL_ENV) return process.env.VERCEL_ENV;
  if (process.env.RAILWAY_ENVIRONMENT) return process.env.RAILWAY_ENVIRONMENT;
  return process.env.NODE_ENV || 'development';
}

Step 9: Pitfall 8 — Importing @sentry/node in Browser Bundle

@sentry/node depends on Node.js built-ins (http, fs). Browser import causes build failures, 100KB+ polyfill bloat, or runtime crashes.

// WRONG
import * as Sentry from '@sentry/node';  // In React/Vue/browser code

// RIGHT — platform-specific SDK
import * as Sentry from '@sentry/react';     // React
import * as Sentry from '@sentry/vue';       // Vue
import * as Sentry from '@sentry/nextjs';    // Next.js (client + server)
import * as Sentry from '@sentry/node';      // Server-only
import * as Sentry from '@sentry/aws-serverless';  // AWS Lambda

Step 10: Pitfall 9 — Ignoring 429 Too Many Requests

When quota is exceeded, Sentry returns 429 and the SDK silently drops events. You lose data during peak traffic — exactly when you need it most.

Prevention:

  1. Enable Spike Protection in Sentry Organization Settings
  2. Set per-key rate limits in Project Settings > Client Keys
  3. Monitor client reports: Project Settings > Client Keys > Stats
// Client-side circuit breaker for resilience
let sentryBackoff = 0;
Sentry.init({
  beforeSend(event) {
    if (Date.now() < sentryBackoff) return null;
    return event;
  },
});

Step 11: Pitfall 10 — No Alert Rules Configured

Sentry collects errors but does not notify anyone by default. Without alerts, critical bugs go unnoticed for hours.

Three-tier alert structure:

TierTriggerChannel
ImmediateNew fatal/error issue in prodPagerDuty
UrgentError rate > 100 events in 5 minSlack #alerts
AwarenessIssue unresolved > 7 daysEmail digest

Set up in Sentry UI: Alerts > Create Alert > Issue Alert (Tier 1) or Metric Alert (Tier 2). See monitoring pitfalls for API-based alert creation.

Step 12: Run the Full Audit Checklist

See audit script for a bash script that checks all 10 pitfalls in one pass.

Output

  • Audit report listing which of the 10 pitfalls were found
  • Code changes applied for each identified pitfall
  • Confirmation that beforeSend returns event on all paths
  • environment and release properly configured
  • Alert rules created or recommended (three tiers)

Error Handling

PitfallSymptomFix
Hardcoded DSNSpam events from attackersprocess.env.SENTRY_DSN or build-time injection
sampleRate: 1.010-50x cost overruntracesSampler with per-endpoint rates
No flush()Zero events from Lambda/CLIawait Sentry.flush(2000) before exit
beforeSend drops allEvents silently vanishAlways end with return event
Release mismatchMinified stack tracesSingle SENTRY_RELEASE env var
Swallowed catchCascading undefined errorsRe-throw after capture
No environmentDev noise in prod dashboardenvironment: process.env.NODE_ENV
Wrong SDK importBuild failure or bloatPlatform-specific SDK package
Ignoring 429sData loss at peak trafficSpike protection + circuit breaker
No alertsBugs accumulate unnoticedThree-tier alert rules

Examples

Example 1: Full-stack audit of existing Sentry setup

Request: "Audit our Sentry integration for common mistakes"

Result: Found hardcoded DSN in config.ts (Pitfall 1), 100% tracesSampleRate (Pitfall 2), no environment tag (Pitfall 7), and zero alert rules (Pitfall 10). Applied fixes for all four, added CI gate for DSN detection, created three-tier alert config. See examples for more scenarios.

Example 2: Debugging missing Lambda errors

Request: "Sentry shows no errors from our Lambda functions but we know they're failing"

Result: Identifi


Content truncated.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.