@sentry/browser

  • Version 9.34.0
  • Published
  • 1.2 MB
  • 5 dependencies
  • MIT license

Install

npm i @sentry/browser
yarn add @sentry/browser
pnpm add @sentry/browser

Overview

Official Sentry SDK for browsers

Index

Variables

variable chromeStackLineParser

const chromeStackLineParser: StackLineParser;

    variable defaultRequestInstrumentationOptions

    const defaultRequestInstrumentationOptions: RequestInstrumentationOptions;

      variable defaultStackLineParsers

      const defaultStackLineParsers: StackLineParser[];

        variable defaultStackParser

        const defaultStackParser: any;

          variable feedbackAsyncIntegration

          const feedbackAsyncIntegration: any;
          • An integration to add user feedback to your application, while loading most of the code lazily only when it's needed.

          variable feedbackIntegration

          const feedbackIntegration: any;
          • Add a widget to capture user feedback to your application.

          variable feedbackSyncIntegration

          const feedbackSyncIntegration: any;
          • Add a widget to capture user feedback to your application.

          variable geckoStackLineParser

          const geckoStackLineParser: StackLineParser;

            variable opera10StackLineParser

            const opera10StackLineParser: StackLineParser;

              variable opera11StackLineParser

              const opera11StackLineParser: StackLineParser;

                variable WINDOW

                const WINDOW: any;

                  variable winjsStackLineParser

                  const winjsStackLineParser: StackLineParser;

                    Functions

                    breadcrumbsIntegration: (
                    options?: Partial<BreadcrumbsOptions> | undefined
                    ) => any;

                      function browserApiErrorsIntegration

                      browserApiErrorsIntegration: (
                      options?: Partial<BrowserApiErrorsOptions> | undefined
                      ) => any;
                      • Wrap timer functions and event targets to catch errors and provide better meta data.

                      function browserProfilingIntegration

                      browserProfilingIntegration: () => any;

                        function browserSessionIntegration

                        browserSessionIntegration: () => any;
                        • When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry. More information: https://docs.sentry.io/product/releases/health/

                          Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/

                        function browserTracingIntegration

                        browserTracingIntegration: (_options?: Partial<BrowserTracingOptions>) => {
                        name: string;
                        setup(client: Client<any>): void;
                        afterAllSetup(client: Client<any>): void;
                        };
                        • The Browser Tracing integration automatically instruments browser pageload/navigation actions as transactions, and captures requests, metrics and errors as spans.

                          The integration can be configured with a variety of options, and can be extended to use any routing library.

                          We explicitly export the proper type here, as this has to be extended in some cases.

                        function buildLaunchDarklyFlagUsedHandler

                        buildLaunchDarklyFlagUsedHandler: () => LDInspectionFlagUsedHandler;
                        • LaunchDarkly hook to listen for and buffer flag evaluations. This needs to be registered as an 'inspector' in LaunchDarkly initialize() options, separately from launchDarklyIntegration. Both the hook and the integration are needed to capture LaunchDarkly flags.

                        function contextLinesIntegration

                        contextLinesIntegration: (options?: ContextLinesOptions | undefined) => any;
                        • Collects source context lines around the lines of stackframes pointing to JS embedded in the current page's HTML.

                          This integration DOES NOT work for stack frames pointing to JS files that are loaded by the browser. For frames pointing to files, context lines are added during ingestion and symbolication by attempting to download the JS files to the Sentry backend.

                          Use this integration if you have inline JS code in HTML pages that can't be accessed by our backend (e.g. due to a login-protected page).

                        function createUserFeedbackEnvelope

                        createUserFeedbackEnvelope: (
                        feedback: UserFeedback,
                        {
                        metadata,
                        tunnel,
                        dsn,
                        }: {
                        metadata: SdkMetadata | undefined;
                        tunnel: string | undefined;
                        dsn: DsnComponents | undefined;
                        }
                        ) => EventEnvelope;
                        • Creates an envelope from a user feedback.

                        function diagnoseSdkConnectivity

                        diagnoseSdkConnectivity: () => Promise<
                        'no-client-active' | 'sentry-unreachable' | 'no-dsn-configured' | void
                        >;
                        • A function to diagnose why the SDK might not be successfully sending data.

                          Possible return values wrapped in a Promise: - "no-client-active" - There was no active client when the function was called. This possibly means that the SDK was not initialized yet. - "sentry-unreachable" - The Sentry SaaS servers were not reachable. This likely means that there is an ad blocker active on the page or that there are other connection issues.

                          If the function doesn't detect an issue it resolves to undefined.

                        function eventFromException

                        eventFromException: (
                        stackParser: StackParser,
                        exception: unknown,
                        hint?: EventHint,
                        attachStacktrace?: boolean
                        ) => PromiseLike<Event>;
                        • Creates an Event from all inputs to captureException and non-primitive inputs to captureMessage.

                        function eventFromMessage

                        eventFromMessage: (
                        stackParser: StackParser,
                        message: ParameterizedString,
                        level?: SeverityLevel,
                        hint?: EventHint,
                        attachStacktrace?: boolean
                        ) => PromiseLike<Event>;
                        • Builds and Event from a Message

                        function exceptionFromError

                        exceptionFromError: (stackParser: StackParser, ex: Error) => Exception;
                        • This function creates an exception from a JavaScript Error

                        function forceLoad

                        forceLoad: () => void;
                        • This function is here to be API compatible with the loader.

                        function getDefaultIntegrations

                        getDefaultIntegrations: (_options: Options) => Integration[];
                        • Get the default integrations for the browser SDK.

                        function globalHandlersIntegration

                        globalHandlersIntegration: (
                        options?: Partial<GlobalHandlersIntegrations> | undefined
                        ) => any;

                          function graphqlClientIntegration

                          graphqlClientIntegration: (options: GraphQLClientOptions) => any;
                          • This integration ensures that GraphQL requests made in the browser have their GraphQL-specific data captured and attached to spans and breadcrumbs.

                          function httpClientIntegration

                          httpClientIntegration: (options?: Partial<HttpClientOptions> | undefined) => any;
                          • Create events for failed client side HTTP requests.

                          function httpContextIntegration

                          httpContextIntegration: () => any;
                          • Collects information about HTTP request headers and attaches them to the event.

                          function init

                          init: (options?: BrowserOptions) => Client | undefined;
                          • The Sentry Browser SDK Client.

                            To use this SDK, call the init function as early as possible when loading the web page. To set context information or send manual events, use the provided methods.

                            Example 1

                            import { init } from '@sentry/browser';
                            init({
                            dsn: '__DSN__',
                            // ...
                            });

                            Example 2

                            import { addBreadcrumb } from '@sentry/browser';
                            addBreadcrumb({
                            message: 'My Breadcrumb',
                            // ...
                            });

                            Example 3

                            import * as Sentry from '@sentry/browser';
                            Sentry.captureMessage('Hello, world!');
                            Sentry.captureException(new Error('Good bye'));
                            Sentry.captureEvent({
                            message: 'Manual',
                            stacktrace: [
                            // ...
                            ],
                            });

                            See Also

                          function instrumentOutgoingRequests

                          instrumentOutgoingRequests: (
                          client: Client,
                          _options?: Partial<RequestInstrumentationOptions>
                          ) => void;
                          • Registers span creators for xhr and fetch requests

                          function launchDarklyIntegration

                          launchDarklyIntegration: () => any;
                          • Sentry integration for capturing feature flag evaluations from LaunchDarkly.

                            See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.

                            Example 1

                            import * as Sentry from '@sentry/browser';
                            import {launchDarklyIntegration, buildLaunchDarklyFlagUsedInspector} from '@sentry/browser';
                            import * as LaunchDarkly from 'launchdarkly-js-client-sdk';
                            Sentry.init(..., integrations: [launchDarklyIntegration()])
                            const ldClient = LaunchDarkly.initialize(..., {inspectors: [buildLaunchDarklyFlagUsedHandler()]});

                          function lazyLoadIntegration

                          lazyLoadIntegration: (
                          name: keyof typeof LazyLoadableIntegrations,
                          scriptNonce?: string
                          ) => Promise<IntegrationFn>;
                          • Lazy load an integration from the CDN. Rejects if the integration cannot be loaded.

                          function linkedErrorsIntegration

                          linkedErrorsIntegration: (options?: LinkedErrorsOptions | undefined) => any;
                          • Aggregrate linked errors in an event.

                          function makeBrowserOfflineTransport

                          makeBrowserOfflineTransport: <T extends BaseTransportOptions>(
                          createTransport?: (options: T) => Transport
                          ) => (options: T & BrowserOfflineTransportOptions) => Transport;
                          • Creates a transport that uses IndexedDb to store events when offline.

                          function makeFetchTransport

                          makeFetchTransport: (
                          options: BrowserTransportOptions,
                          nativeFetch?: typeof WINDOW.fetch | undefined
                          ) => Transport;
                          • Creates a Transport that uses the Fetch API to send events to Sentry.

                          function onLoad

                          onLoad: (callback: () => void) => void;
                          • This function is here to be API compatible with the loader.

                          function openFeatureIntegration

                          openFeatureIntegration: () => any;

                            function reportingObserverIntegration

                            reportingObserverIntegration: (
                            options?: ReportingObserverOptions | undefined
                            ) => any;
                            • Reporting API integration - https://w3c.github.io/reporting/

                            function showReportDialog

                            showReportDialog: (options?: ReportDialogOptions) => void;
                            • Present the user with a report dialog.

                              Parameter options

                              Everything is optional, we try to fetch all info need from the current scope.

                            function spotlightBrowserIntegration

                            spotlightBrowserIntegration: (
                            options?: Partial<SpotlightConnectionOptions> | undefined
                            ) => any;
                            • Use this integration to send errors and transactions to Spotlight.

                              Learn more about spotlight at https://spotlightjs.com

                            function startBrowserTracingNavigationSpan

                            startBrowserTracingNavigationSpan: (
                            client: Client,
                            spanOptions: StartSpanOptions
                            ) => Span | undefined;
                            • Manually start a navigation span. This will only do something if a browser tracing integration has been setup.

                            function startBrowserTracingPageLoadSpan

                            startBrowserTracingPageLoadSpan: (
                            client: Client,
                            spanOptions: StartSpanOptions,
                            traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined }
                            ) => Span | undefined;
                            • Manually start a page load span. This will only do something if a browser tracing integration integration has been setup.

                              If you provide a custom traceOptions object, it will be used to continue the trace instead of the default behavior, which is to look it up on the tags.

                            function statsigIntegration

                            statsigIntegration: (args_0: { featureFlagClient: StatsigClient }) => any;
                            • Sentry integration for capturing feature flag evaluations from the Statsig js-client SDK.

                              See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.

                              Example 1

                              import { StatsigClient } from '@statsig/js-client';
                              import * as Sentry from '@sentry/browser';
                              const statsigClient = new StatsigClient();
                              Sentry.init({
                              dsn: '___PUBLIC_DSN___',
                              integrations: [Sentry.statsigIntegration({featureFlagClient: statsigClient})],
                              });
                              await statsigClient.initializeAsync(); // or statsigClient.initializeSync();
                              const result = statsigClient.checkGate('my-feature-gate');
                              Sentry.captureException(new Error('something went wrong'));

                            function unleashIntegration

                            unleashIntegration: (args_0: UnleashIntegrationOptions) => any;
                            • Sentry integration for capturing feature flag evaluations from the Unleash SDK.

                              See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.

                              Example 1

                              import { UnleashClient } from 'unleash-proxy-client';
                              import * as Sentry from '@sentry/browser';
                              Sentry.init({
                              dsn: '___PUBLIC_DSN___',
                              integrations: [Sentry.unleashIntegration({featureFlagClientClass: UnleashClient})],
                              });
                              const unleash = new UnleashClient(...);
                              unleash.start();
                              unleash.isEnabled('my-feature');
                              Sentry.captureException(new Error('something went wrong'));

                            Classes

                            class BrowserClient

                            class BrowserClient extends Client<BrowserClientOptions> {}
                            • The Sentry Browser SDK Client.

                              See Also

                              • BrowserOptions for documentation on configuration options.

                              • SentryClient for usage documentation.

                            constructor

                            constructor(options: any);
                            • Creates a new Browser SDK instance.

                              Parameter options

                              Configuration options for this SDK.

                            method eventFromException

                            eventFromException: (exception: unknown, hint?: EventHint) => PromiseLike<Event>;

                            method eventFromMessage

                            eventFromMessage: (
                            message: ParameterizedString,
                            level?: SeverityLevel,
                            hint?: EventHint
                            ) => PromiseLike<Event>;

                            class OpenFeatureIntegrationHook

                            class OpenFeatureIntegrationHook implements OpenFeatureHook {}
                            • OpenFeature Hook class implementation.

                            method after

                            after: (
                            _hookContext: Readonly<HookContext<JsonValue>>,
                            evaluationDetails: EvaluationDetails<JsonValue>
                            ) => void;
                            • Successful evaluation result.

                            method error

                            error: (
                            hookContext: Readonly<HookContext<JsonValue>>,
                            _error: unknown,
                            _hookHints?: HookHints
                            ) => void;
                            • On error evaluation result.

                            Interfaces

                            interface RequestInstrumentationOptions

                            interface RequestInstrumentationOptions {}
                            • Options for Request Instrumentation

                            property enableHTTPTimings

                            enableHTTPTimings: boolean;
                            • If true, Sentry will capture http timings and add them to the corresponding http spans.

                              Default: true

                            property traceFetch

                            traceFetch: boolean;
                            • Flag to disable patching all together for fetch requests.

                              Default: true

                            property tracePropagationTargets

                            tracePropagationTargets?: Array<string | RegExp>;
                            • List of strings and/or Regular Expressions used to determine which outgoing requests will have sentry-trace and baggage headers attached.

                              **Default:** If this option is not provided, tracing headers will be attached to all outgoing requests. If you are using a browser SDK, by default, tracing headers will only be attached to outgoing requests to the same origin.

                              **Disclaimer:** Carelessly setting this option in browser environments may result into CORS errors! Only attach tracing headers to requests to the same origin, or to requests to services you can control CORS headers of. Cross-origin requests, meaning requests to a different domain, for example a request to https://api.example.com/ while you're on https://example.com/, take special care. If you are attaching headers to cross-origin requests, make sure the backend handling the request returns a "Access-Control-Allow-Headers: sentry-trace, baggage" header to ensure your requests aren't blocked.

                              If you provide a tracePropagationTargets array, the entries you provide will be matched against the entire URL of the outgoing request. If you are using a browser SDK, the entries will also be matched against the pathname of the outgoing requests. This is so you can have matchers for relative requests, for example, /^\/api/ if you want to trace requests to your /api routes on the same domain.

                              If any of the two match any of the provided values, tracing headers will be attached to the outgoing request. Both, the string values, and the RegExes you provide in the array will match if they partially match the URL or pathname.

                              Examples: - tracePropagationTargets: [/^\/api/] and request to https://same-origin.com/api/posts: - Tracing headers will be attached because the request is sent to the same origin and the regex matches the pathname "/api/posts". - tracePropagationTargets: [/^\/api/] and request to https://different-origin.com/api/posts: - Tracing headers will not be attached because the pathname will only be compared when the request target lives on the same origin. - tracePropagationTargets: [/^\/api/, 'https://external-api.com'] and request to https://external-api.com/v1/data: - Tracing headers will be attached because the request URL matches the string 'https://external-api.com'.

                            property traceXHR

                            traceXHR: boolean;
                            • Flag to disable patching all together for xhr requests.

                              Default: true

                            property trackFetchStreamPerformance

                            trackFetchStreamPerformance: boolean;
                            • Flag to disable tracking of long-lived streams, like server-sent events (SSE) via fetch. Do not enable this in case you have live streams or very long running streams.

                              Disabled by default since it can lead to issues with streams using the cancel() api (https://github.com/getsentry/sentry-javascript/issues/13950)

                              Default: false

                            method onRequestSpanStart

                            onRequestSpanStart: (
                            span: Span,
                            requestInformation: { headers?: WebFetchHeaders }
                            ) => void;
                            • Is called when spans are started for outgoing requests.

                            method shouldCreateSpanForRequest

                            shouldCreateSpanForRequest: (this: void, url: string) => boolean;
                            • This function will be called before creating a span for a request with the given url. Return false if you don't want a span for the given url.

                              Default: (url: string) => true

                            Type Aliases

                            type BrowserOptions

                            type BrowserOptions = Options<BrowserTransportOptions> &
                            BrowserSpecificOptions & {
                            /**
                            * Important: Only set this option if you know what you are doing!
                            *
                            * By default, the SDK will check if `Sentry.init` is called in a browser extension.
                            * In case it is, it will stop initialization and log a warning
                            * because browser extensions require a different Sentry initialization process:
                            * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/
                            *
                            * Setting up the SDK in a browser extension with global error monitoring is not recommended
                            * and will likely flood you with errors from other web sites or extensions. This can heavily
                            * impact your quota and cause interference with your and other Sentry SDKs in shared environments.
                            *
                            * If this check wrongfully flags your setup as a browser extension, you can set this
                            * option to `true` to skip the check.
                            *
                            * @default false
                            */
                            skipBrowserExtensionCheck?: boolean;
                            };
                            • Configuration options for the Sentry Browser SDK.

                              See Also

                              • @sentry/core Options for more information.

                            Namespaces

                            namespace logger

                            module 'build/npm/types/log.d.ts' {}
                            • Capture a log with the trace level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.

                              Example 1

                              Sentry.logger.trace('User clicked submit button', {
                              buttonId: 'submit-form',
                              formId: 'user-profile',
                              timestamp: Date.now()
                              });

                              Example 2

                              With template strings

                              Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {
                              userId: '123',
                              sessionId: 'abc-xyz'
                              });

                            function debug

                            debug: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the debug level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { component: 'Header', state: 'loading' }.

                              Example 1

                              Sentry.logger.debug('Component mounted', {
                              component: 'UserProfile',
                              props: { userId: 123 },
                              renderTime: 150
                              });

                              Example 2

                              With template strings

                              Sentry.logger.debug(Sentry.logger.fmt`API request to ${endpoint} failed`, {
                              statusCode: 404,
                              requestId: 'req-123',
                              duration: 250
                              });

                            function error

                            error: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the error level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { error: 'NetworkError', url: '/api/data' }.

                              Example 1

                              Sentry.logger.error('Failed to load user data', {
                              error: 'NetworkError',
                              url: '/api/users/123',
                              statusCode: 500,
                              retryCount: 3
                              });

                              Example 2

                              With template strings

                              Sentry.logger.error(Sentry.logger.fmt`Payment processing failed for order ${orderId}`, {
                              error: 'InsufficientFunds',
                              amount: 100.00,
                              currency: 'USD',
                              userId: 'user-456'
                              });

                            function fatal

                            fatal: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the fatal level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { appState: 'corrupted', sessionId: 'abc-123' }.

                              Example 1

                              Sentry.logger.fatal('Application state corrupted', {
                              lastKnownState: 'authenticated',
                              sessionId: 'session-123',
                              timestamp: Date.now(),
                              recoveryAttempted: true
                              });

                              Example 2

                              With template strings

                              Sentry.logger.fatal(Sentry.logger.fmt`Critical system failure in ${service}`, {
                              service: 'payment-processor',
                              errorCode: 'CRITICAL_FAILURE',
                              affectedUsers: 150,
                              timestamp: Date.now()
                              });

                            function info

                            info: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the info level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { feature: 'checkout', status: 'completed' }.

                              Example 1

                              Sentry.logger.info('User completed checkout', {
                              orderId: 'order-123',
                              amount: 99.99,
                              paymentMethod: 'credit_card'
                              });

                              Example 2

                              With template strings

                              Sentry.logger.info(Sentry.logger.fmt`User ${user} updated profile picture`, {
                              userId: 'user-123',
                              imageSize: '2.5MB',
                              timestamp: Date.now()
                              });

                            function trace

                            trace: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the trace level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.

                              Example 1

                              Sentry.logger.trace('User clicked submit button', {
                              buttonId: 'submit-form',
                              formId: 'user-profile',
                              timestamp: Date.now()
                              });

                              Example 2

                              With template strings

                              Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {
                              userId: '123',
                              sessionId: 'abc-xyz'
                              });

                            function warn

                            warn: (message: ParameterizedString, attributes?: Log) => void;
                            • Capture a log with the warn level. Requires _experiments.enableLogs to be enabled.

                              Parameter message

                              The message to log.

                              Parameter attributes

                              Arbitrary structured data that stores information about the log - e.g., { browser: 'Chrome', version: '91.0' }.

                              Example 1

                              Sentry.logger.warn('Browser compatibility issue detected', {
                              browser: 'Safari',
                              version: '14.0',
                              feature: 'WebRTC',
                              fallback: 'enabled'
                              });

                              Example 2

                              With template strings

                              Sentry.logger.warn(Sentry.logger.fmt`API endpoint ${endpoint} is deprecated`, {
                              recommendedEndpoint: '/api/v2/users',
                              sunsetDate: '2024-12-31',
                              clientVersion: '1.2.3'
                              });

                            Package Files (33)

                            Dependencies (5)

                            Dev Dependencies (2)

                            Peer Dependencies (0)

                            No peer dependencies.

                            Badge

                            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@sentry/browser.

                            • Markdown
                              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@sentry/browser)
                            • HTML
                              <a href="https://www.jsdocs.io/package/@sentry/browser"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>