@coralogix/browser
v1.2.14
Published
Official Coralogix SDK for browsers
Downloads
46,313
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',
});
CoralogixRum.log(CoralogixLogSeverity.Error, 'this is a log', { key: 'value' });
CoralogixRum.error('this is a log with error severity', { key: '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.
CoralogixRum.init({
// ...
instrumentations: {
xhr: true,
fetch: true,
web_vitals: false,
interactions: false,
custom: true,
errors: true,
long_tasks: true,
resources: false,
},
});
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,
},
});
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,
},
});
Session 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,
//...
},
},
},
});
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 with specific elements 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 element, string or RegExp. default is cx-mask
.
CoralogixRum.init({
// ...
maskInputTypes: ['password', 'date'], // will only mask password and date inputs
maskClass: 'mask-me', // will mask any element with class 'mask-me'
});
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"
},
});
TraceParentInHeader
Add trace context propagation in headers across service boundaries
CoralogixRum.init({
// ...
traceParentInHeader: {
enabled: true,
options: {
// When the backend domain is different from the app domain, specifying backend domains is necessary.
propagateTraceHeaderCorsUrls: [new RegExp('https://webapi.*')],
/* B3 propagation
propagateB3TraceHeader: {
singleHeader: true,
multiHeader: true,
}, */
/* 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,
});
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',
})]);
}