Integrate an SDK · Web
Web & React SDK
A framework-independent browser SDK, thin React helpers, and a Playwright runner the CLI launches per replay attempt. Capsules carry sdk.name: @bugcapsule/web and runtime.name: web.
| Package (0.4.0, ESM only) | Entry points | What it is |
|---|---|---|
@bugcapsule/web | ., ./core | The SDK, no dependencies. /core is the environment-neutral model, codec, redaction and request-key core (also used in Node). |
@bugcapsule/react | ., ./react-router | Hooks and components. Peers: @bugcapsule/web 0.4.0 (exact), react ≥18, react-router ≥6.4 (optional) |
@bugcapsule/web-replay | bin bugcapsule-web-runner | Node ≥20 + playwright-core 1.63 runner. Dev dependency, only where you run bugcapsule run|verify |
1. Install
Stable packages are available on npm. Use is governed by the included Bug Capsule Proprietary License; use and distribution require prior written permission.
npm install @bugcapsule/web@0.4.0 @bugcapsule/react@0.4.0
npm install -D @bugcapsule/web-replay@0.4.0
# Optional: source-map upload CLI
npm install -D @bugcapsule/cli@0.4.1
2. Connect with your SDK token
SDK tokens and the status API are included in these releases. Use the SDK token from your dashboard for a new integration. Existing explicit API URL and ingest key configuration remains supported.
Generate an SDK token in the dashboard (Project Settings › Keys › SDK tokens; it is shown once), then make init the first thing your app does:
import { BugCapsule } from '@bugcapsule/web';
await BugCapsule.init({ token: 'bcsdk.v1.…' });
renderApp();
That is a complete connection. The token carries your BugCapsule address and an ingest-only credential: it can send Capsules and events and read capture settings, nothing else, so it is safe in a web bundle. Hosted and self-hosted BugCapsule work the same way; the token knows where to go. appVersion defaults to the version part of release (else unknown) and appBuild to 0; set them so Capsules carry your real version.
- Await
initbefore rendering. In replay it restores storage and state there. - Call it before any code keeps its own reference to
fetch, or that code bypasses capture (and replay's network serving). - A wrong, revoked or unreachable token never throws from
initand never delays your app's start. A second call throws. Setup has a 5 s budget (setupTimeoutMs); if it or an integration fails, the app runs without capture. - Leaving out
modemeans'production', which records onlyproductionSampleRate(10%) of sessions. Set'qa'for QA builds (step 4).
Check the connection
const status = BugCapsule.status(); // null before init
status.connection.state; // 'connected', 'connecting', 'offline', 'rejected', …
status.connection.reason; // e.g. 'token_revoked'
status.connection.message; // what to do about it
status.connection.configFetchedAt; // 1st confirmation: configuration fetched
status.connection.firstEventAcceptedAt; // 2nd confirmation: first event received …
status.connection.firstCapsuleAcceptedAt; // … or first Capsule received
status.instrumentation.missing; // e.g. ['network', 'navigation', 'app_state']
connection.state | Meaning |
|---|---|
not_configured | No token and no backend: captures are saved locally only |
invalid_token / unsupported_token_version | The token can't be read (damaged, a key pasted instead, or made for a newer SDK). One [bugcapsule] line in the console says why; the app runs without BugCapsule |
connecting | No configuration fetched yet in this page session |
connected | Configuration fetched: address, token and network work |
offline | BugCapsule can't be reached; data stays in the outbox and is retried |
rejected | The token was refused: reason is token_revoked, token_expired or token_unknown, message says what to do. Capture and uploads stop for the page session |
disabled | enabled: false, or capture switched off for the project |
The two confirmations are separate on purpose, and the dashboard shows them the same way during onboarding and in the SDK token list: Configuration fetched proves address, token and network; First event or Capsule received proves captured data reaches your project. Neither means replay is fully instrumented: that is instrumentation, and step 4.
3. Get your origin allowed
Browsers only let the SDK reach BugCapsule from origins your project allows. Send your BugCapsule team the exact origins (scheme, host and port) your app runs on, for example:
https://app.example.com
https://staging.app.example.com
http://127.0.0.1:4317 # local QA builds
Until an origin is allowed, the browser console shows CORS errors and nothing is uploaded. The SDK never sends cookies to BugCapsule.
4. Add the progressive adapters
The token connects. Faithful replay also needs the app's network, navigation and state, which you add as you go. Each one you skip is listed in status().instrumentation.missing.
import { BugCapsule, networkIntegration, historyIntegration, localStorageIntegration } from '@bugcapsule/web';
await BugCapsule.init({
token: 'bcsdk.v1.…',
appVersion: '1.4.0',
appBuild: '52',
mode: 'qa', // DEFAULT IS 'production' (10% sampled) — set it
gitSha: import.meta.env.VITE_BUGCAPSULE_GIT_SHA,
integrations: [
networkIntegration({ rules: [{ method: 'POST', path: '/api/checkout', ignoreBodyFields: ['timestamp', 'nonce'] }] }),
historyIntegration(),
localStorageIntegration({ allowPrefixes: ['shop.'] }),
],
allowReplay: import.meta.env.DEV || import.meta.env.VITE_BUGCAPSULE_ALLOW_REPLAY === 'true',
});
renderApp();
Step (missing entry) | Gives replay | Add |
|---|---|---|
network | Recorded fetch/XHR responses served in the page | networkIntegration() (or fetchIntegration() / xhrIntegration()) |
navigation | Route events; the runner opens the checkpoint's location | historyIntegration(), or <BugCapsuleRouteListener /> with React Router |
app_state | Storage and app state restored before render | localStorageIntegration / sessionStorageIntegration, indexedDbIntegration, registerState or useBugCapsuleState |
Then name actions, track inputs and add assertions (next section), and pin the commit with gitSha: set VITE_BUGCAPSULE_GIT_SHA=$(git rev-parse HEAD) (or your bundler's equivalent) in every build, production included. Without it capsules are partial.
Self-hosted or existing setups (advanced)
A self-hosted BugCapsule issues tokens that carry its own address, so the token setup above works there unchanged. Apps set up before tokens, with an explicit address and ingest key, keep working:
await BugCapsule.init({
…,
backend: { url: 'https://api.bugcapsule.com', ingestKey: 'bci_…' }, // never a bcs_ secret key
});
When both are set, backend wins over token. status().connection.source says which one is in use ('token' or 'backend').
5. Make more bugs replayable
| Hook | Why |
|---|---|
onClick={BugCapsule.action('cart.checkout', checkout)} + data-bugcapsule-action="cart.checkout" | Semantic replay by id. The attribute is also the stable selector for click replay. Call action() after init. |
BugCapsule.trackInput('login.email', inputEl) | Typed text is replayed. Password inputs, data-bugcapsule-sensitive, { sensitive: true } and sensitive-looking ids record [REDACTED]. |
BugCapsule.check('cart_total_non_negative', total >= 0) / fail(id) | Wrong behaviour that doesn't throw becomes a checkable failure |
BugCapsule.reportError(e) / <BugCapsuleErrorBoundary> | Errors your code or React catches never reach window.onerror |
BugCapsule.registerState('cart', { serialize, restore }) | App-owned state (Redux, Zustand, a store) in checkpoints, restored in replay |
indexedDbIntegration([{ name, snapshot, restore }]) | IndexedDB stores through adapters you write; the SDK never reads IndexedDB itself |
BugCapsule.now() / date() instead of Date.now() | Replay returns the recorded wall clock |
BugCapsule.random() instead of Math.random() | Seeded per session (mulberry32), same seed in replay |
React
import { useBugCapsuleAction, useTrackedState, useBugCapsuleState,
BugCapsuleErrorBoundary, BugCapsuleCaptureButton } from '@bugcapsule/react';
import { BugCapsuleRouteListener } from '@bugcapsule/react/react-router';
function Cart() {
const [coupon, setCoupon] = useTrackedState('cart.coupon', '');
const [cart, setCart] = useState(emptyCart);
useBugCapsuleState('cart', cart, setCart); // checkpoint + restore
const placeOrder = useBugCapsuleAction('cart.checkout', async () => { … });
return <>
<input value={coupon} onChange={(e) => setCoupon(e.target.value)} />
<button data-bugcapsule-action="cart.checkout" onClick={() => void placeOrder()}>Checkout</button>
</>;
}
<BrowserRouter>
<BugCapsuleRouteListener /> {/* route events with push/pop/replace */}
<BugCapsuleErrorBoundary fallback={<Oops />}><Routes>…</Routes></BugCapsuleErrorBoundary>
<BugCapsuleCaptureButton /> {/* renders nothing in production or replay */}
</BrowserRouter>
| Export | Signature |
|---|---|
useBugCapsuleAction | (id, handler) => handler |
useTrackedInput | (id, { sensitive? }) => ref callback for an uncontrolled input |
useTrackedState | (id, initial: string, { sensitive? }) => [value, setValue] |
useBugCapsuleState | (key, value, restore: (data) => void) |
BugCapsuleErrorBoundary | fallback?: ReactNode | (error, reset) => ReactNode |
BugCapsuleCaptureButton | label?, className? |
BugCapsuleRouteListener | Render inside the router; combine with historyIntegration() for checkpoints |
Integrations
Network: fetch and XMLHttpRequest
networkIntegration({
fetch: true, xhr: true, // or fetchIntegration() / xhrIntegration()
rules: [{ method: 'POST', path: '/api/orders/:id', ignoreBodyFields: ['nonce'] }],
ignoreQuery: ['_', 'ts', 'timestamp', 'nonce', 'cachebust'], // default
maxBinaryBytes: 64 * 1024, maxKeyBodyBytes: 64 * 1024, maxBodyWaitMs: 30_000,
exclude: ({ method, url }) => url.includes('/api/payments'), // keeps method, URL, status, timing only
});
- The SDK reads a
clone()of each response up tomaxBodyBytes(256 KiB text, 64 KiB binary) and cancels the clone; the app consumes the original stream unchanged.text/event-streamisomitted. ReadableStreamrequest bodies,FormDataand XHRBlobbodies are never read: keyed without a body hash.- App wrappers installed after
initsit above the SDK's, so app interceptors still run in replay; only the bytes on the wire come from the capsule.
WebSockets
Available from 0.4.0-beta.3. Capsules with WebSockets are written as capsule spec v2, which older CLIs and tools reject: update the CLI everywhere it runs, CI included, before you turn the integration on. Capsules without sockets stay v1.
WebSocket capture is opt-in. Add the integration next to the others:
import { webSocketIntegration, rawBinarySerializer } from '@bugcapsule/web';
integrations: [
networkIntegration(),
webSocketIntegration({
ignoreQuery: ['_', 'ts', 'timestamp', 'nonce', 'cachebust'], // default; left out of the connection key
// binary: { decode: (bytes, frame) => …, encode: (value, frame) => … }, // keep binary frames
// binary: rawBinarySerializer, // bytes as they are, not redacted
// redactedReplayable: true, // the app doesn't branch on redacted fields
}),
],
- Connection URLs are redacted, and text frames go through the same redaction as JSON bodies. A frame that redaction changed is not replayed unless you pass
redactedReplayable: true. - Binary frames are recorded as their size only; replay can't deliver those, and verification reports them (
ws.noPayload). To keep them, pass a serializer.rawBinarySerializerkeeps bytes without redaction, so use it only for frames without personal data or credentials.Blobframes are always size only; setbinaryType = 'arraybuffer'to record them. - In replay,
WebSocketis an in-memory socket with the browser API (ready states, handlers and listeners,binaryType,bufferedAmount,protocol). Connections are matched by URL and order, sends are compared with the recording, and server messages arrive in recorded order with their recorded delays. A connection the recording doesn't have fails like a network error (anerrorevent, then close 1006), also when the build lacks the integration, so replay never opens a real socket. - The runner blocks real sockets that escaped the page's
WebSocket(workers, references taken beforeinit) and reportsdependency.live. - Limits: 64 KiB per frame, 1 MiB of frames per 5 minutes, 32 sockets open at once (
maxPayloadBytes,maxWindowPayloadBytesandmaxConnectionscan only lower them). Anything beyond is recorded as a gap, so such a capsule can't verify a fix that needs the missing frames. - Adapter id
bugcapsule-web.websocket; your project's capture settings can switch it off without affecting the rest. Capture-to-replay tests ran in Chromium 153, Firefox 155 and WebKit 26.6 (Playwright 1.63); the CLI replays in Chromium only.
Storage, history, IndexedDB
localStorageIntegration({ allowPrefixes: ['shop.'], denyPrefixes: ['shop.token'] }) // allowPrefixes is required
sessionStorageIntegration({ allowPrefixes: ['checkout.'] })
historyIntegration({ sanitizeLocation: (l) => l.replace(/\/reset\/[^/]+/, '/reset/:token') })
indexedDbIntegration([{ name: 'offline-cart', snapshot: async () => readCart(), restore: async (d) => writeCart(d) }])
historyIntegration wraps pushState/replaceState and listens to popstate/hashchange. Cookies, DOM content, input values (except tracked inputs) and storage outside the allowlist are never captured.
Configuration reference
| Field | Default | Notes |
|---|---|---|
token | none | The SDK token (bcsdk.v1.…) from the dashboard: all a connection needs |
appVersion, appBuild | version part of release, else unknown / 0 | Set them so Capsules and releases carry your real version |
appId, appName, flavor | null | Max 200 chars |
mode | 'production' | 'debug' | 'qa' | 'production' |
enabled | true | false = no capture setup at all |
backend | none | { url, ingestKey }: the advanced alternative to token, and wins over it. With neither, captures are saved locally only |
gitSha, gitDirty | null | Missing SHA or dirty tree → build.gitSha gap |
stateSchemaVersion | 1 | |
integrations | [] | A state integration is always appended |
checkpointIntervalMs / windowMs / maxEvents | 30 000 / 300 000 / 20 000 | |
productionSampleRate | 0.1 | Your project's sample rate can only lower it |
autoCaptureOnFailure / maxCapsulesPerSession | true / 3 | Limit applies to auto-capture |
captureNetworkBodies / maxBodyBytes | off in production; on in debug/QA / 256 KiB | off in production mode unless set to true; binary bodies need networkIntegration({ captureBinaryBodies: true }) (What's new) |
collectionEnabled / maxRecorderBytes | true / 8 MiB | consent default and in-memory recorder budget; see consent and local data |
redactKeys, redactHeaders, redactPatterns | [] | redactPatterns: RegExp[] |
beforeRecord(type, data) | — | After built-in redaction; return null to drop |
beforeCheckpoint(integration, data) | — | Return null/undefined to omit that snapshot |
outboxLimits | 10 / 10 MiB / 7 days | { maxCount, maxBytes, maxAgeMs } |
maxStaleConfigMs | 7 days | |
ignoreError(error) | — | Return true if not a failure |
labels | {} | At most 100 |
capturePointers | true | |
sensitiveSelector | '[data-bugcapsule-sensitive]' | Password inputs are always sensitive |
allowReplay | false | Wire to a dev/test build flag only |
storageName | 'bugcapsule' | IndexedDB database name |
setupTimeoutMs | 5000 |
Methods
BugCapsule.action(id, handler) // wraps handler
BugCapsule.actionWithPayload(id, (payload) => …)
BugCapsule.trackInput(id, el, { sensitive }) // returns dispose()
BugCapsule.trackValue(id, set, { sensitive }) // { changed(value), dispose() } for custom widgets
BugCapsule.fail(id, message?); BugCapsule.check(id, condition, message?); BugCapsule.reportError(e)
BugCapsule.log(message, 'debug' | 'info' | 'warn' | 'error')
BugCapsule.route(location, source?, action?) // explicit route events
BugCapsule.registerState(key, { serialize, restore }) // returns unregister; stateChanged(key)
await BugCapsule.capture({ note }) // CaptureResult | null
BugCapsule.now(); BugCapsule.date(); BugCapsule.random()
await BugCapsule.refreshRemoteConfig(); await BugCapsule.flushUploads()
await BugCapsule.pendingUploads(); await BugCapsule.savedCaptures()
BugCapsule.status() // connection + instrumentation, see step 2
BugCapsule.isInitialized; BugCapsule.isRecording; BugCapsule.isReplaying; BugCapsule.mode; BugCapsule.session
Replay with the CLI
{
"runtime": "web",
"web": {
"url": "http://127.0.0.1:4317/",
"installCommand": "npm ci",
"buildCommand": "npm run build",
"serveCommand": "npm run preview -- --port 4317 --strictPort",
"env": { "VITE_BUGCAPSULE_ALLOW_REPLAY": "true" }
}
}
bugcapsule run <id> -n 3 # builds (on the capsule's commit when pinned), serves, replays
bugcapsule verify <id> -n 3 # builds the working tree
bugcapsule run <id> --app-url http://127.0.0.1:4317/ # against an already running build
The CLI passes BUGCAPSULE_GIT_SHA/BUGCAPSULE_GIT_DIRTY in the build environment; map them to your bundler's env (the shop demo's vite.config.ts maps them to VITE_BUGCAPSULE_GIT_SHA with define). The CLI refuses to start when something already serves web.url (it might be an old build).
Per attempt, bugcapsule-web-runner:
- Fetches
/settingsand/capsulefrom the CLI's loopback server. - Launches Chromium with the recorded viewport, scale factor and locale, service workers blocked, a fresh browser context.
- Blocks every request to an origin other than the app's (and
web.allowOrigins) and reportsnetwork.escaped. - Restores
localStorage/sessionStoragein an init script before any page script, exposes the Playwright bindings, and opens the checkpoint's location. - The app's own SDK (with
allowReplay: true) runs the engine: real pointer input through Playwright at recorded coordinates (hit-tested against the recorded target), semantic actions, tracked inputs, synthetic lifecycle; fetch/XHR served from the capsule. - Posts the report to
/resultand prints aBUGCAPSULE_RESULT::line. Default timeout 120 s.
Production protection. Replay activates only when allowReplay: true and the page was opened by the runner. With allowReplay false nothing (URLs, storage, messages, scripts) can turn replay on. A script already in a page with allowReplay: true could imitate the runner bindings, one more reason to keep such builds out of production.
Uploads and storage
- IndexedDB database
bugcapsule: outbox (10 / 10 MiB / 7 days), newest 20 saved captures, cached remote config. Without IndexedDB the SDK keeps them in memory. - Several tabs share one queue; only one uploads at a time (Web Locks, or a lease record on insecure origins). Queues survive reloads; nothing relies on an upload finishing during unload.
- Failed uploads retry with backoff from 30 s up to 1 h; a capsule BugCapsule rejects is dropped.
- Kill switch: purges queue and saved captures, persists. A refused SDK token or ingest key also deletes the queue and saved captures and stops capture for the page session;
status()reportsrejectedwith the reason.
Shop demo
examples/shop: React app with four planted bugs (race, legacy cart, discontinued item, coupon) and a local API (api-server.mjs, port 4318). Environment: VITE_BUGCAPSULE_TOKEN (or, advanced, VITE_BUGCAPSULE_BACKEND_URL + VITE_BUGCAPSULE_INGEST_KEY, which win when set), VITE_BUGCAPSULE_ALLOW_REPLAY, VITE_BUGCAPSULE_DEMO_FIX (race|legacy|discontinued|coupon), VITE_SHOP_API_URL.
node examples/shop/api-server.mjs # shop API on 127.0.0.1:4318
cd examples/shop
VITE_BUGCAPSULE_TOKEN=bcsdk.v1.… \
VITE_BUGCAPSULE_ALLOW_REPLAY=true npx vite build && npx vite preview --port 4317 --strictPort
Browsers and limitations
| Browser | Capture | Replay |
|---|---|---|
| Chromium / Chrome / Edge | tested | tested |
| Firefox, Safari | Playwright Firefox/WebKit tested; released Safari/iOS coverage remains limited | not implemented |
- Hover-only interactions aren't recorded (moves only while pressed); keyboard input only through tracked inputs.
- EventSource payloads, service workers,
sendBeaconand third-party iframes are not captured. WebSockets are captured only withwebSocketIntegration()and only in the page itself: not in workers or iframes, not sockets opened beforeBugCapsule.initor through aWebSocketreference taken before it. Ping/pong and frame details aren't recorded; a socket open at a periodic checkpoint can't be restored (dependency.unrestorable). - Synchronous XHR replays without its recorded latency. Cross-origin script errors without CORS headers arrive as
Script error.. - A fix that makes the app send requests the recording never saw verifies as
INCONCLUSIVE, neverFIXED(network.unrecorded). BugCapsuleCaptureButtonclicks are still recorded as pointer events.- Monitoring supports user context and breadcrumbs; see Monitoring. Consent decisions belong to your application: configure collection before initialization and validate both capsule and monitoring behavior.
Monitoring and release readiness
This SDK also sends error events, release-health sessions, traces and feedback. Configure those separately from capsule recording using Monitoring, upload release symbols, and complete the integration checklist. For approved artifacts, versions and upgrade rules, start with Installation and upgrades.