@coralogix/browser
Version:
Official Coralogix SDK for browsers
887 lines (683 loc) • 26.6 kB
Markdown
<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)
- [Only Sessions with Errors](#3-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)
- [Performance](#performance)
- [Worker URL](#worker-url)
- [Screenshots](#screenshots)
10. [Network Extra Configuration](#network-extra-configuration)
11. [Multi Page Application](#multi-page-application)
12. [Ignore Errors](#ignore-errors)
13. [Ignore URLs](#ignore-urls)
14. [Mask Elements](#mask-elements)
15. [Label Providers](#label-providers)
16. [URL Blueprinters](#url-blueprinters)
17. [Traces](#traces)
- [Propagate Trace Header for CORS URLs](#propagatetraceheadercorsurls)
- [Allowed Tracing URLs](#allowedtracingurls)
- [Extra Propagators (B3 / AWS X-Ray)](#b3--aws-x-ray-propagation)
18. [Before Send](#before-send)
19. [Proxy URL](#proxy-url)
20. [Collect IP Data](#collect-ip-data)
21. [Custom Measurement](#custom-measurement)
22. [Add Timing](#add-timing)
23. [Custom Time Measurement](#custom-time-measurement)
24. [Microfrontend Support](#microfrontend-support)
- [Pre Requisites](#pre-requisites)
25. [Custom Spans](#custom-spans)
- [Ignored Instruments](#ignored-instruments)
26. [Soft Navigations (Experimental)](#soft-navigations--experimental)
27. [Memory Usage (Experimental)](#memory-usage---experimental)
28. [CDN](#cdn)
- [Specific Version](#specific-version-recommended)
- [Latest Version](#latest-version)
- [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)
29. [Flutter Web](#flutter-web)
---
</details>
# Official Coralogix SDK for Browsers
[](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. 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';
CoralogixRum.log(CoralogixLogSeverity.Info, 'this is a custom log');
CoralogixRum.log(CoralogixLogSeverity.Error, 'this is an error custom log with extra data', { data: 'tbd' });
CoralogixRum.error('this is a custom log with error severity', { data: 'tbd' });
```
### 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,
},
});
```
### 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.
},
});
```
#### 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. |
#### Performance
Session Recording works by recording incremental DOM changes that occur in your web application.
To avoid performance issues, Session Recording will stop recording if it detects a large number of mutations (Default: 5,000).
```javascript
CoralogixRum.init({
// ...
sessionRecordingConfig: {
// ...
// According to MutationObserver API, A large number of DOM mutations can negatively impact performance
maxMutations: 5000,
},
});
```
#### 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;
},
});
```
### 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
});
```
### 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', 'email', 'tel']`
<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>
```
### 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,
},
},
});
```
### 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',
});
```
### 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,
});
```
### 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) and include them in your build process.<br>
Plugins for other bundlers are coming soon.
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' });
globalSpan.withContext(() => {
const customSpan = globalSpan.startCustomSpan('custom-span', { action: 'scroll' });
customSpan.endSpan();
});
// 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
```
### 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();
```
## CDN
Coralogix Browser SDK is also provided via CDN.<br>
You can choose your desired version.
#### Specific Version (recommended)
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).
#### Latest Version
> _**Note: CDN latest has been deprecated, please use an explicit version instead.**_
https://cdn.rum-ingress-coralogix.com/coralogix/browser/latest/coralogix-browser-sdk.js
### Add the CDN script to your application
```javascript
<head>
...
<script src="https://cdn.rum-ingress-coralogix.com/coralogix/browser/1.5.0/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/latest/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',
})]);
}
```