0
# @sentry/node
1
2
@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.
3
4
## Package Information
5
6
- **Package Name**: @sentry/node
7
- **Package Type**: npm
8
- **Language**: TypeScript/JavaScript
9
- **Installation**: `npm install @sentry/node`
10
11
## Core Imports
12
13
```typescript
14
import * as Sentry from "@sentry/node";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const Sentry = require("@sentry/node");
21
```
22
23
Named imports:
24
25
```typescript
26
import {
27
init,
28
captureException,
29
captureMessage,
30
startSpan,
31
addBreadcrumb,
32
setUser,
33
setTag
34
} from "@sentry/node";
35
```
36
37
## Basic Usage
38
39
```typescript
40
import * as Sentry from "@sentry/node";
41
42
// Initialize Sentry
43
Sentry.init({
44
dsn: "YOUR_DSN_HERE",
45
tracesSampleRate: 1.0,
46
});
47
48
// Capture an exception
49
try {
50
throw new Error("Something went wrong!");
51
} catch (error) {
52
Sentry.captureException(error);
53
}
54
55
// Capture a message
56
Sentry.captureMessage("Hello World", "info");
57
58
// Add breadcrumbs
59
Sentry.addBreadcrumb({
60
message: "User clicked button",
61
category: "ui",
62
level: "info",
63
});
64
65
// Set user context
66
Sentry.setUser({
67
id: "123",
68
email: "user@example.com",
69
});
70
71
// Start a span for performance monitoring
72
Sentry.startSpan({ name: "my-operation" }, (span) => {
73
// Your code here
74
return performOperation();
75
});
76
```
77
78
## Architecture
79
80
@sentry/node is built around several key components:
81
82
- **Core SDK**: Initialization, configuration, and client management
83
- **Error Capture**: Exception and message capture with context
84
- **Performance Monitoring**: OpenTelemetry-based tracing and spans
85
- **Context Management**: Scopes, user data, tags, and breadcrumbs
86
- **Auto-Instrumentation**: Automatic instrumentation for frameworks, databases, and services
87
- **Integration System**: Pluggable integrations for extending functionality
88
89
## Capabilities
90
91
### SDK Initialization and Configuration
92
93
Core functions for initializing and configuring the Sentry SDK, including client management and default integrations.
94
95
```typescript { .api }
96
function init(options?: NodeOptions): NodeClient | undefined;
97
function initWithoutDefaultIntegrations(options?: NodeOptions): NodeClient | undefined;
98
function getDefaultIntegrations(options: Options): Integration[];
99
function isInitialized(): boolean;
100
function close(timeout?: number): PromiseLike<boolean>;
101
```
102
103
[SDK Initialization](./initialization.md)
104
105
### Error and Event Capture
106
107
Functions for capturing exceptions, messages, events, and user feedback.
108
109
```typescript { .api }
110
function captureException(exception: any, captureContext?: CaptureContext): string;
111
function captureMessage(message: string, level?: SeverityLevel, captureContext?: CaptureContext): string;
112
function captureEvent(event: Event, hint?: EventHint): string;
113
function captureFeedback(feedback: UserFeedback): string;
114
function lastEventId(): string | undefined;
115
```
116
117
[Error Capture](./error-capture.md)
118
119
### Context and Scope Management
120
121
Functions for managing context data, user information, tags, and scopes throughout your application.
122
123
```typescript { .api }
124
function setUser(user: User): void;
125
function setTag(key: string, value: Primitive): void;
126
function setContext(key: string, context: Context): void;
127
function setExtra(key: string, extra: Extra): void;
128
function getCurrentScope(): Scope;
129
function withScope<T>(callback: (scope: Scope) => T): T;
130
```
131
132
[Context Management](./context-management.md)
133
134
### Performance Monitoring and Tracing
135
136
OpenTelemetry-based performance monitoring with spans, traces, and distributed tracing support.
137
138
```typescript { .api }
139
function startSpan<T>(context: StartSpanOptions, callback: (span: Span) => T): T;
140
function startSpanManual<T>(context: StartSpanOptions, callback: (span: Span, finish: () => void) => T): T;
141
function startInactiveSpan(context: StartSpanOptions): Span;
142
function getActiveSpan(): Span | undefined;
143
function startNewTrace<T>(callback: () => T): T;
144
function continueTrace(tracingData: TracingData, callback: () => T): T;
145
function getTraceData(): TraceData;
146
```
147
148
[Performance Monitoring](./performance-monitoring.md)
149
150
### Framework Integrations
151
152
Auto-instrumentation for popular Node.js web frameworks including Express, Fastify, Koa, and Hapi.
153
154
```typescript { .api }
155
function expressIntegration(options?: ExpressOptions): Integration;
156
function fastifyIntegration(options?: FastifyOptions): Integration;
157
function koaIntegration(options?: KoaOptions): Integration;
158
function hapiIntegration(options?: HapiOptions): Integration;
159
function setupExpressErrorHandler(app: Express, options?: ExpressErrorHandlerOptions): void;
160
```
161
162
[Framework Integrations](./framework-integrations.md)
163
164
### Database Integrations
165
166
Comprehensive database instrumentation for MongoDB, PostgreSQL, MySQL, Redis, Prisma, and more.
167
168
```typescript { .api }
169
function mongoIntegration(options?: MongoOptions): Integration;
170
function postgresIntegration(options?: PostgresOptions): Integration;
171
function mysqlIntegration(options?: MysqlOptions): Integration;
172
function mysql2Integration(options?: Mysql2Options): Integration;
173
function redisIntegration(options?: RedisOptions): Integration;
174
function ioredisIntegration(options?: IoredisOptions): Integration;
175
function prismaIntegration(options?: PrismaOptions): Integration;
176
function knexIntegration(options?: KnexOptions): Integration;
177
function tediousIntegration(options?: TediousOptions): Integration;
178
function genericPoolIntegration(options?: GenericPoolOptions): Integration;
179
function dataloaderIntegration(options?: DataloaderOptions): Integration;
180
```
181
182
[Database Integrations](./database-integrations.md)
183
184
### AI Service Integrations
185
186
Instrumentation for AI services including OpenAI, Anthropic, and Vercel AI SDK.
187
188
```typescript { .api }
189
function openAIIntegration(options?: OpenAIOptions): Integration;
190
function anthropicAIIntegration(options?: AnthropicOptions): Integration;
191
function vercelAIIntegration(options?: VercelAIOptions): Integration;
192
```
193
194
[AI Service Integrations](./ai-service-integrations.md)
195
196
### Feature Flag Integrations
197
198
Integrations for feature flag providers including LaunchDarkly, OpenFeature, Statsig, and Unleash.
199
200
```typescript { .api }
201
function launchDarklyIntegration(options?: LaunchDarklyOptions): Integration;
202
function openFeatureIntegration(options?: OpenFeatureOptions): Integration;
203
function statsigIntegration(options?: StatsigOptions): Integration;
204
function unleashIntegration(options?: UnleashOptions): Integration;
205
function featureFlagsIntegration(options?: FeatureFlagsOptions): Integration;
206
function buildLaunchDarklyFlagUsedHandler(client: Client): FlagUsedHandler;
207
```
208
209
[Feature Flag Integrations](./feature-flags-integrations.md)
210
211
### Node.js System Integrations
212
213
Node.js-specific integrations for handling uncaught exceptions, unhandled rejections, system monitoring, and utilities.
214
215
```typescript { .api }
216
function onUncaughtExceptionIntegration(options?: UncaughtExceptionOptions): Integration;
217
function onUnhandledRejectionIntegration(options?: UnhandledRejectionOptions): Integration;
218
function nodeContextIntegration(): Integration;
219
function localVariablesIntegration(options?: LocalVariablesOptions): Integration;
220
function contextLinesIntegration(options?: ContextLinesOptions): Integration;
221
function modulesIntegration(): Integration;
222
function spotlightIntegration(options?: SpotlightOptions): Integration;
223
function childProcessIntegration(options?: ChildProcessOptions): Integration;
224
function systemErrorIntegration(): Integration;
225
function supabaseIntegration(options?: SupabaseOptions): Integration;
226
function zodErrorsIntegration(options?: ZodErrorsOptions): Integration;
227
```
228
229
[Node.js System Integrations](./nodejs-integrations.md)
230
231
### Cron and Session Monitoring
232
233
Built-in support for cron job monitoring and session tracking.
234
235
```typescript { .api }
236
function withMonitor<T>(
237
monitorSlug: string,
238
callback: () => T,
239
upsertMonitorConfig?: MonitorConfig
240
): T;
241
function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string;
242
function startSession(context?: SessionContext): Session;
243
function captureSession(endSession?: boolean): void;
244
function endSession(): void;
245
function cron(config: CronConfig): CronJob;
246
```
247
248
[Monitoring and Sessions](./monitoring-sessions.md)
249
250
### Additional Utilities
251
252
Additional utility functions and specialized features.
253
254
```typescript { .api }
255
function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;
256
function isInitialized(): boolean;
257
function isEnabled(): boolean;
258
function flush(timeout?: number): PromiseLike<boolean>;
259
function close(timeout?: number): PromiseLike<boolean>;
260
function lastEventId(): string | undefined;
261
function getClient(): NodeClient | undefined;
262
function getCurrentScope(): Scope;
263
function getIsolationScope(): Scope;
264
function withScope<T>(callback: (scope: Scope) => T): T;
265
function withIsolationScope<T>(callback: (scope: Scope) => T): T;
266
function addIntegration(integration: Integration): void;
267
function createSentryWinstonTransport(options?: WinstonTransportOptions): Transport;
268
function wrapMcpServerWithSentry<T>(server: T): T;
269
```
270
271
## Types
272
273
### Core Options and Configuration
274
275
```typescript { .api }
276
interface NodeOptions {
277
dsn?: string;
278
debug?: boolean;
279
tracesSampleRate?: number;
280
environment?: string;
281
release?: string;
282
serverName?: string;
283
integrations?: Integration[];
284
beforeSend?: BeforeSendHook;
285
beforeSendTransaction?: BeforeSendHook;
286
maxBreadcrumbs?: number;
287
attachStacktrace?: boolean;
288
sampleRate?: number;
289
maxValueLength?: number;
290
normalizeDepth?: number;
291
normalizeMaxBreadth?: number;
292
httpProxy?: string;
293
httpsProxy?: string;
294
skipOpenTelemetrySetup?: boolean;
295
includeLocalVariables?: boolean;
296
registerEsmLoaderHooks?: boolean;
297
autoSessionTracking?: boolean;
298
profilesSampleRate?: number;
299
}
300
301
interface NodeClient {
302
captureException(exception: any, hint?: EventHint, scope?: Scope): string;
303
captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string;
304
captureEvent(event: Event, hint?: EventHint, scope?: Scope): string;
305
close(timeout?: number): PromiseLike<boolean>;
306
flush(timeout?: number): PromiseLike<boolean>;
307
getDsn(): DsnLike | undefined;
308
getOptions(): Options;
309
getIntegrationByName<T extends Integration>(name: string): T | undefined;
310
}
311
```
312
313
### Context and User Types
314
315
```typescript { .api }
316
interface User {
317
id?: string;
318
username?: string;
319
email?: string;
320
ip_address?: string;
321
segment?: string;
322
[key: string]: any;
323
}
324
325
interface Breadcrumb {
326
message?: string;
327
category?: string;
328
level?: SeverityLevel;
329
timestamp?: number;
330
type?: string;
331
data?: { [key: string]: any };
332
}
333
334
type SeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug";
335
336
interface Scope {
337
addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): Scope;
338
setUser(user: User | null): Scope;
339
setTag(key: string, value: Primitive): Scope;
340
setContext(key: string, context: Context | null): Scope;
341
setLevel(level: SeverityLevel): Scope;
342
setFingerprint(fingerprint: string[]): Scope;
343
}
344
```
345
346
### Span and Tracing Types
347
348
```typescript { .api }
349
interface StartSpanOptions {
350
name: string;
351
attributes?: Record<string, any>;
352
startTime?: number;
353
parentSpan?: Span;
354
scope?: Scope;
355
onlyIfParent?: boolean;
356
forceTransaction?: boolean;
357
op?: string;
358
origin?: string;
359
}
360
361
interface Span {
362
spanContext(): SpanContext;
363
setAttribute(key: string, value: any): Span;
364
setAttributes(attributes: Record<string, any>): Span;
365
setStatus(status: SpanStatus): Span;
366
updateName(name: string): Span;
367
end(endTime?: number): void;
368
isRecording(): boolean;
369
}
370
371
interface TraceData {
372
"sentry-trace": string;
373
baggage?: string;
374
}
375
376
interface MonitorConfig {
377
schedule?: {
378
type: 'crontab' | 'interval';
379
value: string;
380
};
381
checkinMargin?: number;
382
maxRuntime?: number;
383
timezone?: string;
384
}
385
386
interface CheckIn {
387
monitorSlug: string;
388
status: 'in_progress' | 'ok' | 'error';
389
duration?: number;
390
checkInId?: string;
391
}
392
393
interface CronConfig {
394
name: string;
395
schedule: string;
396
onStart?: () => void;
397
onComplete?: () => void;
398
onError?: (error: Error) => void;
399
}
400
401
interface Integration {
402
name: string;
403
setupOnce?: (addGlobalEventProcessor: any, getCurrentHub: any) => void;
404
setup?: (options: any) => void;
405
}
406
407
interface BreadcrumbHint {
408
message?: string;
409
category?: string;
410
level?: SeverityLevel;
411
[key: string]: any;
412
}
413
```