@coralogix/browser
v1.2.42
Published
Official Coralogix SDK for browsers
Downloads
70,523
Readme
Official Coralogix SDK for Browsers
Links
Supported Frameworks
JavaScript / TypeScript Frameworks: React, Angular, Vue, NextJS and more. 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.
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()
.
import { CoralogixRum } from '@coralogix/browser';
// Update user context dynamically
CoralogixRum.setUserContext({
user_id: '123',
user_name: 'name',
user_email: '[email protected]',
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
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.
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.
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
import { CoralogixRum } from '@coralogix/browser';
import { CoralogixLogSeverity } from '@coralogix/browser/src/types-external';
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.
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 get it captured as an event.
try {
// Some code that might throw an error
} catch (error) {
CoralogixRum.captureError(error);
}
Session Recording
Session Recording enhances your user experience monitoring by enabling you to record and visually replay the web browsing activities of your users.
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:
// 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:
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:
<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).
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
For a locally hosted worker file:
CoralogixRum.init({
// ...
sessionRecordingConfig: {
// ...
workerUrl: "/assets/worker.min.js"
},
});
For an externally hosted worker file:
CoralogixRum.init({
// ...
sessionRecordingConfig: {
// ...
workerUrl: "https://cdn.rum-ingress-coralogix.com/coralogix/browser/latest/worker.min.js"
},
});
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.
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.
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.
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.
use maskInputTypes
to specify the types of inputs to mask. defaults to: ['password', 'email', 'tel']
use maskClass
to specify the class name that will be used to mask any clickable element. Default masking class is cx-mask
.
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:
<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
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.
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
CoralogixRum.init({
// ...
traceParentInHeader: {
enabled: true,
},
});
propagateTraceHeaderCorsUrls
When the backend domain is different from the app domain, specifying backend domains is necessary.
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.
CoralogixRum.init({
// ...
traceParentInHeader: {
enabled: true,
options: {
propagateTraceHeaderCorsUrls: [new RegExp('https://webapi.*')],
},
},
});
allowedTracingUrls
Specify the allowed URLs to propagate the trace header.
Note that if allowedTracingUrls is not specified, the trace header will be propagated to all URLs.
allowedTracingUrls works only on 1st party URLs. (see propagateTraceHeaderCorsUrls for 3d party URLs)
For example if you want to propagate the trace header only for URLs that contain the word alpha
:
CoralogixRum.init({
// ...
traceParentInHeader: {
enabled: true,
options: {
allowedTracingUrls: [new RegExp('alpha')],
},
},
});
Extra Propagators
B3 / AWS X-Ray Propagation
CoralogixRum.init({
// ...
traceParentInHeader: {
enabled: true,
options: {
// ...
/* for B3 propagation */
propagateB3TraceHeader: {
singleHeader: true,
multiHeader: true,
},
/* for Aws propagation */
propagateAwsXrayTraceHeader: true,
},
},
});
beforeSend
Enable event access and modification before sending to Coralogix, supporting content modification, and event discarding.
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).
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.
CoralogixRum.init({
// ...
collectIPData: true,
});
Custom Measurement
Custom measurement allows you to send numeric data to Coralogix for precise monitoring and analysis.
CoralogixRum.sendCustomMeasurement('my-page-load', 1000);
Add Timing
Add timing is a simple API to add extra performance timing to your RUM data. The timing relates to the time between the page load and the moment the timing is added. For example, you can add a timing for the first click event.
window.addEventListener('click', function handler(){
window.removeEventListener('click', handler);
CoralogixRum.addTiming('first-click');
});
OR
You can provide your own timing.
window.addEventListener('click', function handler(){
window.removeEventListener('click', handler);
CoralogixRum.addTiming('first-click', 1000);
});
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).
** This feature requires enabling the feature flag(#enable-experimental-web-platform-features) in the browser. **
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 API. The SDK will collect memory usage data every interval and send it to Coralogix. To enable the feature, your website needs to be in a secure context.
CoralogixRum.init({
// ...
memoryUsageConfig:{
enabled:true,
interval: 300_000 // Defaults to 5 minutes
}
});
You can also manually trigger memory usage data collection.
CoralogixRum.measureUserAgentSpecificMemory();
CDN
Coralogix Browser SDK is also provided via CDN. You can choose a specific version or use the latest one.
Specific Version (recommended)
https://cdn.rum-ingress-coralogix.com/coralogix/browser/[version]/coralogix-browser-sdk.js
Replace [version] with a version from Releases page.
Latest Version
https://cdn.rum-ingress-coralogix.com/coralogix/browser/latest/coralogix-browser-sdk.js
Add the CDN script to your application
<head>
...
<script src="https://cdn.rum-ingress-coralogix.com/coralogix/browser/1.0.101/coralogix-browser-sdk.js"></script>
</head>
Initialization
Via JS file
window.CoralogixRum.init(...);
Via TS file
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:
<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:
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',
})]);
}