# @sentry/node

@sentry/node is a comprehensive error tracking and performance monitoring SDK for Node.js applications. It provides real-time error tracking with detailed stack traces, automatic performance monitoring using OpenTelemetry, and extensive auto-instrumentation for popular Node.js frameworks and libraries.

## Package Information

- **Package Name**: @sentry/node
- **Package Type**: npm
- **Language**: TypeScript/JavaScript
- **Installation**: `npm install @sentry/node`

## Core Imports

```typescript
import * as Sentry from "@sentry/node";
```

For CommonJS:

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

Named imports:

```typescript
import { 
  init, 
  captureException, 
  captureMessage, 
  startSpan,
  addBreadcrumb,
  setUser,
  setTag
} from "@sentry/node";
```

## Basic Usage

```typescript
import * as Sentry from "@sentry/node";

// Initialize Sentry
Sentry.init({
  dsn: "YOUR_DSN_HERE",
  tracesSampleRate: 1.0,
});

// Capture an exception
try {
  throw new Error("Something went wrong!");
} catch (error) {
  Sentry.captureException(error);
}

// Capture a message
Sentry.captureMessage("Hello World", "info");

// Add breadcrumbs
Sentry.addBreadcrumb({
  message: "User clicked button",
  category: "ui",
  level: "info",
});

// Set user context
Sentry.setUser({
  id: "123",
  email: "user@example.com",
});

// Start a span for performance monitoring
Sentry.startSpan({ name: "my-operation" }, (span) => {
  // Your code here
  return performOperation();
});
```

## Architecture

@sentry/node is built around several key components:

- **Core SDK**: Initialization, configuration, and client management
- **Error Capture**: Exception and message capture with context
- **Performance Monitoring**: OpenTelemetry-based tracing and spans
- **Context Management**: Scopes, user data, tags, and breadcrumbs
- **Auto-Instrumentation**: Automatic instrumentation for frameworks, databases, and services
- **Integration System**: Pluggable integrations for extending functionality

## Capabilities

### SDK Initialization and Configuration

Core functions for initializing and configuring the Sentry SDK, including client management and default integrations.

```typescript { .api }
function init(options?: NodeOptions): NodeClient | undefined;
function initWithoutDefaultIntegrations(options?: NodeOptions): NodeClient | undefined;
function getDefaultIntegrations(options: Options): Integration[];
function isInitialized(): boolean;
function close(timeout?: number): PromiseLike<boolean>;
```

[SDK Initialization](./initialization.md)

### Error and Event Capture

Functions for capturing exceptions, messages, events, and user feedback.

```typescript { .api }
function captureException(exception: any, captureContext?: CaptureContext): string;
function captureMessage(message: string, level?: SeverityLevel, captureContext?: CaptureContext): string;
function captureEvent(event: Event, hint?: EventHint): string;
function captureFeedback(feedback: UserFeedback): string;
function lastEventId(): string | undefined;
```

[Error Capture](./error-capture.md)

### Context and Scope Management

Functions for managing context data, user information, tags, and scopes throughout your application.

```typescript { .api }
function setUser(user: User): void;
function setTag(key: string, value: Primitive): void;
function setContext(key: string, context: Context): void;
function setExtra(key: string, extra: Extra): void;
function getCurrentScope(): Scope;
function withScope<T>(callback: (scope: Scope) => T): T;
```

[Context Management](./context-management.md)

### Performance Monitoring and Tracing

OpenTelemetry-based performance monitoring with spans, traces, and distributed tracing support.

```typescript { .api }
function startSpan<T>(context: StartSpanOptions, callback: (span: Span) => T): T;
function startSpanManual<T>(context: StartSpanOptions, callback: (span: Span, finish: () => void) => T): T;
function startInactiveSpan(context: StartSpanOptions): Span;
function getActiveSpan(): Span | undefined;
function startNewTrace<T>(callback: () => T): T;
function continueTrace(tracingData: TracingData, callback: () => T): T;
function getTraceData(): TraceData;
```

[Performance Monitoring](./performance-monitoring.md)

### Framework Integrations

