Skip to main content
Technology & EngineeringError Tracking Services234 lines

Sentry

Integrating Sentry for real-time error tracking, performance monitoring, and session replay across web and mobile applications

Quick Summary28 lines
You are an expert in integrating Sentry for error tracking and crash reporting.

## Key Points

- Issue alerts: trigger on new errors, error frequency spikes, or specific error types.
- Metric alerts: trigger when transaction duration or failure rate exceeds a threshold.
- Custom dashboards: combine error counts, performance metrics, and release health widgets.
- Set `tracesSampleRate` below 1.0 in production to control costs; use 0.1-0.2 as a starting point and adjust based on traffic volume.
- Always configure `release` and upload source maps so stack traces are readable and you can correlate errors to deploys.
- Use `beforeSend` to scrub sensitive data (passwords, tokens, PII) before events leave the client.
- Group related errors with fingerprinting to avoid duplicate issues flooding your dashboard.
- Set up Slack/PagerDuty alert integrations for critical errors so the on-call team is notified immediately.
- Forgetting to call `Sentry.init()` before any other code runs, causing early errors to be missed.
- Setting `tracesSampleRate: 1.0` in high-traffic production, which generates excessive costs and quota usage.
- Not uploading source maps, resulting in minified stack traces that are impossible to debug.
- Catching errors in a try/catch without re-throwing or calling `captureException`, silently swallowing failures.

## Quick Example

```bash
npm install @sentry/node @sentry/profiling-node
```

```bash
npm install @sentry/react
```
skilldb get error-tracking-services-skills/SentryFull skill: 234 lines
Paste into your CLAUDE.md or agent config

Sentry — Error Tracking

You are an expert in integrating Sentry for error tracking and crash reporting.

Core Philosophy

Overview

Sentry is the most widely adopted open-source error tracking platform. It supports 100+ languages and frameworks, provides detailed stack traces with source map support, and offers performance monitoring, session replay, and release health tracking. Use Sentry when you need comprehensive error visibility across a polyglot stack with strong open-source community support.

Setup & Configuration

JavaScript / Node.js

npm install @sentry/node @sentry/profiling-node
const Sentry = require("@sentry/node");
const { nodeProfilingIntegration } = require("@sentry/profiling-node");

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  environment: process.env.NODE_ENV,
  release: "my-app@1.2.0",
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
  integrations: [nodeProfilingIntegration()],
});

React

npm install @sentry/react
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration(),
  ],
  tracesSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

// Wrap your app with the error boundary
const App = () => (
  <Sentry.ErrorBoundary fallback={<p>Something went wrong.</p>}>
    <MyApp />
  </Sentry.ErrorBoundary>
);

Express Middleware

const express = require("express");
const Sentry = require("@sentry/node");

const app = express();

Sentry.setupExpressErrorHandler(app);

// The error handler must be registered after all routes
app.use(function onError(err, req, res, next) {
  res.statusCode = 500;
  res.end(res.sentry + "\n");
});

Core Patterns

Error Capturing

// Capture an exception explicitly
try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}

// Capture a message
Sentry.captureMessage("Something unexpected happened", "warning");

Context and Breadcrumbs

// Set context for all future events
Sentry.setContext("order", {
  orderId: "abc-123",
  itemCount: 3,
});

// Add a breadcrumb manually
Sentry.addBreadcrumb({
  category: "auth",
  message: "User authenticated",
  level: "info",
});

User Identification

Sentry.setUser({
  id: "user-42",
  email: "user@example.com",
  username: "janedoe",
  ip_address: "{{auto}}",
});

// Clear user on logout
Sentry.setUser(null);

Release Tracking

# Upload source maps during CI/CD
npx @sentry/cli releases new my-app@1.2.0
npx @sentry/cli releases files my-app@1.2.0 upload-sourcemaps ./dist
npx @sentry/cli releases finalize my-app@1.2.0

Source Maps with Webpack

const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

module.exports = {
  devtool: "source-map",
  plugins: [
    sentryWebpackPlugin({
      org: "my-org",
      project: "my-project",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
};

Advanced Features

Performance Monitoring

// Manual transaction
const transaction = Sentry.startTransaction({
  op: "task",
  name: "My Custom Task",
});

Sentry.getCurrentScope().setSpan(transaction);

const span = transaction.startChild({
  op: "db.query",
  description: "SELECT * FROM users",
});

// ... perform operation
span.finish();
transaction.finish();

Session Replay

Session replay is configured during Sentry.init() via replayIntegration(). It captures DOM mutations, network requests, and console logs to reconstruct user sessions leading up to errors.

Custom Dashboards and Alerting

Use Sentry's web UI to create:

  • Issue alerts: trigger on new errors, error frequency spikes, or specific error types.
  • Metric alerts: trigger when transaction duration or failure rate exceeds a threshold.
  • Custom dashboards: combine error counts, performance metrics, and release health widgets.

Cron Monitoring

const checkInId = Sentry.captureCheckIn({
  monitorSlug: "daily-backup",
  status: "in_progress",
});

// ... run the job

Sentry.captureCheckIn({
  checkInId,
  monitorSlug: "daily-backup",
  status: "ok",
});

Best Practices

  • Set tracesSampleRate below 1.0 in production to control costs; use 0.1-0.2 as a starting point and adjust based on traffic volume.
  • Always configure release and upload source maps so stack traces are readable and you can correlate errors to deploys.
  • Use beforeSend to scrub sensitive data (passwords, tokens, PII) before events leave the client.
  • Group related errors with fingerprinting to avoid duplicate issues flooding your dashboard.
  • Set up Slack/PagerDuty alert integrations for critical errors so the on-call team is notified immediately.

Common Pitfalls

  • Forgetting to call Sentry.init() before any other code runs, causing early errors to be missed.
  • Setting tracesSampleRate: 1.0 in high-traffic production, which generates excessive costs and quota usage.
  • Not uploading source maps, resulting in minified stack traces that are impossible to debug.
  • Catching errors in a try/catch without re-throwing or calling captureException, silently swallowing failures.
  • Using the same DSN across environments, mixing development noise with production errors.

Anti-Patterns

Over-engineering for hypothetical scale. Building for millions of users when you have hundreds adds complexity without value. Solve today's problems first.

Ignoring the existing ecosystem. Reinventing functionality that mature libraries already provide well wastes time and introduces unnecessary risk.

Premature abstraction. Creating elaborate frameworks and utilities before you have enough concrete cases to know what the abstraction should look like produces the wrong abstraction.

Neglecting error handling at boundaries. Internal code can trust its inputs, but system boundaries (user input, APIs, file I/O) require defensive validation.

Skipping documentation for obvious code. What is obvious to you today will not be obvious to your colleague next month or to you next year.

Install this skill directly: skilldb add error-tracking-services-skills

Get CLI access →