CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sentry--browser

Official Sentry SDK for browsers providing comprehensive error monitoring, performance tracking, user feedback collection, and session management capabilities for client-side JavaScript applications.

Pending
Overview
Eval results
Files

performance-monitoring.mddocs/

Performance Monitoring

Browser performance monitoring with distributed tracing capabilities. The Sentry Browser SDK provides comprehensive performance tracking for web applications including page loads, navigation, user interactions, and custom operations.

Capabilities

Span Management

Create and manage performance spans to track operations.

/**
 * Start a new span to track an operation
 * @param context - Span context configuration
 * @returns Span instance for the created span
 */
function startSpan<T>(context: SpanContext, callback: (span: Span) => T): T;

/**
 * Start an inactive span that must be manually activated
 * @param context - Span context configuration
 * @returns Span instance
 */
function startInactiveSpan(context: SpanContext): Span;

/**
 * Start a span with manual lifecycle control
 * @param context - Span context configuration
 * @returns Span instance that must be manually ended
 */
function startSpanManual(context: SpanContext): Span;

Usage Examples:

import { startSpan, startInactiveSpan } from "@sentry/browser";

// Automatic span management
const result = startSpan(
  { name: "data_processing", op: "function" },
  (span) => {
    span.setTag("data_type", "user_analytics");
    span.setData("record_count", 1000);
    
    // Your operation here
    const processedData = processAnalyticsData();
    
    span.setData("processed_count", processedData.length);
    return processedData;
  }
);

// Manual span management
const span = startInactiveSpan({
  name: "file_upload",
  op: "http.client",
});

span.setTag("file_type", "image");
span.setData("file_size", fileSize);

try {
  const response = await uploadFile(file);
  span.setData("response_size", response.size);
  span.setStatus("ok");
} catch (error) {
  span.setStatus("internal_error");
  throw error;
} finally {
  span.end();
}

Active Span Management

Work with the currently active span.

/**
 * Get the currently active span
 * @returns Active span instance or undefined if no span is active
 */
function getActiveSpan(): Span | undefined;

/**
 * Get the root span of the current trace
 * @returns Root span instance or undefined
 */
function getRootSpan(): Span | undefined;

/**
 * Execute callback with a specific span as the active span
 * @param span - Span to make active (or null to clear active span)
 * @param callback - Function to execute with the active span
 * @returns Result of the callback function
 */
function withActiveSpan<T>(span: Span | null, callback: () => T): T;

Usage Examples:

import { getActiveSpan, withActiveSpan, startSpan } from "@sentry/browser";

// Get current active span
const currentSpan = getActiveSpan();
if (currentSpan) {
  currentSpan.setTag("has_active_span", true);
}

// Execute code with specific active span
const parentSpan = startInactiveSpan({ name: "parent_operation" });

withActiveSpan(parentSpan, () => {
  // Any spans created here will be children of parentSpan
  startSpan({ name: "child_operation" }, () => {
    // This span is a child of parentSpan
    performChildOperation();
  });
});

Trace Management

Manage distributed traces across different contexts.

/**
 * Start a new trace, isolating it from any existing trace
 * @param callback - Function to execute in the new trace context
 * @returns Result of the callback function
 */
function startNewTrace<T>(callback: () => T): T;

/**
 * Continue a trace from incoming headers (e.g., HTTP requests)
 * @param headers - Headers containing trace information
 * @param callback - Function to execute in the continued trace context
 * @returns Result of the callback function
 */
function continueTrace<T>(
  headers: { [key: string]: string | string[] | undefined },
  callback: () => T
): T;

/**
 * Get trace data for the current span/transaction
 * @returns Object containing trace and baggage headers
 */
function getTraceData(): { "sentry-trace"?: string; baggage?: string };

/**
 * Suppress tracing for the given callback
 * @param callback - Function to execute without tracing
 * @returns Result of the callback function
 */
function suppressTracing<T>(callback: () => T): T;

Usage Examples:

import { startNewTrace, continueTrace, getTraceData } from "@sentry/browser";

// Start completely new trace
startNewTrace(() => {
  // This creates a new trace, disconnected from any parent
  startSpan({ name: "independent_operation" }, () => {
    performIndependentWork();
  });
});

// Continue trace from incoming request
function handleIncomingRequest(headers: Record<string, string>) {
  continueTrace(headers, () => {
    startSpan({ name: "request_handler" }, () => {
      processRequest();
    });
  });
}

// Get trace data for outgoing requests
const traceData = getTraceData();
fetch("/api/data", {
  headers: {
    ...traceData, // Includes sentry-trace and baggage headers
  },
});

Span Utilities

Utility functions for working with spans.

/**
 * Convert span to JSON representation
 * @param span - Span to convert
 * @returns JSON representation of the span
 */
function spanToJSON(span: Span): SpanJSON;

/**
 * Create sentry-trace header from span
 * @param span - Span to create header from
 * @returns sentry-trace header value
 */
function spanToTraceHeader(span: Span): string;

/**
 * Create baggage header from span
 * @param span - Span to create header from
 * @returns baggage header value
 */
