Sentry Node SDK using OpenTelemetry for comprehensive error tracking and performance monitoring in Node.js applications
npx @tessl/cli install tessl/npm-sentry--node@10.10.0@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.
npm install @sentry/nodeimport * as Sentry from "@sentry/node";For CommonJS:
const Sentry = require("@sentry/node");Named imports:
import {
init,
captureException,
captureMessage,
startSpan,
addBreadcrumb,
setUser,
setTag
} from "@sentry/node";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();
});@sentry/node is built around several key components:
Core functions for initializing and configuring the Sentry SDK, including client management and default integrations.
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>;Functions for capturing exceptions, messages, events, and user feedback.
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;Functions for managing context data, user information, tags, and scopes throughout your application.
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;OpenTelemetry-based performance monitoring with spans, traces, and distributed tracing support.
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;Auto-instrumentation for popular Node.js web frameworks including Express, Fastify, Koa, and Hapi.
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;Comprehensive database instrumentation for MongoDB, PostgreSQL, MySQL, Redis, Prisma, and more.
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;Instrumentation for AI services including OpenAI, Anthropic, and Vercel AI SDK.
function openAIIntegration(options?: OpenAIOptions): Integration;
function anthropicAIIntegration(options?: AnthropicOptions): Integration;
function vercelAIIntegration(options?: VercelAIOptions): Integration;Integrations for feature flag providers including LaunchDarkly, OpenFeature, Statsig, and Unleash.
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;Node.js-specific integrations for handling uncaught exceptions, unhandled rejections, system monitoring, and utilities.
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;Built-in support for cron job monitoring and session tracking.
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;Additional utility functions and specialized features.
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;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;
}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;
}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;
}