0
# Sentry Browser SDK
1
2
The Sentry Browser SDK provides comprehensive error monitoring, performance tracking, user feedback collection, and session management capabilities for client-side JavaScript applications. It offers automatic error capturing, manual event reporting, breadcrumb tracking, user context management, performance monitoring, session replay, and extensive integration options designed for maximum compatibility across modern browsers.
3
4
## Package Information
5
6
- **Package Name**: @sentry/browser
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @sentry/browser`
10
11
## Core Imports
12
13
```typescript
14
import * as Sentry from "@sentry/browser";
15
```
16
17
For specific functionality:
18
19
```typescript
20
import {
21
init,
22
captureException,
23
captureMessage,
24
addBreadcrumb,
25
setUser,
26
setTag,
27
setExtra
28
} from "@sentry/browser";
29
```
30
31
CommonJS:
32
33
```javascript
34
const Sentry = require("@sentry/browser");
35
// or specific imports
36
const { init, captureException } = require("@sentry/browser");
37
```
38
39
## Basic Usage
40
41
```typescript
42
import * as Sentry from "@sentry/browser";
43
44
// Initialize the SDK
45
Sentry.init({
46
dsn: "YOUR_DSN_HERE",
47
integrations: [
48
Sentry.browserTracingIntegration(),
49
Sentry.replayIntegration(),
50
],
51
tracesSampleRate: 1.0,
52
replaysSessionSampleRate: 0.1,
53
replaysOnErrorSampleRate: 1.0,
54
});
55
56
// Capture errors
57
try {
58
throw new Error("Something went wrong");
59
} catch (error) {
60
Sentry.captureException(error);
61
}
62
63
// Capture messages
64
Sentry.captureMessage("User clicked button", "info");
65
66
// Add context
67
Sentry.setUser({ id: "12345", email: "user@example.com" });
68
Sentry.setTag("environment", "production");
69
Sentry.addBreadcrumb({
70
message: "User navigated to page",
71
category: "navigation",
72
level: "info",
73
});
74
```
75
76
## Architecture
77
78
The Sentry Browser SDK is built around several key components:
79
80
- **Client**: Core `BrowserClient` class that manages configuration and event processing
81
- **SDK Initialization**: Main `init()` function with comprehensive configuration options
82
- **Event Capture**: Multiple capture methods for exceptions, messages, and custom events
83
- **Context Management**: Scope-based system for managing user context, tags, and extra data
84
- **Integrations**: Modular system with 25+ integrations for automatic and manual instrumentation
85
- **Transport Layer**: Pluggable transport system with fetch-based and offline-capable options
86
- **Performance Monitoring**: Comprehensive tracing system with browser-specific instrumentation
87
- **Session Replay**: Complete user session recording and playback capabilities
88
- **User Feedback**: Built-in widgets and APIs for collecting user feedback on errors
89
90
## Capabilities
91
92
### SDK Initialization and Configuration
93
94
Core SDK setup and configuration management for browser environments.
95
96
```typescript { .api }
97
function init(options?: BrowserOptions): Client | undefined;
98
99
interface BrowserOptions {
100
dsn?: string;
101
debug?: boolean;
102
environment?: string;
103
release?: string;
104
sampleRate?: number;
105
maxBreadcrumbs?: number;
106
attachStacktrace?: boolean;
107
sendDefaultPii?: boolean;
108
integrations?: Integration[];
109
beforeSend?: (event: Event, hint: EventHint) => Event | null | PromiseLike<Event | null>;
110
beforeBreadcrumb?: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => Breadcrumb | null;
111
tracesSampleRate?: number;
112
profilesSampleRate?: number;
113
// ... additional browser-specific options
114
}
115
```
116
117
[SDK Initialization](./sdk-initialization.md)
118
119
### Error and Event Capture
120
121
Comprehensive error capturing and event reporting functionality.
122
123
```typescript { .api }
124
function captureException(exception: any, hint?: EventHint): string;
125
function captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string;
126
function captureEvent(event: Event, hint?: EventHint): string;
127
function captureFeedback(feedback: FeedbackEvent, hint?: EventHint): string;
128
129
type SeverityLevel = "fatal" | "error" | "warning" | "info" | "debug";
130
```
131
132
[Error and Event Capture](./error-capture.md)
133
134
### Context and Scope Management
135
136
User context, tags, and extra data management system.
137
138
```typescript { .api }
139
function setUser(user: User): void;
140
function setTag(key: string, value: Primitive): void;
141
function setTags(tags: { [key: string]: Primitive }): void;
142
function setExtra(key: string, extra: Extra): void;
143
function setContext(key: string, context: Context): void;
144
function withScope(callback: (scope: Scope) => void): void;
145
146
interface User {
147
id?: string;
148
username?: string;
149
email?: string;
150
ip_address?: string;
151
[key: string]: any;
152
}
153
```
154
155
[Context Management](./context-management.md)
156
157
### Performance Monitoring and Tracing
158
159
Browser performance monitoring with distributed tracing capabilities.
160
161
```typescript { .api }
162
function startSpan(context: SpanContext): Span;
163
function getActiveSpan(): Span | undefined;
164
function withActiveSpan<T>(span: Span | null, callback: () => T): T;
165
function startNewTrace<T>(callback: () => T): T;
166
167
interface Span {
168
setTag(key: string, value: string): void;
169
setData(key: string, value: any): void;
170
setStatus(status: SpanStatus): void;
171
end(timestamp?: number): void;
172
}
173
```
174
175
[Performance Monitoring](./performance-monitoring.md)
176
177
### Integrations
178
179
Comprehensive integration system for automatic instrumentation and extended functionality.
180
181
```typescript { .api }
182
function browserTracingIntegration(options?: BrowserTracingOptions): Integration;
183
function replayIntegration(options?: ReplayOptions): Integration;
184
function feedbackIntegration(options?: FeedbackOptions): Integration;
185
function breadcrumbsIntegration(options?: BreadcrumbsOptions): Integration;
186
function globalHandlersIntegration(options?: GlobalHandlersOptions): Integration;
187
188
interface Integration {
189
name: string;
190
setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void;
191
}
192
```
193
194
[Integrations](./integrations.md)
195
196
### Session Management
197
198
User session tracking and management.
199
200
```typescript { .api }
201
function startSession(context?: SessionContext): Session;
202
function endSession(): void;
203
function captureSession(end?: boolean): void;
204
205
interface Session {
206
sid: string;
207
did?: string;
208
init: boolean;
209
timestamp: number;
210
started: number;
211
duration?: number;
212
status: SessionStatus;
213
release?: string;
214
environment?: string;
215
userAgent?: string;
216
ipAddress?: string;
217
user?: User;
218
}
219
```
220
221
[Session Management](./session-management.md)
222
223
### User Feedback
224
225
User feedback collection system with modal widgets and programmatic APIs.
226
227
```typescript { .api }
228
function showReportDialog(options?: ReportDialogOptions): void;
229
function getFeedback(): FeedbackWidget | null;
230
function sendFeedback(feedback: UserFeedback): void;
231
232
interface ReportDialogOptions {
233
eventId?: string;
234
dsn?: string;
235
user?: User;
236
title?: string;
237
subtitle?: string;
238
subtitle2?: string;
239
labelName?: string;
240
labelEmail?: string;
241
labelComments?: string;
242
labelClose?: string;
243
labelSubmit?: string;
244
errorGeneric?: string;
245
errorFormEntry?: string;
246
successMessage?: string;
247
onLoad?: () => void;
248
onClose?: () => void;
249
}
250
```
251
252
[User Feedback](./user-feedback.md)
253
254
### Session Replay
255
256
Complete user session recording and playback capabilities.
257
258
```typescript { .api }
259
function getReplay(): ReplayClient | undefined;
260
function replayIntegration(options?: ReplayOptions): Integration;
261
function replayCanvasIntegration(options?: ReplayCanvasOptions): Integration;
262
263
interface ReplayOptions {
264
sessionSampleRate?: number;
265
errorSampleRate?: number;
266
maskAllText?: boolean;
267
maskAllInputs?: boolean;
268
blockAllMedia?: boolean;
269
mutationBreadcrumbLimit?: number;
270
mutationLimit?: number;
271
slowClickTimeout?: number;
272
slowClickIgnoreSelectors?: string[];
273
}
274
```
275
276
[Session Replay](./session-replay.md)
277
278
### Transport and Communication
279
280
Transport layer for sending events to Sentry with offline support.
281
282
```typescript { .api }
283
function makeFetchTransport(options: BrowserTransportOptions): Transport;
284
function makeBrowserOfflineTransport(createTransport: (options: BrowserTransportOptions) => Transport): Transport;
285
286
interface BrowserTransportOptions {
287
url: string;
288
headers?: Record<string, string>;
289
fetchOptions?: RequestInit;
290
}
291
```
292
293
[Transport](./transport.md)
294
295
### Logging and Debugging
296
297
Structured logging API for capturing logs with different severity levels.
298
299
```typescript { .api }
300
namespace logger {
301
function trace(message: ParameterizedString, attributes?: Log['attributes']): void;
302
function debug(message: ParameterizedString, attributes?: Log['attributes']): void;
303
function info(message: ParameterizedString, attributes?: Log['attributes']): void;
304
function warn(message: ParameterizedString, attributes?: Log['attributes']): void;
305
function error(message: ParameterizedString, attributes?: Log['attributes']): void;
306
function fatal(message: ParameterizedString, attributes?: Log['attributes']): void;
307
function fmt(template: TemplateStringsArray, ...values: any[]): ParameterizedString;
308
}
309
310
function diagnoseSdkConnectivity(): Promise<DiagnosticReport>;
311
312
interface Log {
313
level: LogSeverityLevel;
314
message: ParameterizedString;
315
attributes?: Record<string, any>;
316
severityNumber?: number;
317
}
318
319
type LogSeverityLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
320
type ParameterizedString = string | { __sentry_template_string__: TemplateStringsArray; __sentry_template_values__: any[] };
321
322
interface DiagnosticReport {
323
success: boolean;
324
issues: DiagnosticIssue[];
325
}
326
327
interface DiagnosticIssue {
328
type: 'network' | 'configuration' | 'permissions';
329
message: string;
330
severity: 'error' | 'warning' | 'info';
331
}
332
```
333
334
**Usage Example:**
335
336
```typescript
337
import * as Sentry from "@sentry/browser";
338
339
// Initialize with logging enabled
340
Sentry.init({
341
dsn: "YOUR_DSN_HERE",
342
enableLogs: true,
343
});
344
345
// Structured logging
346
Sentry.logger.info("User completed checkout", {
347
orderId: "order-123",
348
amount: 99.99,
349
paymentMethod: "credit_card"
350
});
351
352
// Template string logging
353
Sentry.logger.debug(Sentry.logger.fmt`User ${userId} navigated to ${page}`, {
354
userId: "123",
355
sessionId: "abc-xyz"
356
});
357
358
// Diagnose connectivity issues
359
const report = await Sentry.diagnoseSdkConnectivity();
360
if (!report.success) {
361
console.error("SDK connectivity issues:", report.issues);
362
}
363
```
364
365
## Core Types
366
367
```typescript { .api }
368
interface Event {
369
event_id?: string;
370
message?: string;
371
timestamp?: number;
372
level?: SeverityLevel;
373
platform?: string;
374
logger?: string;
375
server_name?: string;
376
release?: string;
377
dist?: string;
378
environment?: string;
379
modules?: { [key: string]: string };
380
extra?: { [key: string]: any };
381
tags?: { [key: string]: Primitive };
382
contexts?: { [key: string]: Context };
383
user?: User;
384
exception?: {
385
values?: Exception[];
386
};
387
stacktrace?: Stacktrace;
388
request?: Partial<Request>;
389
transaction?: string;
390
fingerprint?: string[];
391
breadcrumbs?: Breadcrumb[];
392
}
393
394
interface Breadcrumb {
395
type?: string;
396
level?: SeverityLevel;
397
event_id?: string;
398
category?: string;
399
message?: string;
400
data?: any;
401
timestamp?: number;
402
}
403
404
interface Exception {
405
type?: string;
406
value?: string;
407
module?: string;
408
thread_id?: number;
409
stacktrace?: Stacktrace;
410
mechanism?: Mechanism;
411
}
412
413
interface Stacktrace {
414
frames?: StackFrame[];
415
frames_omitted?: [number, number];
416
}
417
418
interface StackFrame {
419
filename?: string;
420
function?: string;
421
module?: string;
422
platform?: string;
423
lineno?: number;
424
colno?: number;
425
abs_path?: string;
426
context_line?: string;
427
pre_context?: string[];
428
post_context?: string[];
429
in_app?: boolean;
430
instruction_addr?: string;
431
addr_mode?: string;
432
package?: string;
433
symbol?: string;
434
symbol_addr?: string;
435
image_addr?: string;
436
}
437
438
type Primitive = number | string | boolean | bigint | symbol | null | undefined;
439
type Context = Record<string, any>;
440
type Extra = any;
441
```