function spanToBaggageHeader(span: Span): string | undefined;

/**
 * Update the name of a span
 * @param span - Span to update
 * @param name - New name for the span
 */
function updateSpanName(span: Span, name: string): void;

/**
 * Get all descendant spans of a given span
 * @param span - Parent span
 * @returns Array of descendant spans
 */
function getSpanDescendants(span: Span): Span[];

Performance Measurements

Set custom performance measurements.

/**
 * Set a custom measurement on the current transaction
 * @param name - Measurement name
 * @param value - Measurement value
 * @param unit - Measurement unit (optional)
 */
function setMeasurement(name: string, value: number, unit?: MeasurementUnit): void;

Usage Example:

import { setMeasurement } from "@sentry/browser";

// Custom performance metrics
setMeasurement("custom.database.query.duration", 150, "millisecond");
setMeasurement("custom.cache.hit.ratio", 0.85, "ratio");
setMeasurement("custom.memory.usage", 1024 * 1024, "byte");

HTTP Status Handling

Utilities for handling HTTP status codes in spans.

/**
 * Get span status from HTTP status code
 * @param httpStatus - HTTP status code
 * @returns Appropriate span status
 */
function getSpanStatusFromHttpCode(httpStatus: number): SpanStatus;

/**
 * Set HTTP status on a span
 * @param span - Span to update
 * @param httpStatus - HTTP status code
 */
function setHttpStatus(span: Span, httpStatus: number): void;

Browser-Specific Tracing

Browser-specific performance monitoring integrations.

/**
 * Create browser tracing integration for automatic performance monitoring
 * @param options - Configuration options for browser tracing
 * @returns Browser tracing integration
 */
function browserTracingIntegration(options?: BrowserTracingOptions): Integration;

/**
 * Start a browser navigation span manually
 * @param context - Navigation span context
 * @returns Navigation span
 */
function startBrowserTracingNavigationSpan(context: NavigationSpanContext): Span;

/**
 * Start a browser page load span manually
 * @param context - Page load span context
 * @returns Page load span
 */
function startBrowserTracingPageLoadSpan(context: PageLoadSpanContext): Span;

Usage Example:

import { browserTracingIntegration } from "@sentry/browser";

// Enable automatic browser tracing
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    browserTracingIntegration({
      enableLongTask: true,
      enableInp: true,
      enableUserTimingApi: true,
      tracePropagationTargets: ["localhost", "api.example.com"],
    }),
  ],
  tracesSampleRate: 0.1,
});

Request Instrumentation

Instrument outgoing HTTP requests for performance monitoring.

/**
 * Default options for request instrumentation
 */
const defaultRequestInstrumentationOptions: RequestInstrumentationOptions;

/**
 * Instrument outgoing requests for performance tracking
 * @param options - Configuration options for request instrumentation
 */
function instrumentOutgoingRequests(options?: RequestInstrumentationOptions): void;

Types

Span Interface

interface Span {
  /** Set a tag on this span */
  setTag(key: string, value: string): void;
  
  /** Set data on this span */
  setData(key: string, value: any): void;
  
  /** Set the status of this span */
  setStatus(status: SpanStatus): void;
  
  /** Set HTTP status on this span */
  setHttpStatus(code: number): void;
  
  /** Update the name of this span */
  updateName(name: string): void;
  
  /** End this span */
  end(timestamp?: number): void;
  
  /** Get the span context */
  spanContext(): SpanContext;
  
  /** Check if span is recording */
  isRecording(): boolean;
  
  /** Add an event to this span */
  addEvent(name: string, attributes?: Record<string, any>, timestamp?: number): void;
}

Span Context

interface SpanContext {
  /** Name of the operation being tracked */
  name: string;
  
  /** Operation type (e.g., "http.client", "db.query") */
  op?: string;
  
  /** Description of the operation */
  description?: string;
  
  /** Start timestamp */
  startTimestamp?: number;
  
  /** End timestamp */
  endTimestamp?: number;
  
  /** Parent span ID */
  parentSpanId?: string;
  
  /** Trace ID */
  traceId?: string;
  
  /** Span ID */
  spanId?: string;
  
  /** Tags for this span */
  tags?: Record<string, string>;
  
  /** Data for this span */
  data?: Record<string, any>;
  
  /** Origin of this span */
  origin?: string;
  
  /** Instrumentation library info */
  instrumenter?: string;
}

Span Status

type SpanStatus = 
  | "ok"
  | "cancelled" 
  | "unknown"
  | "invalid_argument"
  | "deadline_exceeded"
  | "not_found"
  | "already_exists"
  | "permission_denied"
  | "resource_exhausted"
  | "failed_precondition"
  | "aborted"
  | "out_of_range"
  | "unimplemented"
  | "internal_error"
  | "unavailable"
  | "data_loss"
  | "unauthenticated";

Browser Tracing Options

interface BrowserTracingOptions {
  /** Enable Long Task API instrumentation */
  enableLongTask?: boolean;
  
