@userz-ai/browser
v3.0.1
Published
Framework-free Userz feedback widget for browsers.
Readme
@userz-ai/browser
The framework-free core of the Userz feedback widget and in-page telemetry: the bubble and panel in a
shadow DOM, the element picker and session mode, screenshots, console and error capture, the upload and submit pipeline,
and the telemetry families listed under Data collected. The subpath entries
@userz-ai/browser/widget, /panel, /telemetry and /replay are the capability chunks the root entry loads on first
use, and @userz-ai/browser/iife is the script-tag build; an app imports the root entry.
If you use React, you almost certainly want @userz-ai/react on top of this — it adds an idiomatic provider, hook, and <UserzTarget> wrapper. This package is the right entry point for plain HTML, Vue, Svelte, Solid, or vanilla JS.
Install
Script tag (recommended)
No bundler required. Load the pinned, integrity-checked build and create the widget once the page has loaded:
<!-- Pinned to <version> and integrity-checked (recommended) -->
<script src="https://cdn.userz.ai/<version>/userz.js" async
integrity="<integrity>" crossorigin="anonymous"></script>
<script>
window.addEventListener('load', () => {
Userz.createUserz({
publicKey: 'pub_...',
});
});
</script>The current <version> and <integrity> pair is on userz.ai/docs/sdk/browser#cdn,
which renders it from the record each release's deploy writes. The URL names an exact version, so its bytes never change
and the browser refuses to run a file whose digest does not match. The pinned core loads the rest of the SDK from the same
versioned directory and checks each file against a digest built into it, so pinning the core pins everything it loads.
The Content-Security-Policy a page needs is on userz.ai/docs/sdk/csp.
Rolling URL. https://cdn.userz.ai/3/userz.js always serves the newest 3.x release.
Because its bytes change, it cannot carry an integrity attribute. Use it only on pages that accept upgrades without
review. https://cdn.userz.ai/v1/userz.js is frozen at 0.3.5 for existing V1 integrations and never receives a later
release.
npm
pnpm add @userz-ai/browserVersions below 3.0.0 on npm are pre-release builds from May 2026. They are deprecated and predate the consent store, URL
redaction and chunk integrity this README describes. Require ^3.
Quick start
import { createUserz } from '@userz-ai/browser';
const userz = createUserz({
publicKey: 'pub_...',
// getUserToken: identified users (coming) — see "Identified users" below; leave it unset for now.
});
document.querySelector('#feedback-button')?.addEventListener('click', () => {
userz.open();
});That's it. The bubble renders fixed in the bottom-right corner; click it (or call userz.open()) to open the panel. On
submit the widget asks for a presigned upload URL for each screenshot (POST /v1/feedback/upload-url), sends the image
straight to object storage with that URL, then posts the report to POST /v1/feedback.
createUserz throws on a misconfiguration (a missing publicKey, or one that is not a pub_… key), so a bundler
build fails loudly. The script tag's Userz.createUserz warns once on the console and returns the no-op handle instead,
so an inline snippet never breaks the host page. createNoOpUserz() returns that handle yourself: the widget methods do
nothing, and submit and submitSession reject.
Identified users
Identified-user (private) mode: your server signs a short-lived token for the logged-in user with
@userz-ai/node's mintUserToken, and getUserToken returns it, so
each report is attributed to that user. Identified-user (private) mode's self-serve reveal and rotation of the secret in
the dashboard are coming; neither is in the closed beta. Until then, leave getUserToken unset.
Configuration
Every option of createUserz(config). Only publicKey is required.
| Option | Type | Default | What it does |
|---|---|---|---|
| publicKey | string | — | Your App's pub_… key. Required. |
| getUserToken | () => string \| undefined \| Promise<string \| undefined> | — | Returns the identified-user token your server minted (see Identified users — coming). Return undefined when no one is signed in. |
| bubble | boolean | true | Render the floating bubble. Set false to open the panel from your own UI with open(). The App's SDK configuration can also hide the bubble; it never shows one you turned off. |
| showEmailField | boolean | true | Show the "your email" input on the form. Hidden once an identity is known (initialUser or setUser); false hides it always. |
| initialUser | { email?: string; name?: string; externalUserId?: string } | — | The visitor's identity at start; update it with setUser(). |
| mode | 'single' \| 'session' \| 'hover' | the App's SDK configuration, else 'hover' | How a visitor gives feedback: 'hover' shows a small indicator beside the element the pointer rests on, which opens the form for that element (on touch, the bubble starts a tap-to-pick); 'single' opens one form from the bubble; 'session' collects several right-clicked elements and sends them together. Set here, it overrides the App's configuration. In 'single' and 'hover' the session-mode methods do nothing and submitSession() rejects. |
| targetingChord | string | 'Ctrl+Shift+U' | The key chord that toggles the targeting overlay. |
| sessionModeChord | string | 'Ctrl+Shift+S' | The key chord that enters session mode (in mode: 'session'); setSessionMode(true) works without it. |
| consoleCapacity | number | 200 | How many recent console.* lines a submission carries. |
| captureErrors | boolean | true | Attach window errors and unhandled rejections to a submission. |
| onboarding | boolean | true | Show the first-visit popup that explains the active mode, when the App's SDK configuration enables it and the visitor has not dismissed it. false turns it off. |
| onboardingMode | 'dynamic' \| 'static' | 'dynamic' | 'dynamic' animates the demo on a live copy of the page; 'static' shows the animated mock-up and sends nothing. |
| onboardingOnMobile | boolean | false | Show the popup on viewports 520 px wide or narrower too. |
| screenshot | { hostCapture?: HostCapture } | — | hostCapture: a pixel capture your desktop or native shell takes of its own window (see Screenshots). |
| replay | { privacy?: 'strict' \| 'balanced' } | the App's masking profile | privacy: 'strict' masks every text run, 'balanced' masks only tokens holding a digit or @. The stricter of this and the App's profile wins. Replay itself is on only when the App's configuration enables it. |
| componentSource | ComponentSource | — | A source of component names for a picked element that carries none; without one a pick is described without a component name. |
| brandColor | string | Userz mint (UZ_DEFAULT_BRAND) | The bubble's and primary button's colour; any CSS colour. |
| brandForeground | string | UZ_DEFAULT_BRAND_FG | The text colour on top of brandColor. |
| backgroundColor | string | follows the OS light/dark scheme | The panel's surface colour. Once set, the panel no longer switches with the OS scheme. |
| textColor | string | picked for contrast against backgroundColor | The panel's main text colour. |
| csp | { nonce?: string } | the calling script's nonce, if any | nonce: your page's CSP nonce, applied to the widget's <style> element where constructed stylesheets are unavailable. See userz.ai/docs/sdk/csp. |
| telemetry | TelemetryConfig | — | Deprecated: accepted and ignored. The telemetry families run on built-in defaults and the App's SDK configuration; it is kept so existing code still typechecks. |
| platform | PlatformAdapter | the browser | Storage, network, online state, timers and the document the SDK runs on. Inject one to run it against a stub or an embedded runtime; omit it in a browser. |
Methods
userz.open(); // open the panel
userz.setUser({ email, name }); // identity sent with each submission
userz.setMetadata({ route, build }); // metadata sent with each submission
const { id, status } = await userz.submit({ text: 'Wishlist would be great' });
const { blob, width, height } = await userz.captureScreenshot(); // CaptureResult; pass an Element to capture it
userz.destroy(); // tear down every listener and the widget's DOM- Widget:
open(),close(),toggle();setUser(user | null)with{ email?, name?, externalUserId? };setMetadata(meta | null);setTargetingEnabled(on)turns the targeting overlay on or off;registerTarget(target)registers a component for targeting and returns its unregister function. - Submission:
submit(input)sends feedback without the panel and resolves withPromise<{ id: string; status: string }>; its input is{ text, type?, severity?, identity?, metadata?, attachments?, componentTarget?, withScreenshot? }.captureScreenshot(target?)takes a screenshot now, without uploading it, and resolves with aCaptureResult({ blob, width, height, diagnostics?, context? }). - Session mode (
mode: 'session'):setSessionMode(on),isSessionMode(),getSessionItems()(a snapshot, without the screenshots),removeSessionItem(itemId),submitSession({ onProgress? })(uploads every item's screenshot and sends one submission; resolves with{ id, status }) anddiscardSession(). - Identity:
getSessionId(),identify(distinctId, props?),alias(from, to),reset()(a logout: a new anonymous id and a new session) andgetDistinctId(). An e-mail address is never accepted as an identifier. - Consent:
setConsent(category, state)andgetConsent(category)— see Consent. - Telemetry:
signal({ kind, … })emits a custom signal,captureError(err, ctx?)reports an error you caught,trackFunnelStep(name, step)marks a funnel step, andconfigureTelemetry(config?)is deprecated and does nothing. - Replay:
replay—replay.status()(the recorder's state and clip counts) andreplay.uploads()(its uploads). - Events:
on('frustration', handler)fires on each rage, dead or error click the SDK detects, with its kind, the element's descriptor and the DOM node; it returns the unsubscribe function. - Teardown:
destroy()removes every module in reverse install order, then the widget's host element.
Data collected
Every module below installs on every instance, in this order. Telemetry events go to https://api.userz.ai in batches;
every URL the SDK sends passes one sanitiser first, which drops credentials, replaces the value of every query parameter
whose key names a secret (a token, a code, a state, a signature, an e-mail address) and drops every fragment except a hash
route. Console lines are redacted before they leave the page: each secret, token, JWT or e-mail address becomes
[REDACTED:<category>]. "Remote-gated" means the app's SDK configuration in the Userz dashboard can turn the family off.
| Module | What it reads or sends | Where it goes | Consent category | Default |
|---|---|---|---|---|
| transport | Queues every telemetry event and sends it in batches. Batches that could not be delivered, the client rate-limit bucket, a delivery record written at page hide and a server-requested retry deadline are kept in local storage and sent or cleared on the next load. | POST /v1/telemetry/batch | each event's own; an event whose category is not allowed is dropped, and a revoked category's queued events are purged | on |
| config | Fetches the app's SDK configuration with the public key, again when the window regains focus, and keeps the last copy so the next page load starts on it. Sends nothing else. | GET /v1/sdk/config?pk=… | none (sends only the public key) | on |
| upload | Uploads an attachment (a screenshot, a session item's capture, a replay clip): asks for a presigned URL, then sends the bytes straight to object storage. | POST /v1/feedback/upload-url, then a presigned PUT to Cloudflare R2 | the attachment's own | on, only when there is an attachment |
| isolation | Builds the widget's shadow-DOM host and its styles. Sends nothing. | — | — | on |
| widget | The bubble, the feedback panel, the targeting overlay and keyboard chords; holds the identity (setUser) and metadata (setMetadata) a submission carries. Sends nothing itself. | — | — | on |
| submit | The feedback item a visitor sends: the text; the redacted tail of console.log/info/warn/error; uncaught errors and unhandled rejections with their stacks, page URLs inside them sanitised; viewport and user agent; the sanitised page URL; an optional screenshot; the descriptor of a picked or targeted element; your metadata; the identity (from setUser() in public mode, or your JWT in private mode); the session and anonymous ids. A draft may first be sent for a follow-up question. | POST /v1/feedback/evaluate, POST /v1/feedback | feedback (a visitor's own submission) | on |
| session-mode | The multi-item feedback session: the same item content per item, sent as one submission with the items' uploads. | POST /v1/feedback | feedback | on when mode: 'session' |
| picker | The element picker. Reads nothing until a visitor picks an element; the pick adds that element's descriptor to the item. | — | — | on |
| widget-mode | Resolves the submission mode (hover by default) and keeps a per-tab mute after a visitor dismisses the hover prompt. Sends nothing. | — | — | on |
| onboarding | The first-visit popup. Its animated demo sends the page's origin and pathname and the visible text of its headings and buttons, only after the consent store allows analytics; otherwise the visitor gets the static popup, which sends nothing. | POST /v1/widget/demo-suggest | analytics | remote-gated per app |
| screenshot | Captures what the visitor sees, when they ask or pick an element. Regions under a no-capture marker are painted over as same-size boxes. | through upload | feedback | on, only on request |
| session | A session id shared across tabs and a window id per tab, attached to every event; minted only while analytics is allowed. Sends nothing itself. | — | analytics | on |
| identity | An anonymous id (minted on first allowed read) and the identified id from identify(); identify and alias send an event. | POST /v1/telemetry/batch | analytics | on |
| consent | Reads and stores the visitor's consent per category, and reads Global Privacy Control and Do Not Track. Sends nothing. | — | — | on |
| telemetry-api | The manual verbs signal, captureError and trackFunnelStep. | POST /v1/telemetry/batch | analytics | on when you call them |
| autocapture | Clicks on interactive elements, with the clicked element's text after redaction. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
| detectors | Rage clicks, dead clicks and error clicks. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
| errors | Window errors, unhandled rejections and console.error. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
| web-vitals | Core Web Vitals, slow fetches (their sanitised URLs) and long tasks. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
| replay | Session-replay clips around a feedback submission, with text masked by the privacy markers below. | through upload, and a clip event to POST /v1/telemetry/batch | replay | off; on only when the app's configuration enables replay |
| frustration-events | Detects nothing itself: on a frustration the detectors report it can reveal the widget, and it fires on('frustration') in the page. Sends nothing. | — | — | the reveal is off; the event fires |
| pageviews | pageview and pageleave with document.title, the sanitised URL and the referrer. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
| engagement | Scroll depth, time on page, bounces, back-tracking and abandoned forms. | POST /v1/telemetry/batch | analytics | on, remote-gated per app |
Storage
The SDK sets no cookie. It writes only these keys, and a write the browser refuses (a full quota, revoked storage) is kept
in memory for the page instead. A __uz_probe__ key is written and removed in the same call to test that storage is
writable.
| Key | Storage | What it holds | When it is cleared |
|---|---|---|---|
| uz_cfg | local | The last SDK configuration fetched, with the public key it belongs to. | Replaced by the next fetch; a record for another key is ignored. |
| uz_consent | local | The visitor's consent state per category. | Removed when no category holds a recorded state. |
| uz_anon | local | The anonymous id. | reset(). |
| uz_identity | local | The id from identify() and whether a person profile exists. | reset(). |
| uz_session | local | The session id, shared across tabs, and its last activity. | When the session expires, or analytics is revoked. |
| uz_window | session | The window id of this tab. | When the tab closes. |
| uz_eng_pages | session | The number of pages seen in this session. | When the tab closes. |
| uz_q_bucket | local | The client rate-limit bucket. | Overwritten on use. |
| uz_q_overflow | local | Batches that could not be delivered (20 by default). | Sent on the next load. |
| uz_q_handoff | local | A record of the batch sent at page hide. | Read and removed on the next load. |
| uz_q_park | local | A retry deadline the server asked for. | When it passes. |
| userz:onboarding-seen | local | That the first-visit popup was shown. | Never; clear it to show the popup again. |
| userz:onboarding-debug | local | Read only: set it to 1 to log the popup's steps. | — |
| userz:bubble-hint-shown | local | That the bubble's first hint was shown. | Never. |
| userz:hover:frustration:<publicKey> | session | How many times this tab revealed the widget on a frustration. | When the tab closes. |
| userz:hover:muted:<publicKey> | session | That the visitor muted the hover prompt in this tab. | When the tab closes. |
Privacy markers
Put a marker on an element to keep it out of what the SDK captures. Each covers the element and everything inside it.
| Marker | Element descriptions (picker, autocapture, onboarding) | Screenshot | Replay |
|---|---|---|---|
| data-uz-no-capture (also class="ph-no-capture", sentry-block) | not described | painted over with a same-size box | recorded as an empty placeholder |
| data-uz-sensitive (also class="ph-sensitive", sentry-mask) | structure only, no text | unchanged | every text node masked, whatever else is set |
| data-uz-unmask | unchanged | unchanged | text recorded in clear (not under a sensitive marker) |
PostHog's and Sentry's spellings are honoured too, so a page migrating from either is covered from the first load.
Consent
Consent defaults to implicit: the SDK captures until the visitor declines, and a category the visitor has not decided
counts as allowed. The categories are:
analytics— autocapture, page views, performance, engagement, errors and the onboarding demo;replay— session replay;feedback— what a visitor submits through the widget.
A consent banner (CMP) records the visitor's choice through the API:
userz.setConsent('analytics', 'denied'); // 'granted' | 'denied'
userz.getConsent('replay'); // 'unset' | 'granted' | 'denied' — the effective stateBrowsers that send Global Privacy Control or Do Not Track read as denied for analytics and replay, over a recorded
grant, and never for feedback. In explicit mode nothing is captured but a submission the visitor makes until a
category is granted. The mode is the app's SDK configuration (consent.mode); the consent modes are compared on
userz.ai/docs/sdk/migration-v1-to-v2.
Your privacy notice, and whether your EU or UK visitors need consent before any capture, are yours to decide. With the default, the SDK captures from the first page view.
Screenshots
A screenshot is what the user sees, taken in the page and bounded by what is on screen: a log, transcript or feed
thousands of rows long costs no more to capture than its visible part, and a page whose visible part is too large is
refused with a ScreenshotUnavailableError (the feedback still sends) rather than slowing the page. In a desktop or
native shell, hand the widget the shell's own pixel capture:
createUserz({
publicKey: 'pub_…',
screenshot: {
// Electron: the main process's webContents.capturePage(), exposed by your preload script.
hostCapture: async () => {
const png = await window.appShell.captureWindow();
return png ? new Blob([png], { type: 'image/png' }) : null;
},
},
});See userz.ai/docs/sdk/browser#host-capture for the main-process half.
hostCapture may resolve null (or throw) to fall back to the in-page capture for that one screenshot; the image must be
the page's viewport, without window chrome, at any pixel density.
captureScreenshot(element) captures that element, and its CaptureResult also carries context: the whole window,
cropped from the same capture, so a reader sees the element and the page around it. A refused capture rejects with a
ScreenshotUnavailableError whose reason is 'too-large' or 'too-slow'.
Size
These are the ceilings the SDK's asset-budget check holds each build to: the check fails a build that exceeds one.
| Asset | What loads it | At most (gzip) | At most (brotli) |
|---|---|---|---|
| userz.iife.js | The script-tag core, served as https://cdn.userz.ai/<version>/userz.js. | 61,900 B | 53,200 B |
| widget.js | The launcher chunk: the bubble, the targeting overlay and the key chords, fetched when the widget starts. | 52,300 B | 46,100 B |
| panel.js | The panel chunk: the panel, the screenshot editor, the picker, session mode, onboarding and the in-page screenshot, fetched on the first intent to open the panel. | 50,400 B | 44,500 B |
| telemetry.js | The telemetry families' chunk, fetched when the first of them starts. | 14,700 B | 13,400 B |
| replay.js | The session-replay chunk, fetched only when the App's configuration enables replay. | 27,900 B | 25,000 B |
| userz.full.js | Everything in one file, served as https://cdn.userz.ai/<version>/userz.full.js. | 150,300 B | 128,500 B |
| esm-consumer | The entry chunk a bundler emits for import '@userz-ai/browser'; each capability is a lazy chunk of your own bundle. | 38,800 B | 34,500 B |
The script-tag core carries no chunk code. It fetches each chunk from the same exact-version directory on first use and
checks it against an integrity digest built into the core. modern-screenshot ships inside panel.js on the script tag;
in the npm build it stays a dependency your bundler resolves, loaded only when a screenshot is first taken in the page.
userz.full.js fetches nothing: it is for Manifest V3 extensions and strict-CSP pages.
Docs
Full reference at userz.ai/docs/sdk/browser. Source on GitHub.
License
MIT
