Browser: web apps
@sentrinel/plugin/browser captures what a web app does wrong β uncaught
errors, unhandled rejections, failed and slow fetch calls β and puts a
traceparent on same-origin requests, so a click and the server work it caused
land on one trace.
Works in any framework. React, Vue, Svelte, TanStack Start, Next, Remix, or no framework at all.
The one thing to understand first
The browser SDK holds no API key.
Everything in a JavaScript bundle is public. An ingest key shipped to the client is a key any visitor can read out of the page source and use to write into your account, and there is no way to scope an ingest key down after the fact.
So the page posts batches to an endpoint on your own server, and that
endpoint forwards them with the key. @sentrinel/plugin/tunnel is that
endpoint, in about three lines.
The tunnel also pins appName and env server-side, ignoring whatever the
batch claims. Without that, anyone who found the endpoint could write telemetry
into a different app in your account.
browser ββPOST /api/sentrinelβββΆ your server ββX-API-KeyβββΆ api.sentrinel.dev
no key the key lives here
Install
bun add "@sentrinel/plugin@github:Zaga-ltd/sentinel_packages"
Client
// wherever your app boots β before hydration
import { initSentrinelBrowser } from '@sentrinel/plugin/browser';
const sentrinel = initSentrinelBrowser({
endpoint: '/api/sentrinel', // default; same origin, so no key here
release: '2026.8.2',
});
Call it before hydration or first render. An error thrown during hydration is one of the most common real failures, and a handler installed afterwards misses it.
Safe to import from code that also runs on the server: with no window it
returns a no-op handle rather than throwing. Calling it twice returns the first
handle instead of double-patching fetch, which matters because React
StrictMode and hot reload both re-run module init.
Server
Any runtime that speaks Request/Response β Bun, Elysia, Hono, Next route
handlers, TanStack Start, Remix, Deno, Cloudflare Workers.
// app/api/sentrinel/route.ts in Next β the path the SDK posts to by default
import { createSentrinelTunnel } from '@sentrinel/plugin/tunnel';
export const POST = createSentrinelTunnel({
serverUrl: 'https://api.sentrinel.dev',
appName: 'admin',
env: 'prod',
apiKey: process.env.SENTRINEL_API_KEY!, // never reaches the client
release: process.env.GIT_SHA,
});
That is the whole setup.
The default endpoint is /api/sentrinel. It used to be /api/_sentrinel,
which Next's App Router cannot serve β a folder starting with _ is private
and never routed. Pages built against the old default are still out there, so a
server that routes by path should answer both:
import { createSentrinelTunnel, isSentrinelTunnelPath } from '@sentrinel/plugin/tunnel';
const tunnel = createSentrinelTunnel({ /* β¦ */ });
Bun.serve({
fetch: (req) =>
isSentrinelTunnelPath(new URL(req.url).pathname) ? tunnel(req) : app(req),
});
What gets captured
| Signal | Source | Notes |
|---|---|---|
| Uncaught errors | window error event |
Session marked crashed |
| Unhandled rejections | unhandledrejection |
Session marked crashed |
| Handled errors | captureError() |
Session marked errored |
| Requests | patched fetch |
Status, duration, masked query params β client timings, kept apart from the backend's |
| Network failures | patched fetch |
Status 0 β nothing reached a server |
| Breadcrumbs | clicks, navigation, requests, yours | Last 25, on every error |
| Sessions | one per page load | The denominator for crash-free rate |
| Web vitals | PerformanceObserver |
LCP, CLS, INP β attached to the session |
| Device context | navigator, screen |
Language, UA, cores, connection type |
Handlers are added with addEventListener, not by assigning window.onerror.
Assignment replaces whatever the app β or another SDK β already installed, and
silently disabling someone else's error reporting is rude.
The trace join
Same-origin fetch calls get a traceparent header. The backend plugin
continues that trace rather than starting its own, so the click, the request and
the handler appear on one waterfall. That join is the thing most tools do not do
well.
Third-party URLs get nothing by default: sending trace ids to a vendor leaks them, and adding a header turns a simple request into one that needs CORS preflight. Widen it deliberately if you own both ends:
initSentrinelBrowser({
tracePropagationTargets: [/^\//, 'https://api.myapp.com'],
});
A traceparent you set yourself always wins β the SDK only fills in a missing
one.
The same requests β and only those β also carry x-sentrinel-consumer and
x-sentrinel-device (see Identity). If a target is
on another origin, allow traceparent, x-sentrinel-consumer and
x-sentrinel-device in its Access-Control-Allow-Headers.
Browser timings are client data
A fetch timed in the page includes the network and the browser's own queueing;
the backend's measurement of the same call does not. They are different numbers
and are kept apart: browser requests are stored as rows marked
kind: "client" in the web module, and as client spans on the trace β never
rolled into the endpoint metrics the backend plugin reports, where they used to
double every count and blend two unrelated latencies into one p95. Calls to
other origins are marked sentrinel.third_party.
Identity: guests and users
Every browser has a persisted anonymous id (sentrinel.deviceId). Until you say
who the user is, everything is attributed to guest:<device id> β not to
nobody β so a visitor who hit an error before signing in is still one consumer,
followable across visits.
sentrinel.identify('user_123'); // from now on: user_123, and an identify event
// links this device's guest history to them
sentrinel.identify(null); // or sentrinel.reset() β back to the guest id
Every record carries device.id. Same-origin requests send the current consumer
on x-sentrinel-consumer and the device on x-sentrinel-device; the backend
plugins use them when their own consumerIdentifier finds no one β accepting
guest: ids always, and any other value only if it matches the backend's
consumerHeaderPattern, because a header a page sets is a claim, not a fact.
The tunnel's own consumerIdentifier, resolved from the server session,
overrides both.
A user id that cannot be sent as a header value (non-ASCII, over 255 characters) is left off the header rather than failing the request.
Sessions and release health
One session per page load, feeding the same Release health page as mobile.
| Status | Meaning |
|---|---|
ok |
Loaded and left cleanly |
errored |
Reported a handled error |
crashed |
An uncaught error or unhandled rejection |
abnormal |
Ended with no clean shutdown and no error |
Status only ever rises. A handled error after a crash does not downgrade the session β the release's number should not depend on the order two events happened to arrive in.
Delivery is acknowledged: a batch stays queued until the tunnel answers 2xx,
and a failure is retried with backoff (bounded β 50 batches or 1MB, oldest
dropped past that; a 4xx other than 408/429 is not retried). A session whose
batch failed is sent again with its current state, so a crash that happened
after the failure is not overwritten by an older snapshot.
On pagehide (and when the page is hidden) everything still waiting goes by
sendBeacon, the only transport a browser guarantees to complete once the page
is going away, or a keepalive fetch β batches are kept under the 64KB those
allow. unload is unreliable on mobile Safari and blocks the back/forward cache.
Without release, every build reads as unknown and a regression is invisible.
Web vitals
LCP, CLS and INP are collected through PerformanceObserver and travel with the
session, so they are already scoped to a release and a page. They show as p75 on
Release health β vitals have a long tail and the tail
is the point, so an average would hide exactly what you are looking for.
On by default wherever PerformanceObserver exists, which is every supported
browser since 2021; a no-op elsewhere. Turn it off with
captureWebVitals: false.
A page needs on the order of a thousand sessions before these numbers mean anything.
Session replay
Records the DOM and uploads only the seconds leading up to an error.
initSentrinelBrowser({
replay: {
enabled: true,
bufferSeconds: 30, // how much history to keep in memory
tailSeconds: 5, // how long to keep recording after the error
sessionSampleRate: 0, // 0 = errors only; raise to also record clean sessions
},
});
Install the recorder alongside the SDK β it is imported dynamically, so leaving replay off costs nothing in your bundle:
bun add rrweb
Why a buffer, not a stream
Uploading continuously is megabytes per session for recordings almost nobody watches. Buffering means the cost is paid only when something breaks, and what you get is the part you wanted: the thirty seconds before the failure, including the click that caused it. A session that never errors sends nothing at all.
Everything is masked by default
| Text | Masked β every string renders as blocks |
| Inputs | Masked β values are never recorded |
| Canvas | Not recorded |
| Fonts | Not collected |
Nobody enables replay expecting to ship customer names, addresses and order totals to a vendor, so visibility is opt-in:
<!-- This element's text is readable in the replay. Nothing else is. -->
<div data-sentrinel-unmask>Order #1042 β shipped</div>
<!-- Not recorded at all, not even its layout. -->
<div data-sentrinel-block><iframe src="https://bank.example"></iframe></div>
Change the selectors with unmaskSelector / blockSelector if those
attributes clash with your markup.
Requirements and limits
- ClickHouse. Recordings are far too large for the Postgres telemetry
store, so
TELEMETRY_STORE=clickhouseis required. Ingest answers501rather than accepting and dropping them. - Retention is separate and shorter than telemetry β
RETENTION_REPLAY_DAYS, default 14. - A chunk is capped at 4MB. Larger is refused with
413. - A recording that only fails at the very last moment may be lost. The
upload needs the page to still be alive;
sendBeaconcannot carry megabytes.
Recordings appear under Session replay in the dashboard, linked to the session they came from.
Options
initSentrinelBrowser({
endpoint: '/api/sentrinel', // where batches go
release: '2026.8.2', // per-release crash-free rate
captureErrors: true, // window errors + rejections
captureRequests: true, // patch fetch
captureBreadcrumbs: true, // clicks + navigation
trackSessions: true, // one per page load
sampleRate: 1, // successful requests kept
slowRequestThresholdMs: 2_000, // above this, always kept
flushInterval: 10_000,
maxBatch: 100,
tracePropagationTargets: [/^\//], // same-origin only, by default
ignoreErrors: ['AbortError'], // on top of the built-in noise list
maskQueryParams: ['invite'], // on top of the built-in credential list
beforeSend: (record) => record, // last stop before the wire; null drops it
debug: import.meta.env.DEV,
});
Errors and slow requests are never sampled out regardless of sampleRate.
Lowering it only ever loses the healthy baseline you need to tell "slow" from
"normal".
Noise dropped by default
Reported by browsers, never actionable:
Script error.β a cross-origin script failure with nocrossoriginattribute. No message, no file, no line.ResizeObserver loop limit exceeded/β¦undelivered notificationsβ fired by the spec itself, benign in almost every case.- Anything originating in
chrome-extension://ormoz-extension://β someone else's code, not yours.
Redacting in the browser
URLs are masked by default. Reset and magic-link tokens, OAuth code,
?api_key=, pre-signed S3/GCS signatures β the page URL is exactly where they
turn up. Every URL the SDK sends has those values replaced with ***: request
query params, http.url, the page URL on every record, error source URLs,
pageviews and referrers, and the session-replay URL. The fragment is included,
because OAuth's implicit flow returns #access_token=β¦. maskQueryParams adds
keys to the built-in list.
beforeSend runs before a value is ever put on the wire, which is the only
place that helps for other data that should not leave the device at all.
beforeSend: (record) => {
if (record.kind === 'error' && record.errorMessage?.includes('@')) return null;
return record; // return null to drop it entirely
}
A beforeSend that throws does not swallow the record it was inspecting.
Tunnel options
createSentrinelTunnel({
serverUrl: 'https://api.sentrinel.dev',
appName: 'admin', // pinned; the batch cannot override it
env: 'prod', // pinned
apiKey: process.env.SENTRINEL_API_KEY!,
release: process.env.GIT_SHA,
module: 'web', // the default: the page is its own module
maxBodyBytes: 256 * 1024, // an open endpoint that buffers anything
// is a memory-exhaustion target
consumerIdentifier: (request) => userIdFrom(request),
beforeForward: (batch, request) => batch, // null drops the batch
});
consumerIdentifier is read from the request server-side and overrides
whatever the browser claimed. An identity a page asserts about itself is a
claim, not a fact. This is what makes errors group under a person on the
Consumers page.
module defaults to web rather than to the key's name: the tunnel usually
runs on your backend with the backend's own key, and defaulting to the key filed
every browser record under the backend's module. Client spans for propagated
requests go in one batched call per page batch.
The tunnel always answers 202 once a batch parses, even if forwarding to
Sentrinel fails. An error response would appear in the page's console as a
failed request β noise about monitoring, in place of the app's own signal. (The
page's own retry covers the tunnel being unreachable; forwarding failures behind
it are logged on your server.)
API
sentrinel.captureError(err, { orderId }); // handled error, with context
sentrinel.addBreadcrumb('tapped pay', { category: 'ui', data: { amount: 42 } });
sentrinel.identify('user_123'); // setUser() is the same; null = guest again
sentrinel.reset(); // sign-out: back to guest:<device id>
sentrinel.consumer; // 'user_123' or 'guest:anon_β¦'
sentrinel.deviceId; // the persisted anonymous id
sentrinel.setContext({ tier: 'pro' }); // attached to everything after
await sentrinel.flush(); // send now
await sentrinel.close(); // unpatch, end session, send
Breadcrumbs fill themselves from clicks, navigation and requests. Add your own for business events β a trail you have to remember to fill is empty in exactly the session that just broke.
Source maps
A minified stack is not a bug report. t (app-abc123.js:1:48291) says "the
bundle, first line"; renderCheckout (src/pages/checkout.tsx:84:12) is the bug
with a name and an address.
Upload the map your build just produced, tagged with the same release string the SDK reports:
curl -X POST https://your-sentrinel/api/ingest/symbols \
-H "X-API-Key: $SENTRINEL_API_KEY" \
-H "Content-Type: application/json" \
-d "$(jq -n \
--arg app "$SENTRINEL_APP_NAME" \
--arg env "$SENTRINEL_ENV" \
--arg release "$RELEASE" \
--arg file "app.js" \
--rawfile content dist/app.js.map \
'{appName:$app, env:$env, release:$release, kind:"sourcemap", file:$file, content:$content}')"
/api/ingest/symbols authenticates with an API key, because a build pipeline
has no browser session. A server key works; a mobile key is refused on
purpose β it ships inside an app bundle, and a leaked bundle key that could
upload symbol artifacts could rewrite the stack traces of every error in the
release. The dashboard's own upload (POST /api/symbols, session-authenticated)
does the same thing for a map you have on your laptop.
Tell the SDK which release it is running, or there is nothing to match the map against:
sentrinel.init({ release: "2026.8.2" /* β¦the rest */ });
Then:
- Symbolication happens at ingest, before fingerprinting, so issues group by real source location rather than by minified bundle. Two errors from the same minified line collapse into one issue.
- The minified original is kept as
rawStack, so nothing is lost if a map turns out to be wrong. - A re-upload for the same
(app, release, kind, file)replaces the previous one; rebuilding a release does not stack up dead maps. - A map that does not parse is rejected at upload with a
422rather than silently doing nothing for every error that names the release.
Uploads are capped at 8 MB for a source map (20 MB for other artifact kinds).
kindalso acceptsdsym,proguardandsymbols. Those are stored and listed, but nothing consumes them yet β native crash symbolication is not implemented. Onlysourcemapchanges a stack today.
Not covered
- XHR. Only
fetchis patched. Libraries built onXMLHttpRequest(older axios builds) are not recorded. - Native crash symbolication (dSYM / ProGuard). Artifacts upload and store, but no stack is rewritten from them.
See also
- FULL_CONFIG.md β every option across every SDK
- PLUGIN.md β the backend plugin the trace joins up with
- MOBILE.md β Flutter and Dart
- TROUBLESHOOTING.md β nothing showing up?