  /** Enable Interaction to Next Paint (INP) tracking */
  enableInp?: boolean;
  
  /** Enable User Timing API marks and measures */
  enableUserTimingApi?: boolean;
  
  /** URLs to propagate trace headers to */
  tracePropagationTargets?: (string | RegExp)[];
  
  /** Sample rate for navigation transactions */
  routingInstrumentation?: (
    customStartTransaction: (context: TransactionContext) => Transaction,
    startTransactionOnPageLoad?: boolean,
    startTransactionOnLocationChange?: boolean
  ) => void;
  
  /** Maximum transaction duration in seconds */
  maxTransactionDuration?: number;
  
  /** Idle timeout for transactions in seconds */
  idleTimeout?: number;
  
  /** Enable heart beat for long running transactions */
  heartbeatInterval?: number;
  
  /** Mark transactions as failed if they exceed this duration */
  finalTimeout?: number;
  
  /** Enable automatic span creation for fetch requests */
  traceFetch?: boolean;
  
  /** Enable automatic span creation for XHR requests */
  traceXHR?: boolean;
  
  /** Before navigation callback */
  beforeNavigate?: (context: TransactionContext) => TransactionContext | undefined;
}

Request Instrumentation Options

interface RequestInstrumentationOptions {
  /** URLs to track for performance */
  tracePropagationTargets?: (string | RegExp)[];
  
  /** Enable tracing for fetch requests */
  traceFetch?: boolean;
  
  /** Enable tracing for XHR requests */
  traceXHR?: boolean;
  
  /** Function to determine if request should be traced */
  shouldCreateSpanForRequest?: (url: string) => boolean;
  
  /** Callback before creating span for request */
  beforeSpan?: (span: Span, request: { method?: string; url: string }) => void;
}

Measurement Unit

type MeasurementUnit = 
  | "nanosecond"
  | "microsecond" 
  | "millisecond"
  | "second"
  | "minute"
  | "hour"
  | "day"
  | "week"
  | "byte"
  | "kilobyte"
  | "kibibyte"
  | "megabyte"
  | "mebibyte"
  | "gigabyte"
  | "gibibyte"
  | "terabyte"
  | "tebibyte"
  | "petabyte"
  | "pebibyte"
  | "bit"
  | "kilobit"
  | "megabit"
  | "gigabit"
  | "terabit"
  | "petabit"
  | "percent"
  | "ratio"
  | "none";

Automatic Instrumentation

The browser tracing integration automatically creates spans for:

  • Page loads: Complete page load performance
  • Navigation: Client-side route changes
  • HTTP requests: Fetch and XHR requests
  • User interactions: Click events and form submissions
  • Long tasks: Tasks that block the main thread
  • Layout shifts: Cumulative Layout Shift (CLS) tracking
  • Paint timings: First Paint, First Contentful Paint
  • Web Vitals: LCP, FID, CLS metrics

Custom Instrumentation Patterns

Database Operations

import { startSpan } from "@sentry/browser";

async function queryDatabase(query: string) {
  return startSpan(
    {
      name: "db.query",
      op: "db",
      data: {
        query: query.substring(0, 100), // Truncate long queries
        db_type: "postgresql",
      },
    },
    async (span) => {
      try {
        const result = await executeQuery(query);
        span.setData("row_count", result.rows.length);
        span.setStatus("ok");
        return result;
      } catch (error) {
        span.setStatus("internal_error");
        throw error;
      }
    }
  );
}

API Calls

import { startSpan, getTraceData } from "@sentry/browser";

async function callExternalAPI(endpoint: string, data: any) {
  return startSpan(
    {
      name: `API ${endpoint}`,
      op: "http.client",
      data: { endpoint, method: "POST" },
    },
    async (span) => {
      const traceHeaders = getTraceData();
      
      try {
        const response = await fetch(endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...traceHeaders,
          },
          body: JSON.stringify(data),
        });
        
        span.setHttpStatus(response.status);
        span.setData("response_size", response.headers.get("content-length"));
        
        return response.json();
      } catch (error) {
        span.setStatus("internal_error");
        throw error;
      }
    }
  );
}

Background Tasks

import { startSpan } from "@sentry/browser";

function processInBackground(items: any[]) {
  startSpan(
    {
      name: "background_processing",
      op: "task",
      data: { item_count: items.length },
    },
    (span) => {
      let processed = 0;
      
      items.forEach((item, index) => {
        try {
          processItem(item);
          processed++;
        } catch (error) {
          span.setTag("has_errors", "true");
          // Continue processing other items
        }
        
        // Update progress
        if (index % 100 === 0) {
          span.setData("progress", `${index}/${items.length}`);
        }
      });
      
      span.setData("processed_count", processed);
      span.setData("failed_count", items.length - processed);
    }
  );
}

Install with Tessl CLI

npx tessl i tessl/npm-sentry--browser

docs

context-management.md

error-capture.md

index.md

integrations.md

performance-monitoring.md

sdk-initialization.md

session-management.md

session-replay.md

transport.md

user-feedback.md

tile.json