UNPKG

@coralogix/browser

Version:

Official Coralogix SDK for browsers

1,229 lines (939 loc) 37.9 kB
<details> <summary><strong>Table of Contents</strong></summary> 1. [Official Coralogix SDK for Browsers](#official-coralogix-sdk-for-browsers) 2. [Links](#links) 3. [Supported Frameworks](#supported-frameworks) 4. [Usage](#usage) 5. [Sampling](#sampling) - [Basic Sampling](#1-basic-sampling---sample--of-all-sessions) - [Advanced Sampling](#2-advanced-sampling---sample--of-sessions-but-always-track-sessions-with-errors) - [Exclude Specific Instrumentations from Sampling](#3-exclude-specific-instrumentations-from-sampling) - [Only Sessions with Errors](#4-only-sessions-with-errors) 6. [Sending Custom Logs](#sending-custom-logs) 7. [Instrumentations](#instrumentations) 8. [Manually Capture Errors](#manually-capture-errors) 9. [Session Recording](#session-recording) - [Recording Manually](#recording-manually) - [Privacy & Security](#privacy--security) - [Worker URL](#worker-url) - [Screenshots](#screenshots) 10. [Manually Create a New Session](#manually-create-a-new-session) 11. [Unique Users](#unique-users) 12. [Network Extra Configuration](#network-extra-configuration) 13. [Multi Page Application](#multi-page-application) 14. [Ignore Errors](#ignore-errors) 15. [Ignore URLs](#ignore-urls) 16. [Stack Trace Limit](#stack-trace-limit) 17. [Mask Elements](#mask-elements) 18. [Custom Action Names](#custom-action-names) 19. [Label Providers](#label-providers) 20. [URL Blueprinters](#url-blueprinters) 21. [Traces](#traces) - [Propagate Trace Header for CORS URLs](#propagatetraceheadercorsurls) - [Allowed Tracing URLs](#allowedtracingurls) - [Extra Propagators (B3 / AWS X-Ray)](#b3--aws-x-ray-propagation) - [Custom Propagation](#custom-propagation) - [Traces Exporter](#traces-exporter) 22. [Before Send](#before-send) 23. [Proxy URL](#proxy-url) - [ignoreProxyUrlParams](#ignoreproxyurlparams) 24. [Collect IP Data](#collect-ip-data) 25. [SDK Fetch Priority](#sdk-fetch-priority) 26. [Custom Measurement](#custom-measurement) 27. [Add Timing](#add-timing) 28. [Custom Time Measurement](#custom-time-measurement) 29. [Microfrontend Support](#microfrontend-support) - [Pre Requisites](#pre-requisites) 30. [Custom Spans](#custom-spans) - [Ignored Instruments](#ignored-instruments) 31. [OpenTelemetry Batch Configuration](#opentelemetry-batch-configuration) 32. [Soft Navigations (Experimental)](#soft-navigations--experimental) 33. [Memory Usage (Experimental)](#memory-usage---experimental) 34. [Web Worker Support](#web-worker-support) - [Enabling Web Worker Support](#enabling-web-worker-support) - [Examples](#examples) 35. [Angular Zone.js Configuration](#angular-zonejs-configuration) 36. [CDN](#cdn) - [Specific Version](#specific-version-recommended) - [ES5](#es5) - [Add the CDN Script to Your Application](#add-the-cdn-script-to-your-application) - [Initialization](#initialization) - [Via JS File](#via-js-file) - [Via TS File](#via-ts-file) 37. [Flutter Web](#flutter-web) --- </details> # Official Coralogix SDK for Browsers [![npm version](https://img.shields.io/npm/v/@coralogix/browser.svg)](https://www.npmjs.com/package/@coralogix/browser) ## Links - [Changelog](https://coralogix.github.io/coralogix-browser-sdk/CHANGELOG.html) - [Coralogix Real User Monitoring](https://coralogix.com/docs/real-user-monitoring/) ## Supported Frameworks JavaScript / TypeScript Frameworks: React, Angular, Vue, NextJS and more.<br> Flutter (Currently only web). ## Usage To use Coralogix SDK for Browsers, call `CoralogixRum.init(options)` at the soonest available moment after the page load. This will initialize the SDK based on the options you provided. ```javascript import { CoralogixRum } from '@coralogix/browser'; CoralogixRum.init({ application: 'app-name', environment: 'production', public_key: 'abc-123-456', coralogixDomain: 'EU2', version: 'v1.0.3', labels: { payment: 'visa', }, sessionConfig: { sessionSampleRate: 100, // Percentage of overall sessions being tracked, defaults to 100% }, }); ``` To provide contextual information or transmit manual logs, utilize the exported functions of `CoralogixRum`. Keep in mind that these functions will remain inactive until you've invoked `CoralogixRum.init()`. ```javascript import { CoralogixRum } from '@coralogix/browser'; // Update user context dynamically CoralogixRum.setUserContext({ user_id: '123', user_name: 'name', user_email: 'user@email.com', user_metadata: { role: 'admin', // ... }, }); // Update custom labels dynamically CoralogixRum.setLabels({ ...CoralogixRum.getLabels(), paymentMethod: 'visa', userTheme: 'dark', // ... }); // Update application context dynamically CoralogixRum.setApplicationContext({ application: 'app-name', version: '1.0.0', }); ``` ### Sampling #### 1. Basic Sampling - sample % of all sessions ```javascript CoralogixRum.init({ // ... sessionConfig: { sessionSampleRate: 50, // Percentage of overall sessions being tracked, defaults to 100% }, }); ``` #### 2. Advanced Sampling - sample % of sessions, but always track sessions with errors This configuration will ensure all sessions with errors are tracked, and a percentage of sessions without errors are also tracked. ```javascript CoralogixRum.init({ // ... sessionConfig: { sessionSampleRate: 50, alwaysTrackSessionsWithErrors: true, }, }); ``` #### 3. Exclude Specific Instrumentations from Sampling Keep specific instrumentations running at 100% even when sessions are sampled out. This is useful when you want to reduce data volume with sampling but still capture all errors or custom logs. ```javascript CoralogixRum.init({ // ... sessionConfig: { sessionSampleRate: 20, // Only 20% of sessions are fully tracked excludeFromSampling: ['custom'], // These will run at 100% regardless of sampling }, }); ``` #### 4. Only Sessions with Errors Track only sessions with errors, and send specific instrumentation data immediately even if error is not occurred. From Session recording perspective, the SDK will record approximately 10–60s(according to maxRecordTime property) before the error occurred. ```javascript CoralogixRum.init({ // ... sessionConfig: { onlyWithErrorConfig: { enable: true, // Whether to track only sessions with errors, defaults to false maxRumEvents: 5000, // Maximum number of cached RUM events to store in cache up until error is coming, defaults to 5000, max 20000 maxRecordTime: 10_000, // Maximum time in milliseconds to store last record events in cache before error occurred, defaults to 10000(10s), max 60000(1m) /** * Specifies the instrumentation data to be sent for sessions with errors, defaulting to web-vitals only. * The instrumentation data will only be sent if it is enabled in the main configuration. * This data will be sent immediately, even if no error has occurred. */ instrumentationsToSend: { [CoralogixEventType.WEB_VITALS]: true, // more instrumentation's can be added // [CoralogixEventType.LONG_TASK]: true, //... }, }, }, }); ``` ### Sending Custom Logs ```javascript import { CoralogixRum, CoralogixLogSeverity } from '@coralogix/browser'; // send custom logs with different severity levels CoralogixRum.log(CoralogixLogSeverity.Info, 'this is a custom log'); // send custom logs with extra data CoralogixRum.log(CoralogixLogSeverity.Error, 'this is an error custom log with extra data', { data: 'tbd' }); // send custom logs with extra data, call the error severity log directly CoralogixRum.error('this is a custom log with error severity', { data: 'tbd' }); // send custom logs with extra data and labels CoralogixRum.warning( 'this is a custom log message with warning severity', { data: 'tbd', }, { my_label_key: 'my label value', } ); // data is optional unless labels are provided, in which case data is required (can be null CoralogixRum.log(CoralogixLogSeverity.Info, 'this is a custom log message with info severity', null, { my_label_key: 'my label value', }); ``` ### Instrumentation's Turn on/off specific instrumentation, default to all trues. Each instrumentation is responsible for which data the SDK will track and collect for you. ```javascript CoralogixRum.init({ // ... instrumentations: { xhr: true, fetch: true, web_vitals: false, interactions: false, custom: true, errors: true, long_tasks: true, resources: false, }, }); ``` ##### Web Vitals: TBT metric By default, the **TBT** (Total Blocking Time) metric is disabled. To enable it, explicitly configure it as shown below: ```json { "instrumentations": { "web_vitals": { "enabled": true, "metrics": { "tbt": true } } } } ``` ### Manually Capture Errors You can pass an Error object to capture it as an event.<br> Additionally, you can include custom data and labels with the event. ```javascript try { // Some code that might throw an error } catch (error) { CoralogixRum.captureError(error); CoralogixRum.captureError(error, { custom_data: { id: '123' } }); // add custom data CoralogixRum.captureError(error, { custom_data: { id: '123' } }, { label1: 'value1' }); // add custom data and labels } ``` ### Session Recording Session Recording enhances your user experience monitoring by enabling you to record and visually replay the web browsing activities of your users. ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { enable: true, // Must declare. /** * If autoStartSessionRecording is false, you can manually start & stop your session recording. * Refer to Recording Manually Section. **/ autoStartSessionRecording: true, // Automatically records your session when SDK is up. recordConsoleEvents: true, // Will record all console events from dev tools. Levels: log, debug, warn, error, info, table etc.. sessionRecordingSampleRate: 100, // Percentage of overall sessions recording being tracked, defaults to 100% and applied after the overall sessionSampleRate. immediateFlush: false, // Flush recording events immediately on start to capture short-duration sessions (<10s). Defaults to false. }, }); ``` #### Recording Manually You can always start/stop your session recording manually as follows: ```javascript // To start manually the Session Recording CoralogixRum.startSessionRecording(); // To stop the Session Recording CoralogixRum.stopSessionRecording(); ``` #### Privacy & Security To protect your users’ privacy and sensitive information, elements containing certain class names are blocked or masked in recordings, as follows: ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { // .. blockClass: 'rr-block', // Use a string or RegExp to redact all elements that contain this class, defaults to rr-block. ignoreClass: 'rr-ignore', // Use a string or RegExp to Ignore all events that contain this class, defaults to rr-ignore. maskTextClass: 'rr-mask', // Use a string or RegExp to mask all elements that contain this class, defaults to rr-mask. maskAllInputs: false, // Mask all input content as * (Default false), refer to Input types. maskInputOptions: { password: true }, // Mask some kinds of input as *, By Default the SDK masking password inputs. }, }); ``` Example: ```html <div class="rr-block">Dont record me</div> ``` | Element | Action | | ---------- | -------------------------------------------------------------------------------------------------------------------------------- | | .rr-block | An element with the class name .rr-block will not be recorded. Instead, it will replay as a placeholder with the same dimension. | | .rr-ignore | An element with the class name .rr-ignore will not record its input events | | .rr-mask | All text of elements and their children will be masked. | If you want to mask all of your inputs and texts in the session, you can use the following configuration: ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { // ... maskAllInputs: true, maskTextSelector: '*', }, }); ``` #### Worker Url By default, Session recording uses an inline web worker script to compress data before transmission. For added flexibility, you can host a custom worker script on your own domain. Simply host the following file on your server: [worker.min.js](https://cdn.rum-ingress-coralogix.com/coralogix/browser/latest/worker.min.js) For a locally hosted worker file: ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { // ... workerUrl: '/assets/worker.min.js', }, }); ``` For an externally hosted worker file: ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { // ... workerUrl: 'https://cdn.rum-ingress-coralogix.com/coralogix/browser/latest/worker.min.js', }, }); ``` #### Screenshots Screenshot is a feature that allows you to capture a screenshot of the user's screen at the time of an error or based on specific custom logic triggers.<br> Note that the Screenshot feature is a subset of session recording and shares the same configurations, including options like masking, sample rate and others.<br> `sessionRecordingConfig` must be enabled to use this feature.<br> ```javascript CoralogixRum.init({ // ... sessionRecordingConfig: { enable: true, // ... }, }); ``` Capture a screenshot manually: ```javascript CoralogixRum.screenshot(); // or with a description CoralogixRum.screenshot('Screenshot after the user logged in'); ``` Capture a screen automatically based on custom logic, using the beforeSend ```javascript CoralogixRum.init({ // ... beforeSend: (event) => { // ... // automatically take a screenshot when an error occurs and append the screenshot id to the event if (event.event_context.type === 'error' && event.session_context.user_name === 'CEO') { const id = CoralogixRum.screenshot('creating a screenshot due to an error!'); event.screenshotId = id; } return event; }, }); ``` ### Manually Create a New Session By default the SDK rotates the session automatically — after 15 minutes of inactivity, or once a session reaches 1 hour. Starting with version `3.19.0`, you can also rotate it on demand by calling `CoralogixRum.createNewSession()`, for example when a user logs out, so that subsequent events are attributed to a fresh session. ```javascript import { CoralogixRum } from '@coralogix/browser'; // e.g. inside your logout handler CoralogixRum.createNewSession(); ``` This ends the current session and immediately starts a new one with a new session id. If session recording is active, the current recording is finalized and a new one begins for the new session. ### Unique Users Starting with version `2.9.0`, the SDK calculates unique users based on the user’s `fingerprint`.<br> The fingerprint is generated and stored on each user’s machine for reuse.<br> In earlier versions, the SDK used user_id to calculate unique users, which is still supported for backward compatibility.<br> ### Network Extra Configuration The `networkExtraConfig` property is an array of configuration objects, each specifying custom rules for capturing network requests and responses. This feature collects data from `Fetch` and `XMLHttpRequest` calls, attaching specified request and response information, headers, and payloads to each network event. ```javascript CoralogixRum.init({ networkExtraConfig: [ { url: 'http://example.com', // Capture requests to this specific URL or regex pattern reqHeaders: ['Authorization', 'Content-Type'], // Capture 'Authorization' and 'Content-Type' headers in requests resHeaders: ['Cache-Control', 'Date'], // Capture 'Cache-Control' and 'Date' headers in responses collectReqPayload: true, // Collect request payload collectResPayload: false, // Do not collect response payload }, ], }); ``` #### Important Note The server must explicitly permit access to specific headers by listing them in the `Access-Control-Expose-Headers` response header. Due to restrictions in the Fetch and XHR APIs, header retrieval operates on a best-effort basis, meaning that some headers may occasionally be unavailable in the events collected by this integration. Additionally, any large payloads exceeding the allowed size will be dropped. ### Multi Page Application If your application is not a single page application (SPA), you can initialize the SDK with a configuration to retain the session ID after a reload/refresh. This will prevent multiple sessions from being created when the user navigates within the app. ```javascript CoralogixRum.init({ // ... sessionConfig: { // ... keepSessionAfterReload: true, }, }); ``` ### Ignore Errors The ignoreErrors option allows you to exclude errors that meet specific criteria. This options accepts a set of strings and regular expressions to match against the event's error message. Use regular expressions for exact matching as strings remove partial matches. ```javascript import { CoralogixRum } from '@coralogix/browser'; CoralogixRum.init({ // ... ignoreErrors: [/Exact Match Error Message/, 'partial/match'], }); ``` ### Ignore Urls The ignoreUrls option allows you to exclude network requests that meet specific criteria. This options accepts a set of strings and regular expressions to match against the event's network url. Use regular expressions for exact matching as strings remove partial matches. ```javascript import { CoralogixRum } from '@coralogix/browser'; CoralogixRum.init({ // ... ignoreUrls: [/.*\.svg/, /.*\.ico/], // will ignore all requests to .svg and .ico files }); ``` ### Stack Trace Limit Browsers typically capture 10 stack frames by default. If your error stack traces are being truncated and you need to see deeper into the call stack, you can increase this limit using the `stackTraceLimit` option. ```javascript import { CoralogixRum } from '@coralogix/browser'; CoralogixRum.init({ // ... stackTraceLimit: 50, }); ``` > **Note:** Higher values may have a performance impact, as the browser needs to capture more frames each time an error is created. ### Mask elements User interactions capture text from clickable elements only (button, label, link, input, option). Elements text can be masked to prevent sensitive data exposure. <br>use `maskInputTypes` to specify the types of inputs to mask. defaults to: `['password']` <br>use `maskClass` to specify the class name that will be used to mask any clickable element. Default masking class is `cx-mask`. ```javascript CoralogixRum.init({ // ... maskInputTypes: ['password', 'date'], // will only mask password and date inputs maskClass: 'mask-me', // will mask any clickable element with class 'mask-me' }); ``` Examples of masked elements: ```javascript <button class="cx-mask"> <span>Some Text</span> </button> <button> <span class="cx-mask">Some Text</span> </button> <my-button-component class="cx-mask"> <button>Text</button> </my-button-component> ``` ### Custom Action Names The SDK uses various strategies to name click actions. For more control, define a `data-cx-action-name` attribute on clickable elements (or any of their parents) to set the action name. ```html <button data-cx-action-name="add-to-cart"> Add to Cart </button> <form data-cx-action-name="checkout-form"> <input type="text" placeholder="Card number" /> <button type="submit">Complete Purchase</button> </form> <nav data-cx-action-name="main-navigation"> <a href="/products">Products</a> <a href="/pricing">Pricing</a> </nav> ``` > **Note:** The `data-cx-action-name` attribute is never masked, even when the element has a mask class applied. This ensures your custom action names are always captured for tracking purposes. ### Label Providers Provide labels based on url or event ```javascript import { CoralogixRum } from '@coralogix/browser'; const featurePageUrlLabelProvider = new UrlBasedLabelProvider({ urlType: UrlType.PAGE, urlPatterns: [ { regexps: [/apm/], labels: { featureGroupId: 'apm' }, }, ], defaultLabels: { featureGroupId: 'unknown-feature-group', }, }); const regularExpErrorLabelProvider: GenericLabelProvider = { providerFunc: (url, event) => { if (event.error_context?.error_message?.includes('Invalid regular expression')) { return { regular_expression_error: 'true', }; } return {}; }, }; CoralogixRum.init({ // ... labelProviders: [featurePageUrlLabelProvider, regularExpErrorLabelProvider], }); ``` ### Url Blueprinters Modify the event's page or network url based on custom-defined functions. ```javascript import { CoralogixRum } from '@coralogix/browser'; CoralogixRum.init({ // ... urlBlueprinters: { pageUrlBlueprinters: [ (url) => { const hostnameParts = new URL(url).hostname.split('.'); hostnameParts[0] = '{team-id}'; return 'https://' + hostnameParts.join('.'); // "https://alpha.company.com" => "https://{team-id}.company.com" }, ], networkUrlBlueprinters: [(url) => url.replace('api/v1', '{server}')], // "https://path/api/v1/logs" => "https://path/{server}/logs" }, }); ``` ### Traces Add trace context propagation in headers across service boundaries ```javascript CoralogixRum.init({ // ... traceParentInHeader: { enabled: true, }, }); ``` #### propagateTraceHeaderCorsUrls When the backend domain is different from the app domain, specifying backend domains is necessary. <br> For example, if the app is hosted on `https://app.com` and the backend is hosted on `https://webapi.com`, you should specify the backend domain. ```javascript CoralogixRum.init({ // ... traceParentInHeader: { enabled: true, options: { propagateTraceHeaderCorsUrls: [new RegExp('https://webapi.*')], }, }, }); ``` #### allowedTracingUrls Specify the allowed URLs to propagate the trace header. <br> Note that if allowedTracingUrls is not specified, the trace header will be propagated to all URLs.<br> allowedTracingUrls works only on 1st party URLs. (see propagateTraceHeaderCorsUrls for 3d party URLs) <br> <br>For example if you want to propagate the trace header only for URLs that contain the word `alpha`: ```javascript CoralogixRum.init({ // ... traceParentInHeader: { enabled: true, options: { allowedTracingUrls: [new RegExp('alpha')], }, }, }); ``` ### Extra Propagators #### B3 / AWS X-Ray Propagation ```javascript CoralogixRum.init({ // ... traceParentInHeader: { enabled: true, options: { // ... /* for B3 propagation */ propagateB3TraceHeader: { singleHeader: true, multiHeader: true, }, /* for Aws propagation */ propagateAwsXrayTraceHeader: true, }, }, }); ``` #### Custom Propagation ```javascript CoralogixRum.init({ // ... traceParentInHeader: { enabled: true, options: { // ... /* for Custom propagation */ propagateCustomTraceHeader: new CustomPropagator() }, }, }); // Example of CustomPropagator, Converts the 128-bit OpenTelemetry trace/span IDs into 64-bit decimal IDs import { TextMapGetter, TextMapSetter, TextMapPropagator, Context, trace, } from '@opentelemetry/api'; export class CustomPropagator implements TextMapPropagator { inject(context: Context, carrier: any, setter: TextMapSetter) { const span = trace.getSpan(context); if (!span) return; const spanContext = span.spanContext(); if (!spanContext) return; // Custom trace ID = last 64 bits of OTel trace ID const customTraceId = BigInt( '0x' + spanContext.traceId.slice(16) ).toString(); const customParentId = BigInt('0x' + spanContext.spanId).toString(); setter.set(carrier, 'my-custom-trace-id', customTraceId); setter.set(carrier, 'my-custom-parent-id', customParentId); } extract(context: Context, carrier: any, getter: TextMapGetter): Context { const traceIdHeader = getter.get(carrier, 'my-custom-trace-id'); const parentIdHeader = getter.get(carrier, 'my-custom-parent-id'); if (!traceIdHeader || !parentIdHeader) return context; const traceId = BigInt(traceIdHeader as string) .toString(16) .padStart(32, '0'); const spanId = BigInt(parentIdHeader as string) .toString(16) .padStart(16, '0'); return trace.setSpan( context, trace.wrapSpanContext({ traceId, spanId, traceFlags: 1, isRemote: true, }) ); } fields(): string[] { return ['my-custom-trace-id', 'my-custom-parent-id']; } } ``` ### Before Send Enable event access and modification before sending to Coralogix, supporting content modification, and event discarding. ```javascript CoralogixRum.init({ // ... beforeSend: (event) => { // Discard events from @company.com users. if (event.session_context.user_email?.endsWith('@company.com')) { return null; } // Redact sensitive information from the page URL. event.page_context.page_url = event.page_context.page_url.replace('sensitive-info', 'redacted'); return event; }, }); ``` ### Proxy Url Proxy configuration to route requests. By specifying a proxy URL, all RUM data will be directed to this URL via the POST method. However, it is necessary for this data to be subsequently relayed from the proxy to Coralogix. The Coralogix route for each request that is sent to the proxy is available in the request’s cxforward parameter (for example, https://www.your-proxy.com/endpoint?cxforward=https%3A%2F%2Fingress.eu1.rum-ingress-coralogix.com%2Fbrowser%2Fv1beta%2Flogs). ```javascript CoralogixRum.init({ // ... coralogixDomain: 'EU1', proxyUrl: 'https://www.your-proxy.com/endpoint', }); ``` #### ignoreProxyUrlParams If you want the SDK to ignore the cxforward parameter and always send data to the proxy URL directly, you can use the ignoreProxyUrlParams option. By default, this option is disabled. ```javascript CoralogixRum.init({ // ... coralogixDomain: 'EU1', proxyUrl: 'https://proxy.mycompany.com/rum', ignoreProxyUrlParams: true, }); ``` ### Collect IP Data Determines whether the SDK should collect the user's IP address and corresponding geolocation data. Defaults to true. ```javascript CoralogixRum.init({ // ... collectIPData: true, }); ``` ### SDK Fetch Priority Controls the [`priority`](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#priority) hint applied to the SDK's own network requests — the internal calls it makes to send logs and recordings to Coralogix. This is unrelated to your application's requests. When omitted, the browser uses its default (Chromium treats this as `high`), which can cause SDK traffic to compete with your application's critical requests. Set `sdkFetchPriority: 'low'` to deprioritize SDK traffic. Accepted values: `'low'`, `'high'`, or `'auto'` (default). ```javascript CoralogixRum.init({ // ... sdkFetchPriority: 'low', }); ``` > **Note:** The `priority` hint only works in Chromium browsers (Chrome/Edge 101+) and is a no-op elsewhere. We type this option with our own `SdkFetchPriority` alias instead of the DOM `RequestPriority` type, so it still compiles on older TypeScript versions (the SDK supports `>= 4.4.2`). ### Custom Measurement Custom measurement allows you to send numeric data to Coralogix for precise monitoring and analysis. ```javascript CoralogixRum.sendCustomMeasurement('my-page-load', 1000); ``` ### Add Timing Add timing is a simple API to add extra performance timing to your RUM data.<br> The timing relates to the time between the page load and the moment the timing is added.<br> For example, you can add a timing for the first click event. ```javascript window.addEventListener('click', function handler() { window.removeEventListener('click', handler); CoralogixRum.addTiming('first-click'); }); ``` OR You can provide your own timing. ```javascript window.addEventListener('click', function handler() { window.removeEventListener('click', handler); CoralogixRum.addTiming('first-click', 1000); }); ``` ### Custom Time Measurement Custom time measurement allows you to track the time between two points by starting a timer with `startTimeMeasure` and stopping it with `endTimeMeasure`, using a unique name to identify each measurement. Labels can be added at the start for additional context. ```javascript CoralogixRum.startTimeMeasure('login', { paymentMethod: 'visa', userTheme: 'dark', }); ``` ```javascript CoralogixRum.endTimeMeasure('login'); ``` ### Microfrontend support This feature allows you to track multiple applications on the same page.<br> <b>Only errors with stacktrace are supported.</b> #### Pre Requisites To support microfrontend, you need to install one of these plugins: [webpack](https://www.npmjs.com/package/@coralogix/webpack-plugin), [esbuild](https://www.npmjs.com/package/@coralogix/esbuild-plugin), [vite](https://www.npmjs.com/package/@coralogix/vite-plugin) and include them in your build process. When an error occurs, the SDK will find the correlated microfrontend and will add a label with the microfrontend app/version to the error event. ```javascript CoralogixRum.init({ // ... supportMfe: true, }); ``` ### Custom Spans Create your own custom spans to track specific operations in your application.<br> Each span will share the same trace ID, which will allow you to create flows in your application and see them in the [Tracing view](https://coralogix.com/docs/user-guides/monitoring-and-insights/distributed-tracing/distributed-tracing/).<br> Labels can be added during span creation for additional context. ```javascript const customTracer = CoralogixRum.getCustomTracer(); const globalSpan = customTracer.startGlobalSpan('global-span', { page: 'posts' }); // Easily create custom spans for specific operations in your application. globalSpan.startCustomSpan('submit-button', { action: 'click' }).endSpan(); // You can also use the with context method to modeling a specific flow in your application. globalSpan.withContext(async () => { globalSpan.startCustomSpan('get-data-btn', { action: 'click' }).endSpan(); const res = await fetch('my-api-endpoint'); globalSpan.startCustomSpan('click-on-first-row', { action: 'click' }).endSpan(); // ... your code }); // note: End the global span only after the operation is complete. globalSpan.endSpan(); ``` #### Ignored Instruments After creating a global span, some of the instrumented events (network, errors, interactions) will automatically share the same trace ID, unless specifically ignored. ```javascript const customTracer = CoralogixRum.getCustomTracer({ ignoredInstruments: [CoralogixEventType.NETWORK_REQUEST, CoralogixEventType.ERROR, CoralogixEventType.USER_INTERACTION], }); // ... your code ``` ### Traces Exporter The `tracesExporter` callback gives you full control over how collected trace events are handled. It receives a `TraceExporterData` object containing all trace data that the SDK has collected. ```ts CoralogixRum.init({ tracesExporter: (data: TraceExporterData) => { // Example: forward traces to your own backend endpoint fetch('https://api.mycompany.com/rum-traces', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); }, }); ``` ### OpenTelemetry Batch Configuration The SDK batches logs and traces through an OpenTelemetry `BatchSpanProcessor` before sending them to Coralogix. Use `otelConfig` to tune that batching — for example, to flush less frequently and reduce the number of network requests your app makes. All fields are optional. Omitting `otelConfig` keeps the SDK defaults, and any out-of-range value is clamped to the documented bounds. ```javascript CoralogixRum.init({ // ... otelConfig: { maxExportBatchSize: 50, // Max spans per export; reaching it triggers an early flush. Defaults to 50, min 1, max 256 scheduledDelayMillis: 2000, // Delay in ms between two consecutive exports. Defaults to 2000(2s), min 2000(2s), max 30000(30s) maxQueueSize: 2048, // Max buffered spans before new spans are dropped. Defaults to 2048, min 512, max 4096 }, }); ``` ### Soft Navigations — Experimental Soft navigations are navigations that do not trigger a full page reload, such as SPA navigations. Defaults to false. With this option enabled, the SDK will track soft navigations and Partial Web vitals metrics such as (TTFB, FCP, LCP, CLS, INP). **<b><i> This feature requires enabling the feature flag(#enable-experimental-web-platform-features) in the browser. </i></b> ** ```javascript CoralogixRum.init({ // ... trackSoftNavigations: false, }); ``` ### Memory Usage - Experimental Memory usage is a feature that allows you to track the memory usage of your application. It uses the [measureUserAgentSpecificMemory](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measureUserAgentSpecificMemory) API.<br> The SDK will collect memory usage data every interval and send it to Coralogix.<br> To enable the feature, your website needs to be in a [secure context](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measureUserAgentSpecificMemory#security_requirements). ```javascript CoralogixRum.init({ // ... memoryUsageConfig: { enabled: true, interval: 300_000, // Defaults to 5 minutes }, }); ``` You can also manually trigger memory usage data collection. ```javascript CoralogixRum.measureUserAgentSpecificMemory(); ``` ## Web Worker Support Web Worker support enables the capture of events originating from Web Workers, including unhandled errors, custom logs, and other functionalities provided by the SDK. > By default, Web Worker support is **disabled**. --- ### Enabling Web Worker Support ```javascript CoralogixRum.init({ workerSupport: true, }); ``` --- #### Examples ```javascript // App code – creating a worker. The SDK will automatically capture errors from it. const worker = new Worker('my-worker.js'); ``` ```javascript // Worker code // Log a basic info log worker.CoralogixRum.log(CoralogixLogSeverity.Info, 'Test log from worker'); // Manually capture errors try { // Some code that might throw an error } catch (error) { worker.CoralogixRum.captureError(error, { worker: 'analytics-worker' }, { label1: 'value1' }); } // Log messages received in the worker self.onmessage = (message) => { worker.CoralogixRum.log(CoralogixLogSeverity.Info, message); }; ``` --- ## Angular Zone.js Configuration By default, the SDK runs its internal timers outside Angular's Zone.js to prevent unnecessary change detection cycles. This improves performance by avoiding redundant UI updates triggered by the SDK's background operations. ```javascript CoralogixRum.init({ // ... runOutsideAngularZone: true, // Defaults to true }); ``` | Value | Behavior | | ------- | ------------------------------------------------------------------------ | | `true` | SDK timers run outside Zone.js, preventing change detection triggers. | | `false` | SDK timers run inside Zone.js, which may trigger change detection. | > **Note:** In most cases, you should keep the default value (`true`) for optimal performance. Only set to `false` if you have a specific reason to include SDK operations in Angular's change detection. --- ## CDN Coralogix Browser SDK is also provided via CDN.<br> You can choose your desired version. #### Specific Version (recommended) By default, the CDN is built using the <b>ES2015 (ES6)</b> standard.<br> https://cdn.rum-ingress-coralogix.com/coralogix/browser/[version]/coralogix-browser-sdk.js \ Replace [version] with a version from [Releases page](https://www.npmjs.com/package/@coralogix/browser?activeTab=versions). #### ES5 If you are targeting legacy environments, make sure to use the ES5-compatible version. https://cdn.rum-ingress-coralogix.com/coralogix/browser/[version]/coralogix-browser-sdk.es5.js > _**Note: CDN latest has no longer maintained, please use an explicit version instead.**_ ### Add the CDN script to your application ```javascript <head> ... <script src="https://cdn.rum-ingress-coralogix.com/coralogix/browser/[version]/coralogix-browser-sdk.js"></script> </head> ``` ### Initialization #### Via JS file ```javascript window.CoralogixRum.init(...); ``` #### Via TS file ```javascript window.CoralogixRum.init(...); // In case of warning from TSC declare global { interface Window { CoralogixRum: any; } } ``` ## Flutter web Coralogix Browser SDK is also provided for Flutter web. Add the following CDN to your `index.html` file: ```javascript <script src="https://cdn.rum-ingress-coralogix.com/coralogix/browser/[version]/coralogix-browser-sdk.js"></script> ``` Then, in your Dart code, you can use the SDK as follows: ```dart import 'package:flutter/material.dart'; import 'dart:js' as js; void main() { runApp(const MyApp()); var rum = js.JsObject.fromBrowserObject(js.context['CoralogixRum']); rum.callMethod('init', [js.JsObject.jsify({ environment: 'test', application: 'my-app', version: '1.0.0', public_key: 'my-key-123', coralogixDomain: 'EU2', })]); } ```