Web SDK
@cohorly/web is the browser SDK. It is built on the shared core with localStorage persistence, a fetch/sendBeacon transport (so events survive tab close and navigation), and optional SPA pageview autotracking.
Install
bashpnpm add @cohorly/web# or: npm install @cohorly/web
Initialize
Call init() once at your app entry point. Pass your project token so
events route to the right project; apiHost defaults to the hosted Cohorly
API.
tsimport { init } from "@cohorly/web";const cohorly = init({token: "YOUR_PROJECT_TOKEN",trackPageviews: true,});
After init() has run once, you can import the named cohorly singleton
anywhere instead of threading the returned instance through your app:
tsimport { cohorly } from "@cohorly/web";cohorly.track("Button Clicked", { button: "checkout" });
Options
| Option | Type | Notes |
|---|---|---|
apiHost | string | Optional. Ingestion API base URL. Defaults to the hosted Cohorly endpoint. |
sanitizeUrl | function | (url) => string. Rewrites every URL the SDK sends, on events and in session replay (for example ids in paths). See URLs with personal data. |
token | string | Project token stamped on every event and request. |
trackPageviews | boolean | Autotrack SPA pageviews. |
flushIntervalMs | number | How often the queue auto-flushes. |
batchSize | number | Flush once this many events are queued. |
superProperties | object | Properties merged into every event from the start. |
debug | boolean | Verbose logging. |
loadFeatureFlags | boolean | Evaluate feature flags on init. Default true. |
sendExposureEvents | boolean | Track $feature_flag_called on flag reads. Default true. |
flagPersistence | string | "networkOnly", "networkFirst", or "persistenceUntilNetworkSuccess" (default). See Feature flags. |
flagCacheTtlMs | number | How long the persisted flag cache stays valid, checked when the cache is adopted - adopted values keep serving until the next reload or identity change. Default 86400000 (24 h). |
captureExceptions | boolean | true captures unhandled errors and promise rejections automatically. Omitted: only captureException() sends. false: no $exception is sent at all, manual calls included. See Error tracking. |
release | string | The release this build is. Sent as $exception_release on exceptions and as $app_version_string on every event. |
dist | string | Distribution inside the release (e.g. a build hash), sent as $exception_dist. |
beforeSendException | function | Scrub or drop an exception before it is queued. |
maxExceptionQueueSize | number | Capacity of the exception queue. Default 50. |
metrics | object | { flagKey?: string }. The feature flag that works as the kill switch for custom metrics. Default "cohorly_metrics". |
sessionReplay | object | { sampleRate?, onErrorSampleRate?, remoteConfig?, maskTextSelector?, maskAttributes?, blockSelector?, allowedIframeOrigins?, canvas?, console?, network? }. Records sessions with rrweb. See Session replay. |
persistence | string | "localStorage+cookie" (default), "cookie" or "localStorage". Where the identity is kept. See Identity persistence. |
crossSubdomainCookie | boolean | Share the identity cookie across subdomains. Default true. |
cookieDomain | string | Explicit cookie domain, e.g. ".example.com". Wins over crossSubdomainCookie. |
cookieName | string | Override the identity cookie name. By default each project token gets an isolated cookie (cohorly_id_<hash>), or cohorly_id when no client token is passed. |
secureCookie | boolean | Secure attribute of the identity cookie. Default: on for https pages. |
cookieExpirationDays | number | Identity cookie lifetime. Default 365. |
initialDeviceId | string | Device id to start from when the browser has no identity yet, e.g. read on the server with readCohorlyDeviceId(). Never replaces an existing identity. |
syncDeviceCookie | boolean | Keep the @cohorly/nextjs proxy's device cookie in step on reset() and optOutTracking(). Default false. |
Track events
track(event, properties?) queues an event. The SDK automatically merges in
$browser, $os, $current_url, and screen size, plus distinct_id,
time, $insert_id, and $lib.
tscohorly.track("Signed Up", { plan: "pro" });cohorly.track("Item Added", { sku: "A-100", price: 29 });
Identify
identify(id) switches the current user to a known id. The switch (distinct
id, persisted state) is applied synchronously, before any network call, so a
slow or offline request never delays it. On the first call after being
anonymous it then sends an /alias request so pre-login and post-login
activity link into one profile; the request is best effort - a failure
neither throws nor blocks, since the server also links the anonymous and
identified ids implicitly from the next event that carries both (see
Identity).
tsawait cohorly.identify("user_123");
Use reset() on logout to generate a fresh anonymous id. This matters on
shared devices: without it, the next person to use the device inherits the
previous person's anonymous history.
tscohorly.reset();
Identity persistence
By default (persistence: "localStorage+cookie") the identity lives in
localStorage and in one first-party cookie (named cohorly_id_<hash> per
project token, or cohorly_id when no client token is passed or overridden
with cookieName), set on the widest domain the browser accepts
(.example.com), so shop.example.com and pay.example.com share one
distinct_id and one $device_id without leaking between unrelated projects.
The cookie holds only identity metadata (cohorly_distinct_id,
cohorly_device_id, cohorly_anonymous, cohorly_opt_out,
cohorly_identified_at, cohorly_reset_at and cohorly_first_touch).
Queues, flags, super properties and timed events stay in localStorage. If
the cookie would pass 2048 bytes, the first touch is left out of it; the
identity keys always fit.
- An install that only had localStorage keeps its exact ids and gains the cookie.
- A browser arriving on another subdomain with only the cookie adopts it into localStorage.
- When both exist and disagree: an identified side always beats an anonymous
one, except when the anonymous side carries a newer
cohorly_reset_atthan the identified side'scohorly_identified_at(soreset()on one subdomain logs out stale identified sessions on sibling subdomains instead of restoring the previous user); when both are identified, localStorage wins (the session on this page is never replaced); when both are anonymous, the cookie wins (subdomains converge). The result is written back to both. Opt-out on either side applies to both.
persistence: "cookie" keeps the identity in the cookie only.
persistence: "localStorage" never reads or writes a cookie (the behaviour
before 0.8), while still honoring initialDeviceId if no local storage exists.
The cookie is host-only on local loopback hosts, IP addresses and single-label hosts,
and when crossSubdomainCookie is false.
tscohorly.getDeviceId(); // the $device_id on every event
Safari's ITP can erase storage written by script after 7 days without a
visit. To survive that, enable the deviceCookie option of the
Next.js proxy: an HttpOnly cookie set by your
server keeps the device id, and with syncDeviceCookie: true the SDK tells
the proxy when reset() or optOutTracking() changes it.
Super properties
Super properties are merged into every subsequent event. Register and
unregister them with register() / unregister(). Event-level properties
override super properties of the same key.
tscohorly.register({ app_version: "1.2.3", plan: "free" });cohorly.track("Viewed Page"); // includes app_version and plancohorly.unregister("plan");
People profiles
Update the current user's profile through cohorly.people. These map to the
/engage endpoint.
tsawait cohorly.people.set({ name: "Ada Lovelace", plan: "pro" });await cohorly.people.setOnce({ first_seen: Date.now() });await cohorly.people.increment({ logins: 1 });await cohorly.people.unset(["temp_flag"]);await cohorly.people.delete();
Feature flags
Flags are evaluated on init by default and cached per identity (localStorage,
scoped by distinct_id, bounded by flagCacheTtlMs). The cache serves
immediately on the next launch until the first successful reload replaces it;
flagPersistence controls that policy - under the default
"persistenceUntilNetworkSuccess" an expired cache still serves up to 7
days stale, while "networkFirst" serves only inside the TTL.
tsconst value = cohorly.getFeatureFlag("checkout-redesign", "control");const enabled = cohorly.isFeatureEnabled("checkout-redesign", false);const details = cohorly.getFeatureFlagDetails("checkout-redesign");// details.source: "network" | "persistence" | "fallback"
A read that resolves to the fallback is a default, not an exposure. See Feature flags for the persistence policies, TTL, and source semantics.
Custom metrics
cohorly.metrics.count, gauge and distribution have the same signature and
send the same $metric events as @cohorly/core (see
Core SDK): one event per series (metric name,
type, unit and tags) per 60 second window, never one per sample.
tsimport { cohorly } from "@cohorly/web";cohorly.metrics.count("checkout_started", 1, { plan: "pro" });cohorly.metrics.gauge("queue_length", queue.length);cohorly.metrics.distribution("js_cost.service.max_ms", elapsedMs, { service: "cart" });cohorly.metrics.distribution("render_ms", elapsedMs, { tags: { page: "home" }, unit: "ms" });
Unlike the rest of cohorly, metrics does nothing before init() and never
throws, so a library can record without knowing whether the host app has
initialized the SDK. Pass init({ metrics: { flagKey } }) to read the kill
switch from another flag.
- Kill switch. Deactivate the feature flag
cohorly_metrics(or set its rollout to 0%) and the client stops recording and drops the window in progress. A missing flag means on. - Page hide. The window in progress is queued and persisted on
pagehideand when the page becomes hidden, and sent withnavigator.sendBeaconwhen the browser and the queue allow it (one batch, under the beacon size limit, and no other flush running). Whatever stays behind is sent on the next visit.optOutTracking()discards the window. - Flags not loaded yet. While the first flag evaluation is running and no
flags are loaded,
$metricevents stay in the queue and are not sent. A disabled kill switch flag then drops them; otherwise they are sent. An evaluation that fails, orloadFeatureFlags: false, holds nothing back.
Error tracking
Errors are ordinary events named $exception, so they can be broken down,
filtered and put into funnels like any other event. Capture one yourself with
captureException(error, options?):
tstry {await submitOrder(cart);} catch (error) {cohorly.captureException(error, {level: "error", // "fatal" | "error" (default) | "warning" | "info"title: "Checkout submit failed", // display title, also prefixes the fingerprinttags: { step: "payment" }, // top-level propertiesextra: { cartSize: cart.items.length },});}
The event carries the error and its cause chain (outermost first, at most
5) with the stack parsed into frames, the current breadcrumbs, the release,
and the same default properties as track(). tags and extra become
top-level properties (tags wins) but can never overwrite a reserved key
($exception_*, error_title, distinct_id, time, $insert_id, $lib,
token, $device_id, $user_id). Anything that is not an Error (a string,
a plain object) is sent as a synthetic exception. Pass fingerprint to group
exceptions yourself; the server still derives the final fingerprint from it.
Automatic capture
With captureExceptions: true the SDK also listens for uncaught errors and
unhandled promise rejections, both with mechanism.handled: false. An
uncaught error is sent with level: "fatal" (it counts against crash-free
users); an unhandled rejection with level: "error"; handlers already on the page keep running. A
rejection with a value that is not an Error is reported as
UnhandledRejection.
It also records breadcrumbs automatically:
| Category | What | Never |
|---|---|---|
navigation | "/cart -> /checkout" on SPA route changes | query string, fragment |
ui.click | A short selector, e.g. button#pay | element text, input values |
console | console.error arguments | |
fetch | "POST /api/cart 500" for failed or rejected requests | query, headers, bodies, the SDK's own requests |
xhr | "POST /api/cart 500" for XMLHttpRequests that end with status 400 or more, a network error or a timeout (failed); never an abort | query, headers, bodies, the SDK's own requests |
The same error is sent at most 10 times per minute (same type, message and crashing frame); a render loop cannot flood the queue.
An error that a global handler and captureException() both report within one
second (same type, message and crashing frame) is sent once. React 18 does this
in development: it re-reports a render error its boundary caught to window.
The event that stays is the one from the global handler (level fatal).
Breadcrumbs
Add your own with addBreadcrumb(). The last 50 travel with every exception.
They are kept in memory only, and reset() clears them.
tscohorly.addBreadcrumb({category: "checkout",message: "Applied coupon",level: "info",data: { coupon: "WELCOME10" },});
Scrubbing with beforeSendException
beforeSendException sees every exception right before it is queued. Return
the event, changed if needed, or null to drop it. If the hook throws, the
exception is dropped - it is never sent unscrubbed.
tsimport { init, type ExceptionListEntry } from "@cohorly/web";init({token: "YOUR_PROJECT_TOKEN",captureExceptions: true,beforeSendException(event) {const props = event.properties;if (typeof props.$current_url === "string") {props.$current_url = props.$current_url.split("?")[0];}const exceptions = props.$exception_list as ExceptionListEntry[];if (exceptions[0]?.type === "AbortError") return null; // dropfor (const exception of exceptions) {exception.value = exception.value.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, "[email]");}return event;},});
Delivery
Exceptions have their own queue (50 by default, persisted), so a burst of
ordinary events can never push one out. Every flush sends exceptions first,
fatal ones before the rest, then events; when the queue is full the oldest
non-fatal exception is dropped first. When the page is hidden or closed,
fatal exceptions go out first through sendBeacon. Retries follow the same
rules as events.
Releases
Set release to the version you deploy, from the same source as your build
(e.g. "web@2026.11.3" or a git tag). It is sent as $exception_release on
every exception and as $app_version_string on every event, which is what
makes crash-free users by release possible: the numerator (users with a fatal
exception in the release) and the denominator (users active in the release)
read the same string. Use dist for the build hash inside a release.
Session replay
Session replay records what happened on the page (DOM, inputs masked, clicks, scrolls, network requests) with rrweb, so you can watch a session from the user's profile or from an error issue.
tsinit({token: "<project token>",captureExceptions: true,sessionReplay: {sampleRate: 0.1, // record 10% of sessions wholeonErrorSampleRate: 1, // of the rest, keep the last 30 to 60 s and send them on an errormaskTextSelector: ".pii", // optional, added to [data-cohorly-mask]blockSelector: ".ads", // optional, added to [data-cohorly-block]console: true, // default; false records no console lines},});
The recorder (and rrweb) is downloaded only when the current session records
or buffers. A page without sessionReplay, with both rates at 0, opted out
at init(), or whose session was sampled out never loads it.
Sessions
With sessionReplay set (and a rate above 0), every event, $exception
included, carries $session_id. A session belongs to one browser tab: a
reload continues it, and another tab, or a duplicated one, has its own. It
expires after 30 minutes without a tracked event or a recorded interaction
(the SDK's own $metric events do not count), or after 24 hours. Recording
stops while the session is expired, and the next interaction or tracked
event starts a new session from a full snapshot. reset() starts a new
session at once.
The sampling decision is made once per session. sampleRate picks sessions
recorded whole; among the others, onErrorSampleRate picks sessions that
only keep a short buffer for errors.
Settings from the dashboard
tsinit({token: "<project token>",sessionReplay: { sampleRate: 0, remoteConfig: true },});
With remoteConfig: true, the rates and the minimum duration saved in
Settings > Session replay apply without a new deploy. Each field the project
saved wins over the same field in your code; a field it never saved keeps
your code's value, and with no network and no cached copy your code's values
apply. Masking, blocking and iframe origins always come from your code. The
SDK keeps the settings for up to 1 hour per token, and a change applies to
new sessions only: a session in progress keeps its decision. A new session
gets its $session_id at once and waits at most 3 seconds for the settings
before it is sampled. With a minimum duration, a recorded session sends
nothing until it is that long; a shorter one is never sent and never counts
toward the quota (sessions recorded on error are always sent). Without
remoteConfig (the default), the SDK never reads these settings. The
@cohorly/nextjs proxy (createCohorlyProxy) forwards only POST
requests, so with apiHost pointing at it the SDK cannot read the settings
and uses your code's values.
The triggers saved there also apply with remoteConfig: true. In a session
that is not recorded, or only keeps a buffer for errors, a trigger starts the
recording when its event is tracked with properties that pass its filters,
when the page path matches its pattern (on load and on each client-side
navigation; the query and fragment never count), or when its flag loads on
(with the variant it names, if any). Each trigger draws its rate once per
session, hit or miss, and a page reload does not draw it again. A hit records
the rest of the session from a full snapshot; a session that was buffering
sends its buffer first. The minimum duration counts from the snapshot the hit
starts. Flag
triggers read the flags the SDK loaded without sending
$feature_flag_called, and never fire with loadFeatureFlags: false.
Session mode
Chunks go to POST /replay every 5 seconds or 1000 rrweb events, gzipped
where the browser supports CompressionStream. When the tab is hidden or
closing, queued chunks are sent with fetch(..., { keepalive: true }) as far
as the browser's 64 KB keepalive budget allows; the rest stays queued if the
page comes back. Chunks wait in memory only (at most 5 MB) and follow the same
retry rules as events. A 404 from /replay turns replay off for that page
load.
Error mode
Error mode keeps the last 30 to 60 seconds in memory and sends them only
when the SDK captures an $exception. It needs exception capture:
captureExceptions: true, or your own
captureException() calls. With captureExceptions: false no exception is sent, so error mode never sends anything.
The recording sent with an error starts at a full snapshot, covers at least 30 seconds when the session is that old, never includes anything older than 60 seconds, and ends with the event that led to the error. Buffering then continues, so a later error sends again (at most one send every 5 seconds).
Quota
When the project is over its monthly replay quota, the server answers 429
replay quota exceeded. Session mode then stops until the Retry-After
time, remembered across reloads and tabs, and those sessions fall back to
the error buffer. Error-mode recordings are never refused by the quota.
Privacy
These defaults cannot be turned off:
- Every input value is masked: every input type,
hiddenandpasswordincluded, plus textarea and select. - Text inside
[data-cohorly-mask](plus yourmaskTextSelector) is masked. - Inside those same elements, attributes that carry text are masked too, on
the element and everything in it:
data-*,title,alt,aria-label,aria-description,placeholderandvalue, plus the names you add withmaskAttributes. Each character becomes*, so the length (and a CSScontent: attr(data-text)) stays the same. Links and images there (href,src,srcset,background,<object data>and everyurl(...)instyleor in a<style>there) lose their query and fragment; amailto:ortel:link keeps onlymailto:/tel:.class,idand the rest ofstylenever change, so the layout replays as it was. [data-cohorly-block]elements (plus yourblockSelector) are never recorded; the replay shows a placeholder of the same size.- The page URL is recorded without its query string or fragment.
- Network requests (
fetchandXMLHttpRequest,httpandhttpsonly) are recorded as method, URL without query or fragment, status (0 for a network error) and duration, never the SDK's own requests. Headers and bodies are recorded only when you turn them on for chosen URLs (below).
Where to use what:
| You want to | Use |
|---|---|
| Hide text and its attributes, keep the layout | data-cohorly-mask on the element, or maskTextSelector: ".pii" |
| Mask one more attribute name inside masked elements | maskAttributes: ["data-tooltip", "aria-*"] (added to the defaults; a trailing * is a prefix) |
| Leave an element out of the recording entirely | data-cohorly-block, or blockSelector: ".kyc-document" |
| Remove ids or names from URLs (page, links, images, requests, events) | sanitizeUrl |
| Clean request and response headers and bodies | network.redact (it never sees the URL as something to change) |
URLs with personal data
Paths often carry ids or names: /admin/users/8f2c1e, /customers/maria-souza.
The query is already left out of replay URLs, but the path is not. Set
sanitizeUrl at the top level of init():
tsinit({token: "<project token>",sanitizeUrl: (url) => url.replace(/\/(users|avatars)\/[^/?#.]+/, "/$1/:id"),trackPageviews: true,sessionReplay: { sampleRate: 0.1 },});
It runs on every URL the SDK sends: $current_url on every event, the
pageview's URL, domain, path and search (taken from the rewritten URL),
$referrer and $initial_referrer and their domains (also a first touch
stored by an earlier version of the SDK), autocapture's $el_href, error
tracking breadcrumbs and the script URLs of stack frames, and in replays the
page URL, $network URLs (after the query is cut), the href, src,
srcset, background and <object data> of every element and every
url(...) in CSS (inline style and style sheets). data: and blob: URLs are never cut but still
go through your function (return "" to drop them); a plain local reference such
as <use href="#icon-user"> is left alone, but a hash route such as
#/users/8f2c is a URL like any other. If your function throws or
returns something that is not a string, the URL is sent empty, never as it
was. network.redact covers headers and bodies only: it does not change the
URL. In CSS only the url(...) changes (any case, escapes decoded, and
@import "..."); the rest of the style is recorded as written, text in
content: '...' and comments included. A bare string inside image-set()
is not rewritten.
Your function also receives the URLs of your scripts, from error stack
frames. Symbolication matches them to the source maps you uploaded, so
return them resolvable: rewrite only the id segment of a route
(/users/8f2c1e -> /users/:id), never the path of a .js file.
A complete example, a backoffice page at /admin/users/8f2c1e:
html<section data-cohorly-mask><h1 data-text="Maria Souza" title="Maria Souza">Maria Souza</h1><a href="mailto:maria@example.com">maria@example.com</a><img src="/avatars/8f2c1e.png?sig=abc" alt="Maria Souza" /></section><div data-cohorly-block>documents</div>
With the init() above, the replay shows the heading as ***** *****
(its data-text, title and the image's alt too), the link as mailto:,
the image as /avatars/:id.png, the page as /admin/users/:id, and no
documents at all; events carry /admin/users/:id.
Network headers and bodies
network records request and response headers and/or bodies, only for the
URLs you list in allowUrls. It is off by default.
tssessionReplay: {sampleRate: 0.1,network: {headers: true, // default falsebodies: true, // default falseallowUrls: ["https://api.example.com/", /\/graphql$/],redact: (entry) => {// Last say on each request: change it, or return null to keep no headers or bodies.if (entry.url.endsWith("/profile") && entry.response) entry.response.body = "[removed]";return entry;},},}
Turning this on is your responsibility. The SDK removes secrets and
scrubs what it records, but a body can still hold personal data it cannot
recognize (names, addresses, ids). Use allowUrls to keep the list short and
redact to remove the rest.
allowUrlsis tested against the absolute URL without query or fragment: a string matches as a prefix, aRegExpwithtest. WithoutallowUrls(or with an empty list) nothing more is recorded, anddebug: truelogs a warning. A request to another URL is marked as outsideallowUrls, so the player can tell it apart from an app without the option.- These headers are never recorded, in either direction:
authorization,proxy-authorization,cookie,set-cookie,x-api-key, and any header whose name containstoken,secret,password,authorsession. Other values are scrubbed (e-mails, bearer and JWT tokens, card numbers). - Text bodies (JSON,
text/*, form, XML) are kept up to 16 KiB; a longer one is cut and ends in[truncated]. In JSON, values under secret keys (password,apiKey,token, ...) become[token], and every body is scrubbed like the console. Other bodies become[binary N bytes],FormData[form-data], streams andtext/event-stream[stream]. - Your app's requests do not change: the same response, at the same moment,
with its body intact, and the same error. The SDK reads at most 16 KiB of
its own copy of a response, for at most 2 seconds (
[unavailable]after that). redact(entry)gets{ method, url, status, kind, request, response }after the steps above. If it throws, the request is recorded without headers or bodies.- On a cross-origin request the browser shows only the response headers the
server lists in
Access-Control-Expose-Headers(plus a few safe ones), so other response headers are missing from the recording.
Console
console.log, info, warn and error are recorded by default, as lines
the replay player shows in its Console tab. A line is the arguments joined by
a space, at most 2048 characters: an Error with its stack, objects as JSON
(4 levels deep, 50 keys each, cycles as [Circular]). Before it leaves the
browser, values under secret keys (password, apiKey, authorization,
...) become [token], and e-mails, bearer and JWT tokens, token=-style
secrets and card numbers become [email], [token] or [card].
At most 500 lines a minute are recorded per page; the recording shows how
many were dropped. The SDK's own [cohorly] ... messages are never
recorded, nor lines logged while no session is recording. Your console keeps
working as before: same arguments, same this, same return value.
To record no console lines:
tsinit({ token: "<project token>", sessionReplay: { sampleRate: 0.1, console: false } });
html<div data-cohorly-block>card form</div><p data-cohorly-mask>Signed in as jane@example.com</p>
optOutTracking() stops the recorder and drops everything buffered or
queued. When you proxy ingestion with createCohorlyProxy() from
@cohorly/nextjs, /replay is forwarded too.
Cross-origin iframes
A cross-origin <iframe> (a payment or booking widget on another domain)
shows up empty in a recording unless both pages run the SDK and allow each
other with allowedIframeOrigins. Each item is an exact origin, such as
https://pay.example.com: no *, no path, no trailing slash (anything else
is ignored, with a log when debug is on).
ts// https://shop.example.com (the page with the <iframe>)init({token: "<project token>",sessionReplay: { sampleRate: 0.1, allowedIframeOrigins: ["https://pay.example.com"] },});// https://pay.example.com (the page inside the <iframe>)init({token: "<project token>",sessionReplay: { allowedIframeOrigins: ["https://shop.example.com"], maskTextSelector: ".card-holder" },});
The iframe's content is then recorded in the parent page's session, in
place of the frame, and interacting inside it counts as activity of that
session, also after the session expired for inactivity (it starts a new one,
as an interaction on the parent page would). Inside the frame, its own
masking applies (the defaults plus the frame's maskTextSelector,
maskAttributes, sanitizeUrl and blockSelector). A data-cohorly-mask
(or your maskTextSelector) around the <iframe> on the parent page masks
the frame's text, inputs and attributes too, from the moment the container
is masked (what was recorded before stays as it was), also when the
<iframe> sits inside an open shadow root. A canvas inside the
frame is not masked. Outside such a container, what the frame records
reaches the replay exactly as the frame sent it: the parent's own
sanitizeUrl does not apply to it, the frame's does. An <iframe> the parent blocks (its blockSelector, on
the frame or an ancestor) is never recorded. While the parent records it,
the frame does not record a session of its own; when the parent stops, it
goes back to its own (if it records one, in a new session when the frame's
storage is blocked). The frame follows the parent's decision even with both
rates at 0, and a frame that calls init() after the parent started
recording is picked up right away.
Every message goes with postMessage to a listed origin only, never "*":
{ source: "cohorly-replay", v: 1, op }, with op "snapshot" or "stop"
from the parent and "ready" from the frame at each init(). The frame
answers only its own window.parent on a listed origin, and the parent
drops recording messages from origins it does not list. With the list on one
side only, nothing changes.
Not covered: frames whose origin does not run the SDK, more than one level of nesting, canvas inside the frame, and the cursor position inside the frame.
Canvas
canvas records the content of every <canvas>, 2D and WebGL, as WebP
images. It is off unless it is an object: canvas: {} turns it on with the
defaults.
tsinit({token: "<project token>",sessionReplay: { sampleRate: 0.1, canvas: { fps: 2, quality: 0.4 } },});
| Option | Default | Range |
|---|---|---|
fps | 2 | 1 to 12 frames per second per canvas. Values outside are set to the limit. |
quality | 0.4 | 0.1 to 1 (WebP quality). Values outside are set to the limit. |
A canvas that does not change costs one frame. An animated one costs CPU and
bytes: measured with an 800x600 canvas redrawn 20 times a second and fps: 2
(headless Chromium, 2026-11-18), about 118 frames and 1.9 MiB per minute sent
(gzip barely shrinks WebP in base64), +0.74 s of main-thread task time per
minute (1.2% of wall time) and +0.04 s at init, against the same page with
canvas off. At that rate the 64 MiB page ceiling takes about 21 minutes. A frame over 400,000 characters is dropped, and a page
load records at most 64 MiB of frames; past that, later frames are dropped (a
debug log says so) and the rest of the recording goes on.
A canvas is recorded as pixels, so masking does not apply to it: text drawn on
a canvas is recorded as it shows. Only blocking protects it. A canvas inside
[data-cohorly-block], or inside an element matching your blockSelector, is
never recorded and shows as a placeholder in the player.
Two things can leave a canvas empty. A page whose Content-Security-Policy has
no worker-src for blob: (and data:) cannot start rrweb's encoder, and
records no frames, without an error. A WebGL context created before recording
started keeps its own preserveDrawingBuffer (rrweb sets it to true on
contexts created afterwards, which can cost performance on the page).
Flush and accessors
tsawait cohorly.flush(); // send the queued batch nowconst id = cohorly.getDistinctId();const device = cohorly.getDeviceId();const anon = cohorly.isAnonymous();
The queue is persisted to localStorage, so events survive reloads and are retried on the next flush if a request fails.
Opt-out
tscohorly.optOutTracking(); // persisted with the identity (localStorage and the cookie)cohorly.hasOptedOutTracking(); // truecohorly.optInTracking();
Opting out drops everything queued and clears breadcrumbs. While opted out
nothing is queued or sent (events, people updates, /alias and $exception)
and no feature flag request is made. Opting back in does not restore what was
dropped. To turn off only error reports, init with captureExceptions: false.
Keeping the token out of the bundle
Passing token to init() embeds it in your client JS. If you would rather
not, proxy ingestion server-side with @cohorly/nextjs's
createCohorlyProxy() and omit token here. See the
Next.js SDK.