Frontend (RUM)
Korai’s browser SDK has two parts, configured separately:
- RUM (
@koraitech/browser-rum) keeps whole sessions: page views, Core Web Vitals, resources, actions and, when recorded, the replay. It feeds User experience. - Browser Logs (
@koraitech/browser-logs) keeps logs and errors, one by one, whether or not RUM kept the session.
That split is what lets you keep, for example, 1 % of sessions in production and still receive 100 % of the errors. This page shows how, and how to send enough context with each error to investigate it without a session.
1. Install
Section titled “1. Install”In Observability › Connect, the Frontend (RUM) card shows your tenant’s values (site,
organizationIdentifier, the clientToken) and a ready snippet for npm or a <script> tag. It turns green with the
first page view. Initialise both SDKs as early as possible in your app:
import { koraiRum } from '@koraitech/browser-rum'import { koraiLogs } from '@koraitech/browser-logs'
const common = { clientToken: '<RUM_CLIENT_TOKEN>', site: '<your site>', organizationIdentifier: '<your organization>', apiVersion: 'v1', service: 'web', env: config.env, // the real environment of this deployment version: config.version, // the tag, commit or version of this build}
koraiRum.init({ ...common, applicationId: 'web', sessionSampleRate: Number(config.sessionSampleRate ?? 100), sessionReplaySampleRate: Number(config.sessionReplaySampleRate ?? 0), traceSampleRate: Number(config.traceSampleRate ?? 100), trackResources: true, trackLongTasks: true, trackUserInteractions: true, defaultPrivacyLevel: 'mask-user-input',})
koraiLogs.init({ ...common, forwardErrorsToLogs: true, // uncaught errors and unhandled rejections sessionSampleRate: 100, // the logs' own rate: keep it at 100})Both are also published as window.KORAI_RUM and window.KORAI_LOGS, which is what the <script> tag uses.
service, env and version must be real. They are how you filter and compare releases, so fill them from the
same configuration your app already publishes for each deployment rather than hard-coding them. A staging build that
sends env: 'production' mixes with production. Use the same service name as the backend service it calls, so
Korai joins both pages.
2. Sampling per environment
Section titled “2. Sampling per environment”Rates are percentages from 0 to 100:
| Option | What it decides | Staging (example) | Production (example) |
|---|---|---|---|
sessionSampleRate in RUM |
the share of sessions RUM keeps | 100 | 1 |
sessionReplaySampleRate |
of the kept sessions, the share also recorded | 100 | 0 to 20 |
traceSampleRate |
of the kept sessions, the share whose requests start a sampled trace | 100 | 100 |
sessionSampleRate in Logs |
the share of sessions whose logs and errors are sent | 100 | 100 |
The replay and trace rates apply on top of the session rate: with 1 % of sessions and 20 % of replays, about 0.2 % of all sessions are recorded. 1 % is a starting point; raise it if you need more journeys to look at.
Publish the rates from the same per-environment configuration as env and version. The Logs SDK has its own
sessionSampleRate (100 by default): do not copy the RUM rate into it, or you lose errors.
What changes in Korai. User experience counts what the kept sessions saw: page views, Web Vitals and JavaScript errors are those of the sample, not scaled up. The full count of browser errors is in Browser Logs (next section).
3. Every error, with or without a session
Section titled “3. Every error, with or without a session”With forwardErrorsToLogs: true, every uncaught JavaScript error and unhandled promise rejection reaches Browser
Logs, in every session. What you get depends on whether RUM kept the session:
| RUM kept the session | RUM did not keep it | |
|---|---|---|
| The error | yes | yes |
| The session, page views and actions before it | yes | no |
| The replay | if it was recorded | no |
session_id on the log |
added by the SDK | no |
An error without a session is still useful if it carries its context: what failed, on which route, in
which version, which backend request it relates to and whether the app handled it. service, env,
version and the page (view) are added on their own; the rest comes from the next sections.
Do not add your own window.onerror while forwardErrorsToLogs is on: you would receive each error twice.
Errors your app catches. A try/catch that handles an error stops it reaching forwardErrorsToLogs. Log it where
you already handle it, with the error as the third argument (that is what fills the error’s type, message and
stack):
try { await submitPayment()} catch (error) { window.KORAI_LOGS?.logger.error('payment_submission_failed', { error_code: 'PAYMENT_SUBMISSION_FAILED', route_name: 'payments.submit', handled: true, }, error) // ...the handling your app already does}Use stable, repeatable values (error_code, route_name): they group and filter; a full message or a URL with ids
does not.
4. HTTP errors in one place
Section titled “4. HTTP errors in one place”Log failed requests in your common HTTP client or interceptor, not on every screen: the method, the route, the
status, the duration and the request id once, for every call. A fetch wrapper, for example:
async function request(method, url, options = {}) { const path = new URL(url, window.location.origin).pathname const started = performance.now() let response try { response = await fetch(url, { ...options, method }) } catch (error) { window.KORAI_LOGS?.logger.error('http_network_error', { error_code: 'HTTP_NETWORK_ERROR', http_method: method, url_path: path, handled: true, }, error) throw error } if (!response.ok) { window.KORAI_LOGS?.logger.error('http_request_failed', { error_code: 'HTTP_REQUEST_FAILED', http_method: method, http_status_code: response.status, url_path: path, duration_ms: Math.round(performance.now() - started), request_id: response.headers.get('x-request-id'), handled: true, }) } return response}url_path(pathname) leaves out the query string, which can carry variable or personal data.request_idis there when your backend returns it. For a cross-origin API, the backend must also sendAccess-Control-Expose-Headers: x-request-id, or the browser hides the header from your code.- If the request is logged here, the screen’s
catchdoes not need to log it again.
5. The route as a dimension
Section titled “5. The route as a dimension”To filter by route, the route’s name or template is more useful than the literal URL: /users/15/panel and
/users/82/panel are one route, users/{user}/panel. Set it as global context on both SDKs, so it reaches the
RUM events and the error logs (also those without a session):
function setRoute(name, template) { for (const sdk of [window.KORAI_RUM, window.KORAI_LOGS]) { sdk?.setGlobalContextProperty('route_name', name || 'unmatched') sdk?.setGlobalContextProperty('route_template', template || 'unmatched') }}Call it after init and, in a single-page app, on every route change, with the name your router gives it. With
server-rendered pages, publish the route from the template. In Laravel, for example:
<script> window.APP_ROUTE = { name: @json(request()->route()?->getName()), template: @json(request()->route()?->uri()), }</script>and then setRoute(window.APP_ROUTE.name, window.APP_ROUTE.template). On a page with hash navigation
(/app#/overview), you can add the visible route too:
const hashRoute = window.location.hash.replace(/^#/, '').split('?')[0]window.KORAI_RUM?.setGlobalContextProperty('view_route', hashRoute || window.location.pathname)6. Your own dimensions
Section titled “6. Your own dimensions”The same global context takes any field your team filters by. Good dimensions answer one concrete question and have
a small, repeatable set of values: app_area (casino, payments, account), auth_state
(authenticated, anonymous), release_channel (stable, canary), payment_provider (provider_a). Avoid
ids, emails, full messages and URLs with parameters: they do not group, and some are personal data.
function addDimension(name, value) { if (value === undefined || value === null || value === '') return window.KORAI_RUM?.setGlobalContextProperty(name, value) window.KORAI_LOGS?.setGlobalContextProperty(name, value)}
addDimension('app_area', config.appArea)addDimension('auth_state', user ? 'authenticated' : 'anonymous')For a value computed per event, use beforeSend in koraiRum.init. For example, a simple category on errors:
function errorCategory(event) { const status = event.error?.resource?.status_code if (status >= 500) return 'http_5xx' if (status >= 400) return 'http_4xx' if (event.error?.source === 'network') return 'network' return 'javascript'}
koraiRum.init({ // ...the options above beforeSend(event) { if (event.type === 'error') { event.context = { ...event.context, error_category: errorCategory(event) } } return true },})The categories are an example: use the taxonomy your app already has.
7. Traces from the browser
Section titled “7. Traces from the browser”RUM can add a W3C traceparent header to the requests your app makes to your own APIs, so each browser request
opens its backend trace:
koraiRum.init({ // ...the options above traceSampleRate: 100, traceContextInjection: 'all', allowedTracingUrls: [ { match: window.location.origin, propagatorTypes: ['tracecontext'] }, { match: 'https://api.your-domain.com', propagatorTypes: ['tracecontext'] }, ],})A cross-origin API must accept the headers in its CORS configuration:
Access-Control-Allow-Headers: traceparent,tracestate,content-typeWith traceContextInjection: 'all' the backend receives the browser’s decision both ways. A ParentBased sampler
in the backend keeps it:
traceparent sampled=1 -> continues and exports the tracetraceparent sampled=0 -> keeps the decision not to sampleno traceparent -> applies the backend's own samplingOnly in kept sessions. The SDK adds traceparent only in the sessions RUM keeps. With 1 % of sessions, the other
99 % of requests reach the backend without it and the backend’s own sampling decides. To link an error from one of
those sessions to its backend logs and trace, have the backend return its request or trace id in a response header
(for example x-request-id, exposed with Access-Control-Expose-Headers) and log it as in section 4:
browser error -> request_id -> backend log -> traceCheck it. Open a resource of a kept session and its backend span: the RUM trace_id equals the backend’s, and
the RUM span_id is the backend span’s parent_span_id.
Both ways in Korai. In User experience › Resources (or a session’s timeline), Backend trace opens the trace of a request. From the other side, a trace that started in a browser shows Started in the browser above its waterfall: the page, the click before the request, browser, device and user, and Session and replay to watch what the person did.
8. Where it lands and how to query it
Section titled “8. Where it lands and how to query it”RUM events go to the _rumdata stream, browser logs to _rumlog and replays to _sessionreplay. Nested fields are
flattened with _, so RUM context keeps the context_ prefix:
| You send | RUM column (_rumdata) |
|---|---|
env, version, service |
env, version, service |
route_name, route_template, view_route |
context_route_name, context_route_template, context_view_route |
app_area, auth_state, release_channel |
context_app_area, context_auth_state, context_release_channel |
error_category (from beforeSend) |
context_error_category |
The SDK also reports the configured rates (_o2_configuration_session_sample_rate and similar). A route template
keeps its braces (users/{user}/panel). resource_url keeps the full URL of a resource, with its query string; the
normalised route is in context_route_template.
In browser logs, the fields you pass to logger.error and the global context keep their own names (error_code,
route_name, request_id). When RUM kept the session, the session’s timeline in User experience shows its logs.
In Explore › Logs, pick the stream and switch to SQL. Errors by route and category:
SELECT context_route_name, context_error_category, COUNT(*) AS occurrencesFROM "_rumdata"WHERE type = 'error'GROUP BY context_route_name, context_error_categoryORDER BY occurrences DESCEvery browser error, kept session or not, by route and version:
SELECT route_name, version, error_code, COUNT(*) AS occurrencesFROM "_rumlog"WHERE status = 'error'GROUP BY route_name, version, error_codeORDER BY occurrences DESCVolume per environment, to check the sampling:
SELECT env, COUNT(*) AS events, COUNT(DISTINCT session_id) AS sessionsFROM "_rumdata"GROUP BY envORDER BY events DESCChecklist
Section titled “Checklist”service,envandversioncome from each deployment’s real configuration.- RUM
sessionSampleRateper environment (for example 100 in staging, 1 in production); LogssessionSampleRateat 100. forwardErrorsToLogs: true, and no extrawindow.onerror.- Caught errors logged with
logger.error(message, context, error)where they are handled. - Failed requests logged once, in the common HTTP client, with
url_pathandrequest_id. route_nameandroute_templateas global context on both SDKs.allowedTracingUrls, CORS fortraceparentandtracestate, and a ParentBased sampler in the backend.
See also W3C Trace Context.