Auto-instrumentation for popular Node.js web frameworks including Express, Fastify, Koa, and Hapi.

```typescript { .api }
function expressIntegration(options?: ExpressOptions): Integration;
function fastifyIntegration(options?: FastifyOptions): Integration;
function koaIntegration(options?: KoaOptions): Integration;
function hapiIntegration(options?: HapiOptions): Integration;
function setupExpressErrorHandler(app: Express, options?: ExpressErrorHandlerOptions): void;
```

[Framework Integrations](./framework-integrations.md)

### Database Integrations

Comprehensive database instrumentation for MongoDB, PostgreSQL, MySQL, Redis, Prisma, and more.

```typescript { .api }
function mongoIntegration(options?: MongoOptions): Integration;
function postgresIntegration(options?: PostgresOptions): Integration;
function mysqlIntegration(options?: MysqlOptions): Integration;
function mysql2Integration(options?: Mysql2Options): Integration;
function redisIntegration(options?: RedisOptions): Integration;
function ioredisIntegration(options?: IoredisOptions): Integration;
function prismaIntegration(options?: PrismaOptions): Integration;
function knexIntegration(options?: KnexOptions): Integration;
function tediousIntegration(options?: TediousOptions): Integration;
function genericPoolIntegration(options?: GenericPoolOptions): Integration;
function dataloaderIntegration(options?: DataloaderOptions): Integration;
```

[Database Integrations](./database-integrations.md)

### AI Service Integrations

Instrumentation for AI services including OpenAI, Anthropic, and Vercel AI SDK.

```typescript { .api }
function openAIIntegration(options?: OpenAIOptions): Integration;
function anthropicAIIntegration(options?: AnthropicOptions): Integration;
function vercelAIIntegration(options?: VercelAIOptions): Integration;
```

[AI Service Integrations](./ai-service-integrations.md)

### Feature Flag Integrations

Integrations for feature flag providers including LaunchDarkly, OpenFeature, Statsig, and Unleash.

```typescript { .api }
function launchDarklyIntegration(options?: LaunchDarklyOptions): Integration;
function openFeatureIntegration(options?: OpenFeatureOptions): Integration;
function statsigIntegration(options?: StatsigOptions): Integration;
function unleashIntegration(options?: UnleashOptions): Integration;
function featureFlagsIntegration(options?: FeatureFlagsOptions): Integration;
function buildLaunchDarklyFlagUsedHandler(client: Client): FlagUsedHandler;
```

[Feature Flag Integrations](./feature-flags-integrations.md)

### Node.js System Integrations

Node.js-specific integrations for handling uncaught exceptions, unhandled rejections, system monitoring, and utilities.

```typescript { .api }
function onUncaughtExceptionIntegration(options?: UncaughtExceptionOptions): Integration;
function onUnhandledRejectionIntegration(options?: UnhandledRejectionOptions): Integration;
function nodeContextIntegration(): Integration;
function localVariablesIntegration(options?: LocalVariablesOptions): Integration;
function contextLinesIntegration(options?: ContextLinesOptions): Integration;
function modulesIntegration(): Integration;
function spotlightIntegration(options?: SpotlightOptions): Integration;
function childProcessIntegration(options?: ChildProcessOptions): Integration;
function systemErrorIntegration(): Integration;
function supabaseIntegration(options?: SupabaseOptions): Integration;
function zodErrorsIntegration(options?: ZodErrorsOptions): Integration;
```

[Node.js System Integrations](./nodejs-integrations.md)

### Cron and Session Monitoring

Built-in support for cron job monitoring and session tracking.

```typescript { .api }
function withMonitor<T>(
  monitorSlug: string, 
  callback: () => T, 
  upsertMonitorConfig?: MonitorConfig
): T;
function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string;
function startSession(context?: SessionContext): Session;
function captureSession(endSession?: boolean): void;
function endSession(): void;
function cron(config: CronConfig): CronJob;
```

[Monitoring and Sessions](./monitoring-sessions.md)

### Additional Utilities

Additional utility functions and specialized features.

```typescript { .api }
function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;
function isInitialized(): boolean;
function isEnabled(): boolean;
function flush(timeout?: number): PromiseLike<boolean>;
function close(timeout?: number): PromiseLike<boolean>;
function lastEventId(): string | undefined;
function getClient(): NodeClient | undefined;
function getCurrentScope(): Scope;
function getIsolationScope(): Scope;
function withScope<T>(callback: (scope: Scope) => T): T;
function withIsolationScope<T>(callback: (scope: Scope) => T): T;
function addIntegration(integration: Integration): void;
function createSentryWinstonTransport(options?: WinstonTransportOptions): Transport;
function wrapMcpServerWithSentry<T>(server: T): T;
```

## Types

### Core Options and Configuration

```typescript { .api }
interface NodeOptions {
  dsn?: string;
  debug?: boolean;
  tracesSampleRate?: number;
  environment?: string;
  release?: string;
  serverName?: string;
  integrations?: Integration[];
  beforeSend?: BeforeSendHook;
  beforeSendTransaction?: BeforeSendHook;
  maxBreadcrumbs?: number;
  attachStacktrace?: boolean;
  sampleRate?: number;
  maxValueLength?: number;
  normalizeDepth?: number;
  normalizeMaxBreadth?: number;
  httpProxy?: string;
  httpsProxy?: string;
  skipOpenTelemetrySetup?: boolean;
  includeLocalVariables?: boolean;
  registerEsmLoaderHooks?: boolean;
  autoSessionTracking?: boolean;
  profilesSampleRate?: number;
}

interface NodeClient {
  captureException(exception: any, hint?: EventHint, scope?: Scope): string;
  captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string;
  captureEvent(event: Event, hint?: EventHint, scope?: Scope): string;
  close(timeout?: number): PromiseLike<boolean>;
  flush(timeout?: number): PromiseLike<boolean>;
  getDsn(): DsnLike | undefined;
  getOptions(): Options;
  getIntegrationByName<T extends Integration>(name: string): T | undefined;
}
```

### Context and User Types

```typescript { .api }
interface User {
  id?: string;
  username?: string;
  email?: string;
  ip_address?: string;
  segment?: string;
  [key: string]: any;
}

interface Breadcrumb {
  message?: string;
  category?: string;
  level?: SeverityLevel;
  timestamp?: number;
  type?: string;
  data?: { [key: string]: any };
}

type SeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug";

interface Scope {
  addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): Scope;
  setUser(user: User | null): Scope;
  setTag(key: string, value: Primitive): Scope;
  setContext(key: string, context: Context | null): Scope;
  setLevel(level: SeverityLevel): Scope;
  setFingerprint(fingerprint: string[]): Scope;
}
```

### Span and Tracing Types  

```typescript { .api }
interface StartSpanOptions {
  name: string;
  attributes?: Record<string, any>;
  startTime?: number;
  parentSpan?: Span;
  scope?: Scope;
  onlyIfParent?: boolean;
  forceTransaction?: boolean;
  op?: string;
  origin?: string;
}

interface Span {
  spanContext(): SpanContext;
  setAttribute(key: string, value: any): Span;
  setAttributes(attributes: Record<string, any>): Span;
  setStatus(status: SpanStatus): Span;
  updateName(name: string): Span;
  end(endTime?: number): void;
  isRecording(): boolean;
}

interface TraceData {
  "sentry-trace": string;
  baggage?: string;
}

interface MonitorConfig {
  schedule?: {
    type: 'crontab' | 'interval';
    value: string;
  };
  checkinMargin?: number;
  maxRuntime?: number;
  timezone?: string;
}

interface CheckIn {
  monitorSlug: string;
  status: 'in_progress' | 'ok' | 'error';
  duration?: number;
  checkInId?: string;
}

interface CronConfig {
  name: string;
  schedule: string;
  onStart?: () => void;
  onComplete?: () => void;
  onError?: (error: Error) => void;
}

interface Integration {
  name: string;
  setupOnce?: (addGlobalEventProcessor: any, getCurrentHub: any) => void;
  setup?: (options: any) => void;
}

interface BreadcrumbHint {
  message?: string;
  category?: string;
  level?: SeverityLevel;
  [key: string]: any;
}
```