DEV Community

Cover image for Browser Error Tracking: The Tracker You Can Finally See
Rajat
Rajat

Posted on

Browser Error Tracking: The Tracker You Can Finally See

Version 1.0.3 turns a write-only error recorder into something your application can observe, teach and use before the incident with one-line setup, live events, an HTTP client that reports its own failures, and encryption at rest.

At 09:12 on a Monday, a support agent sends you a screenshot. The customer saw Something went wrong at checkout. The console is empty. The network tab is empty. The dashboard is green.

This time, the record exists. It has been in IndexedDB since 09:11:47. It has the route, the order id, the stack, the build id, the page load id. Everything you would have asked for is already there.

Nobody can see it.

That is the strange failure mode of browser telemetry: capturing the error is the easy half. The hard half is making the capture visible to the people who need it, at the moment they need it, without asking a support agent to open DevTools. A tracker that only writes is a diary you never open.

Version 1.0.3 is about that second half. It does not add another place to send errors. It adds the seams that make the recorder legible from inside the application: a configuration that fits on one line, an event stream your UI can subscribe to, an HTTP client that turns a failed request into a record, encryption for the records already on disk, and a defaults page that answers the question everyone asks during an incident — "I never set this, so what am I getting right now?"

Between here and there you will build a small telemetry panel that shows errors as they happen, wire an API client that reports its own failures, teach the classifier your domain vocabulary, and encrypt the fields a support engineer should not be able to read from a devtools screenshot.

Keep one question in mind while you read, because I answer it near the end. If your tracker caught an error right now, how would you know?

This is the sequel to Browser Error Tracking: The Errors Your SDK Never Sends. You do not need to have read that one to follow this — but if you did, this is the part where the recorder starts talking back.

If debugging is the part of the job you actually like, follow me here on Medium. I publish one practical frontend piece a week and I reply to comments. If someone on your team owns the error dashboard, send them this.

What actually changed in 1.0.3

Quick version. The recorder was already complete. What was missing was the surface around it:

New surface What it gives you
setupTelemetry() and flat aliases The shortest real setup stops being a three-level nesting exercise.
handle.events Six typed events, so a badge, a store or a toast can subscribe instead of polling.
@codewithrajat/rm-logvault/http A fetch client whose failures are already shaped for captureError, with retries, timeouts, interceptors and auth.
@codewithrajat/rm-logvault/storage AES-GCM-256 encryption for chosen record fields, plus a repository wrapper.
ADAPTERS and getSinkRegistry() A frozen map of every integration, and a way to list and detach sinks by key.
docs/DEFAULTS.md Every option and every environment variable, with the value in force when the key is absent and what that value does.

Real-world version. None of these is a new category of product. They are the questions a team asks on day two of owning a tracker:

  • "Why is this configuration so long that nobody reviews it?"
  • "How do I show the error count in the app without polling the database?"
  • "Our API failures are not in the vault. Do we really need a try/catch around every call?"
  • "The redaction works, but the message still contains a customer name. What if someone reads the database?"
  • "Which adapter exists for our framework, and what does it export?"
  • "I did not set this option. What is it doing?"

Under the hood. The release is deliberately split by cost. The event emitter, the flat aliases, the context-builder registry and the sink registry live in the core entry because they are wired into captureError and initTelemetry and are small. The HTTP client and encryption live behind subpaths, because an application that already uses axios should not pay for a fetch client it will never call, and an application that does not encrypt should not pay for AES.

That is the same rule the library has followed since 1.0.0: a feature that only some users need is an option that costs nothing when unset, or a separate entry point.

Teaser. The shortest way to see the difference is to look at the configuration you already have.

The configuration that fits on one line

Quick version. Here is a real initTelemetry call from a checkout app, before 1.0.3.

// src/telemetry.ts
import { initTelemetry } from '@codewithrajat/rm-logvault';

initTelemetry({
  appName: 'checkout',
  appVersion: '2.4.1',
  rest: {
    errorsUrl: '/telemetry',
    logsUrl: '/telemetry',
  },
  logs: {
    level: 'info',
    consoleLevel: 'warn',
  },
  errors: {
    maxRecords: 1000,
  },
});
Enter fullscreen mode Exit fullscreen mode

Nothing here is wrong. It is precise, explicit, and exactly what the type says. It is also fifteen lines to express four facts: which app this is, where the records go, what is worth persisting, and how many errors to keep.

After 1.0.3:

// src/telemetry.ts
import { setupTelemetry } from '@codewithrajat/rm-logvault';

export const telemetry = setupTelemetry({
  app: 'checkout',
  version: '2.4.1',
  url: '/telemetry', // feeds BOTH error and log uploads
  level: 'info', // the PERSIST level
  consoleLevel: 'warn',
  maxErrors: 1000,
});
Enter fullscreen mode Exit fullscreen mode

Same configuration. Seven fewer lines, and — more importantly — the line that says url is the line that means "one collector for both kinds", which is the fact you actually wanted to express.

Real-world version. The flat aliases are not a second configuration system. They are the same options, spelled shorter, and they work directly on initTelemetry too. That matters for migration: you can flatten one option at a time, in a codebase that has forty of these calls.

Flat alias Maps to Notes
url rest.errorsUrl and rest.logsUrl the one-collector case
errorUrl / logUrl rest.errorsUrl / rest.logsUrl split the endpoints
headers rest.getHeaders awaited per request
level logs.level the minimum level persisted
consoleLevel logs.consoleLevel console verbosity applied at init
captureConsole logs.captureConsole wraps console.warn / console.error
maxErrors / maxLogs errors.maxRecords / logs.maxRecords rows retained
app / version / build appName / appVersion / buildId identity

The precedence rule is the part worth memorising, because it is what lets you start flat and still override one side later:

nested option  >  flat alias  >  environment  >  built-in default
Enter fullscreen mode Exit fullscreen mode

So this works exactly as it reads:

import { initTelemetry } from '@codewithrajat/rm-logvault';

initTelemetry({
  url: '/everything', // both kinds go here…
  rest: { errorsUrl: '/errors' }, // …except errors, which go here.
});

// errors → /errors      logs → /everything
Enter fullscreen mode Exit fullscreen mode

An invalid or empty nested value does not win. It falls through to the next candidate, which is the behaviour you want when a value comes from an environment variable that somebody typo'd:

// Imagine 'verbose' arrived from an environment variable or a JSON config,
// where the type system cannot reject it.
initTelemetry({ level: 'error', logs: { level: 'verbose' as never } });
// → 'error'. An unrecognised level is ignored, so the flat alias is consulted.
Enter fullscreen mode Exit fullscreen mode

For the two spellings of the same thing, the explicit long name wins:

initTelemetry({ appName: 'checkout', app: 'checkout-dev' });
// → 'checkout'
Enter fullscreen mode Exit fullscreen mode

Under the hood. setupTelemetry forwards to initTelemetry unchanged. It is not a wrapper with its own defaults and it is not a second object to learn. Its option type is a Pick of the real TelemetryOptions, so adding a field to the simple path means adding it to the real one — the two cannot drift.

It is also idempotent in exactly the same way: a second call returns the existing handle and installs nothing. That is deliberate, and it is the reason the examples in this article initialise in one module and import the handle everywhere else. A second call with different options is silently ignored, not merged.

Source note. setupTelemetry is a focused subset. It does not accept a custom repository, beforeCapture, adapters, redaction options or the nested errors / logs groups. When you need those, keep using initTelemetry; the flat aliases are still available there. The encryption example below uses initTelemetry for exactly that reason.

Try this now. Open the file where you call initTelemetry. Count the levels of braces in the options object. If the answer is more than two, rewrite the parts that have a flat alias and run your tests. The behaviour should not change — and if it does, you just found a configuration that was not doing what you thought.

Teaser. A shorter configuration is easier to trust. But you still cannot see it working.

Your tracker should tell you when it catches something

Quick version. initTelemetry returns a handle, and the handle has an events member. It is a small typed emitter. You subscribe; it calls you when something happens.

// src/telemetry.ts
import { setupTelemetry } from '@codewithrajat/rm-logvault';

export const telemetry = setupTelemetry({ app: 'checkout', version: '2.4.1' });

telemetry.events.on('error:captured', (event) => {
  // event.recordId, event.fingerprint, event.severity, event.source,
  // event.category, event.handled, event.occurrenceCount
  console.debug('[telemetry] captured', event.fingerprint, event.source);
});
Enter fullscreen mode Exit fullscreen mode

Six events exist:

Event Fires when Useful fields
error:captured an error record is accepted recordId, fingerprint, severity, source, category, handled, occurrenceCount
log:written a log passes the persist level recordId, level, message
sync:started syncTelemetry() begins, per kind kind, recordCount
sync:completed a kind's upload pass finishes kind, uploaded, retried, failed
sync:failed a kind had terminally failed records kind, status, recordCount
record:dropped a limiter or hook discarded captures kind, reason, count

record:dropped's reason is 'rate-limit', 'repeat-limit', 'consent', 'payload-limit' or 'before-hook'. The distinction matters: a repeat-limit drop means the failure is already in the report, while a rate-limit drop means records are genuinely missing.

The emitter has the rest of the small surface you would expect. onAny(listener) receives every event, off(type, listener) removes one, listenerCount(type?) answers "is anything listening?", and clear() removes everything (it is called by destroyTelemetry). on returns an unsubscribe function, and calling it twice is safe.

Real-world version. The obvious use is a badge. The less obvious use is that a badge is the smallest thing this enables.

Here is the pattern people write before they have events:

// The polling version. It compiles, and it lies.
import { getTelemetryStatus } from '@codewithrajat/rm-logvault';

setInterval(() => {
  const status = getTelemetryStatus();
  setErrorCount(status.pending.errors);
}, 1000);
Enter fullscreen mode Exit fullscreen mode

pending.errors is a snapshot of the outbox, not a count of captures. It goes down after a flush. It can stay at zero while a record is being written. It cannot distinguish "three errors arrived" from "one record is still pending". And on a quiet page it wakes up once a second to tell you nothing.

The event stream gives you the fact you wanted:

// src/telemetry-store.ts
import { setupTelemetry } from '@codewithrajat/rm-logvault';

export const telemetry = setupTelemetry({
  app: 'checkout',
  version: '2.4.1',
  url: '/telemetry',
});

interface Snapshot {
  readonly errors: number;
  readonly lastFingerprint: string;
  readonly lastMessage: string;
}

let snapshot: Snapshot = { errors: 0, lastFingerprint: '', lastMessage: '' };
const listeners = new Set<() => void>();

telemetry.events.on('error:captured', (event) => {
  snapshot = {
    errors: snapshot.errors + 1,
    lastFingerprint: event.fingerprint,
    lastMessage: `${event.severity} from ${event.source}`,
  };
  for (const listener of listeners) listener();
});

export function subscribe(listener: () => void): () => void {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

// Must return the cached object. A fresh object on every call makes React
// re-render forever.
export function getSnapshot(): Snapshot {
  return snapshot;
}
Enter fullscreen mode Exit fullscreen mode
// src/TelemetryBadge.tsx
import { useSyncExternalStore } from 'react';
import { getSnapshot, subscribe } from './telemetry-store';

export function TelemetryBadge() {
  const { errors, lastFingerprint, lastMessage } = useSyncExternalStore(subscribe, getSnapshot);

  if (errors === 0) return null;

  return (
    <span role="status" title={`${lastFingerprint} — ${lastMessage}`}>
      {errors} error{errors === 1 ? '' : 's'} recorded
    </span>
  );
}
Enter fullscreen mode Exit fullscreen mode

useSyncExternalStore is the React 18+ way to read a value that lives outside React without tearing. The cached snapshot is not an optimisation; it is the contract.

You can go further without much code. The following panel is the one I would actually ship on an internal build: a count, the last failure, a drop warning, and a button that produces the report a support engineer needs.

// src/TelemetryPanel.tsx
import { useEffect, useState, useSyncExternalStore } from 'react';
import { exportDiagnosticsReport } from '@codewithrajat/rm-logvault';
import { getSnapshot, subscribe, telemetry } from './telemetry-store';

export function TelemetryPanel() {
  const { errors, lastFingerprint, lastMessage } = useSyncExternalStore(subscribe, getSnapshot);
  const [drops, setDrops] = useState(0);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');

  // Subscribe once, in the component that shows the result.
  // `on` returns the unsubscribe function React uses as cleanup.
  useEffect(() => {
    const off = telemetry.events.on('record:dropped', (event) => {
      setDrops((current) => current + event.count);
    });
    return off;
  }, []);

  async function download(): Promise<void> {
    setBusy(true);
    setMessage('');
    try {
      const result = await exportDiagnosticsReport({ format: 'html' });
      setMessage(result.ok ? `Report ready — ${result.bytes} bytes` : 'Export failed');
    } finally {
      setBusy(false);
    }
  }

  return (
    <aside aria-label="Telemetry">
      <p>
        <strong>{errors}</strong> errors recorded
        {drops > 0 ? `, ${drops} dropped by a limiter` : ''}
      </p>
      {errors > 0 ? (
        <p title={lastFingerprint}>
          Last: {lastMessage}
        </p>
      ) : null}
      <button type="button" disabled={busy} onClick={() => void download()}>
        Download diagnostics
      </button>
      {message !== '' ? <p role="status">{message}</p> : null}
    </aside>
  );
}
Enter fullscreen mode Exit fullscreen mode

Source note. The subscription belongs in useEffect, with the returned unsubscribe function as cleanup. The other safe shape is to subscribe at module scope after initTelemetry has returned. events.on(...) on a handle whose telemetry is not initialised is a no-op: it returns an unsubscribe function, but the listener is never registered and never called.

Under the hood. The emitter is built for the failure path, not for a UI library. Three guarantees make it safe to hand to a host application:

  • A throwing listener cannot break the capture it was notified about. Every listener runs inside its own guard, so a broken badge cannot stop a record from being persisted.
  • An async listener cannot produce an unhandled rejection. A returned promise is observed, and its failure is routed into the library's internal diagnostics.
  • Nested emission is bounded. A listener that emits — or that calls logger.warn(...), which writes a log and emits log:written — has its nested event delivered once, asynchronously. Any further nesting is dropped and reported once. A listener that emits on every event cannot spiral.

The dispatch itself iterates a snapshot of the subscriber set, so a listener can unsubscribe during dispatch and the behaviour is well-defined.

There are boundaries worth knowing before you build a dashboard on this:

  • sync:started and sync:completed are emitted by an explicit syncTelemetry() call. The background scheduled flush is internal and does not emit them, so do not use them as a "last upload" clock on their own.
  • sync:failed.status is always 0, which means "not captured", not "network failure". FlushSummary is a per-kind aggregate over several batch attempts, so there is no single status to report. Use rest.onTerminalFailure when you need the real HTTP status.
  • record:dropped is a periodic summary, not a live per-event feed: it is reported from syncTelemetry() and destroyTelemetry().
  • destroyTelemetry() clears listeners. The handle.events object identity survives a destroy/re-init cycle, but the registrations do not.

Try this now. Add one listener for error:captured that writes event.type to the console, then use your app for a minute. You will learn more about your real error volume from that minute than from a dashboard tab — including how many of those errors you had already decided were "fine".

Teaser. Once you can see the records, the next complaint is that the library's idea of a category does not match yours.

Teaching the classifier your application's vocabulary

Quick version. The library classifies the failures it produces: HTTP, timeout, chunk load, CSP, type errors. It cannot know that code: 'ALARM_NOT_FOUND' is a domain failure, not a runtime crash.

A context builder is where that knowledge goes.

// src/telemetry-domain-context.ts
import { registerErrorContextBuilder } from '@codewithrajat/rm-logvault';

export const unregister = registerErrorContextBuilder({
  name: 'alarms',
  canHandle: (error) => {
    const code = (error as { code?: unknown } | null)?.code;
    return typeof code === 'string' && code.startsWith('ALARM_');
  },
  build: (error) => ({
    category: 'runtime',
    severity: 'warning',
    tags: {
      domain: 'alarms',
      code: String((error as { code?: unknown }).code),
    },
  }),
});
Enter fullscreen mode Exit fullscreen mode

Register it once, at module load, before the first capture. Every capture then passes through it — including captures from window.onerror, a framework adapter, or a third-party script your application does not control.

Real-world version. The first time you write a builder, the temptation is to make it a catch-all. Resist that. Resolution is registration order, first match wins, so a broad builder registered early shadows every specific one after it.

Two rules keep a builder honest:

  1. The call site wins. A builder can supply category, severity, tags and extra, but an explicit field from captureError(error, { source: 'react' }) replaces it. A registration cannot relabel an integration you already described correctly.
  2. tags and extra merge key-by-key. Those two are additive by nature. If the builder contributes { domain: 'alarms' } and your call site contributes { boundary: 'checkout' }, the record gets both. On a conflict, the caller wins.
captureError(error, { source: 'react', tags: { boundary: 'checkout' } });
// record.tags → { domain: 'alarms', boundary: 'checkout' }
Enter fullscreen mode Exit fullscreen mode

The registry survives destroyTelemetry(), because it describes your application rather than one installation. That is what makes it safe across a hot reload or a microfrontend remount. Registering the same name again replaces the previous builder, so re-registration is idempotent instead of stacking duplicates. A throwing canHandle counts as "no match"; a throwing build falls through to the next builder. A bad classifier cannot swallow a capture.

Under the hood. Three built-ins ship behind one call:

import { installBuiltinContextBuilders } from '@codewithrajat/rm-logvault';

installBuiltinContextBuilders();
Enter fullscreen mode Exit fullscreen mode

They run timeout → http → type-error, in that order. Nothing self-registers: importing the module has no effect until you call the function. That is deliberate. Upgrading a patch version must never change how your existing application classifies its errors as a side effect.

Source note. The individual builders are exported too, so you can install one without the other two. See timeoutErrorContextBuilder, httpErrorContextBuilder and typeErrorContextBuilder.

Try this now. Write down the three error codes your support team asks about most often. Those are your first three builders. Notice that none of them is about the library — they are about your product, which is exactly why the library could not know them.

Teaser. Classification helps once the record exists. A lot of API failures never become records at all.

The HTTP call that never became an error

Quick version. Every application has a place where a request failed and nothing was reported. The catch block rethrows, the promise rejects, the console shows a red line, and the vault stays empty because nobody called captureError.

The /http subpath is a fetch client with a seam for exactly that moment.

// src/http.ts
import { captureError } from '@codewithrajat/rm-logvault';
import { createFetchHttpClient } from '@codewithrajat/rm-logvault/http';

export const http = createFetchHttpClient({
  baseUrl: '/api',
  timeoutMs: 10_000,
  retry: 1,
  // Called with the failure before it is thrown. The failure is a real Error,
  // and the context is already an ErrorContext — so the two compose without a cast.
  onError: (error, context) => {
    captureError(error, context);
  },
});
Enter fullscreen mode Exit fullscreen mode
// anywhere
import { http } from './http';

const { data } = await http.get<Order[]>('/orders');
Enter fullscreen mode Exit fullscreen mode

The client belongs at module scope, for the same reason initTelemetry does: it is stateless configuration, and creating it inside a component rebuilds it on every render.

Real-world version. The options that matter are the ones that change what a failure looks like.

Option Default What it does
baseUrl none prefix for relative request URLs
timeoutMs 30_000 abort budget per attempt
headers none merged into every request, before the per-request ones
getHeaders none awaited per request, merged last
bodyMode 'json' 'json' / 'text' / 'raw' request encoding
readAs 'auto' 'auto' / 'json' / 'text' / 'arrayBuffer' / 'blob' / 'none'
credentials 'same-origin' fetch credentials mode
retry 0 extra attempts for a retryable failure
retryDelayMs 300 base backoff delay
rejectOnHttpError true reject on a non-2xx response
onError none observe the failure before it is thrown
fetchImpl globalThis.fetch the fetch to use

timeoutMs is per attempt, not per call. This is the detail that surprises people. Attempts are 1 + retry, and each one gets its own budget, so retry: 2 with a five-second timeout can take about fifteen seconds before it rejects. If you want a hard five-second ceiling, set retry: 0 or lower the per-attempt budget.

Only statuses 0 (no response), 408, 429 and every 5xx are retried. A 404 will not succeed on retry, so it is not retried. A deterministic failure — a header provider that throws, for example — is not retried either, because the same input raises the same throw.

Source note. retry applies to failures that reject. With rejectOnHttpError: false, a non-ok response is the result, so there is nothing to retry and retry is inert. Pick one: either you want failures thrown and retried, or you want the response handed back for inspection.

Reading nothing from the response. For a health check or a ping, readAs: 'none' never touches the body. You save the transfer and the parse, and the body is never read at all.

const health = createFetchHttpClient({
  baseUrl: '/api',
  readAs: 'none',
  timeoutMs: 3_000,
  retry: 2,
  onError: (error, context) => captureError(error, context),
});

const { status, ok } = await health.get('/healthz');
Enter fullscreen mode Exit fullscreen mode

Interceptors. They are the place for the things you would otherwise repeat at every call site.

import { logger } from '@codewithrajat/rm-logvault';
import type { HttpInterceptor } from '@codewithrajat/rm-logvault/http';
import { http } from './http';

const correlation: HttpInterceptor = {
  name: 'correlation',

  onRequest: (request) => ({
    ...request,
    headers: {
      ...request.headers,
      'x-request-id': crypto.randomUUID(),
    },
  }),

  onResponse: (response, request) => {
    if (response.durationMs > 2_000) {
      logger.warn('[http] slow response', { url: request.url, ms: response.durationMs });
    }
    return response;
  },
};

http.setInterceptors([correlation]);
Enter fullscreen mode Exit fullscreen mode

Every callback is contained, though not identically. A throwing onResponse or onError is reported through the library's internal diagnostics and the request still succeeds or fails as it otherwise would. A throwing onRequest is reported and converted into an HttpError: the request is not sent, and the failure is still shaped for onError and captureError rather than escaping as an arbitrary thrown value. An onRequest that returns null cancels the call the same way — useful for a feature flag or an offline guard.

const offlineGuard: HttpInterceptor = {
  name: 'offline-guard',
  onRequest: (request) => (navigator.onLine ? request : null),
};

http.setInterceptors([offlineGuard]);
Enter fullscreen mode Exit fullscreen mode

One auth provider, two consumers. The auth helpers exist so the HTTP client and the telemetry uploader share a single refresh policy. Concurrent refreshes coalesce into one in-flight attempt, so ten parallel requests with an expired token refresh once, not ten times.

// src/auth.ts
import { createAuthHeaderProvider } from '@codewithrajat/rm-logvault/http';

export const auth = createAuthHeaderProvider({
  getToken: () => sessionStore.token,
  refreshToken: async () => (await refreshSession()).token,
  isTokenExpired: (token) => jwtExpiry(token) < Date.now(),
  onUnauthorized: () => {
    router.navigate('/login');
  },
});
Enter fullscreen mode Exit fullscreen mode
// src/telemetry.ts
import { setupTelemetry } from '@codewithrajat/rm-logvault';
import { auth } from './auth';

setupTelemetry({
  app: 'checkout',
  url: '/telemetry',
  // The flat alias for `rest.getHeaders`. Awaited per request, so a rotated
  // token is picked up without re-initialising.
  headers: auth.getHeaders,
});
Enter fullscreen mode Exit fullscreen mode
// src/http.ts
import { captureError } from '@codewithrajat/rm-logvault';
import {
  createAuthInterceptor,
  createFetchHttpClient,
} from '@codewithrajat/rm-logvault/http';
import { auth } from './auth';

export const http = createFetchHttpClient({
  baseUrl: '/api',
  onError: (error, context) => captureError(error, context),
});

http.setInterceptors([createAuthInterceptor(auth)]);
Enter fullscreen mode Exit fullscreen mode

Two details are worth knowing:

  • onUnauthorized is not called when there is simply no token. That is the normal anonymous path, and firing there would redirect to a login page on every request made before a user signs in. It is called when a token was present, was stale, and could not be refreshed — a real loss of session.
  • The interceptor does not re-issue the request after a 401. It refreshes once, and calls logout() / onUnauthorized() if that fails. The client owns its retry policy, and a silent second request would double-report the original failure. Re-issue explicitly from your own code when you want that.

For an API key that is sent bare rather than as a bearer token:

const apiKeyAuth = createAuthHeaderProvider(
  { getToken: () => import.meta.env['VITE_API_KEY'] },
  { headerName: 'X-API-Key', scheme: '' }, // no 'Bearer ' prefix
);
Enter fullscreen mode Exit fullscreen mode

Under the hood. HttpError extends Error with name: 'HttpError', so captureError(error, context) records a real error with a proper name, message and stack rather than an opaque object. The extra fields describe the request without ever reading a body:

Field Meaning
request the request that was issued
response the response, when there was one
isNetworkError the request never reached a server
isTimeout the timeout budget expired
isAbort a caller's AbortSignal aborted it
statusCode response.status, or 0 with no response
attempts attempts made, including the first

The context builder copies an allow-list only: method, URL, status, status text and the timeout budget, with the attempt count added as a tag when there was more than one. Request and response bodies are never copied into an error context. That distinction matters: the client does read response bodies, because that is the point of an HTTP client, but it does not put them in the vault.

This subpath is the one public surface allowed to reject by design. An HTTP client that cannot report a failure is useless. It is walled off from the capture path — nothing in the core, error, storage, sync or export modules imports it — so the library's never-throw guarantee is unaffected. onError is the one-way edge between the two.

Source note. If you already use axios, use the dedicated adapter instead of replacing your client. attachAxios is a response interceptor that classifies, captures and re-throws the original rejection unchanged. The /http client is for a codebase that wants one client it controls, or one place where a fetch failure becomes a record.

Try this now. Count the catch blocks in your codebase that contain exactly one line: captureError(error). Each of those is a candidate for the client's onError. You will probably delete more code than you add.

Teaser. The record exists, the context is good, and the report is readable. The remaining problem is that the message is sitting in IndexedDB in plaintext.

Encryption at rest, without the theatre

Quick version. Redaction is the library's primary privacy control, and it runs before every write. Encryption is the second layer: if someone gets read access to the origin's storage, the fields you chose are unreadable.

The /storage subpath gives you two providers and a repository wrapper.

import { createBase64EncryptionProvider } from '@codewithrajat/rm-logvault/storage';

const provider = createBase64EncryptionProvider();
Enter fullscreen mode Exit fullscreen mode

That first one is encoding, not encryption. It is btoa(encodeURIComponent(value)), and anyone holding the stored value can decode it with atob. It stops a record being readable at a glance in devtools. It provides no confidentiality whatsoever. The name is base64 rather than basic precisely so that reading it in a config file is a warning.

For real encryption, use AES-GCM through the platform's crypto.subtle:

import { createAesGcmEncryptionProvider } from '@codewithrajat/rm-logvault/storage';

// Your own constant. The library never reads import.meta.env or process.env.
const SALT = new Uint8Array([
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
]);

const provider = await createAesGcmEncryptionProvider({
  password: passphrase(),
  // The salt MUST be identical on every load, or previously stored records
  // cannot be decrypted. A build-time constant, never generated at runtime.
  salt: SALT,
});
Enter fullscreen mode Exit fullscreen mode

It returns EncryptionProvider | undefined, and undefined means crypto.subtle is not available — which is every non-secure context, including a plain http: origin. That is a normal outcome on a local development server, so handle it rather than assuming it worked.

Real-world version. createEncryptingRepository takes one repository, not the { errors, logs } pair. You wrap each side and assemble the pair yourself. Both shipped repositories are accepted directly, even though they differ: errors have save and logs have saveBatch.

// src/telemetry-repository.ts
import {
  createErrorRepository,
  createLogRepository,
} from '@codewithrajat/rm-logvault';
import type {
  StorageResult,
  TelemetryRepository,
} from '@codewithrajat/rm-logvault';
import {
  createAesGcmEncryptionProvider,
  createBase64EncryptionProvider,
  createEncryptingRepository,
} from '@codewithrajat/rm-logvault/storage';

const SALT = new Uint8Array([
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
]);

export async function createEncryptedRepository(): Promise<TelemetryRepository> {
  const aes = await createAesGcmEncryptionProvider({
    password: passphrase(),
    salt: SALT,
  });

  // `http://localhost` has no crypto.subtle. In development that is fine; in
  // production it means the page is not a secure context, and silently
  // downgrading would be worse than refusing to start.
  const provider =
    aes ??
    (import.meta.env.DEV
      ? createBase64EncryptionProvider()
      : (() => {
          throw new Error('AES-GCM requires a secure context');
        })());

  // The names `databaseNames(dbPrefix)` would produce. Keeping them in step
  // with `dbPrefix` is what stops you silently starting from an empty vault.
  const rawErrors = createErrorRepository({ dbName: 'rm-logvault-errors' });
  const rawLogs = createLogRepository({ dbName: 'rm-logvault-logs' });

  return {
    errors: createEncryptingRepository(rawErrors, provider, {
      fields: ['message', 'stack', 'componentStack', 'api.url'],
      onDecryptFailure: (field: string, error: unknown) => {
        // Called per field. The stored value is LEFT IN PLACE rather than
        // blanked, so a key rotation shows ciphertext instead of an empty report.
        reportDecryptFailure(field, error);
      },
    }),

    logs: createEncryptingRepository(rawLogs, provider, {
      fields: ['message', 'route'],
    }),

    initialize: async (): Promise<StorageResult<void>> => {
      const errorResult = await rawErrors.initialize();
      const logResult = await rawLogs.initialize();
      // Unusable only if BOTH failed: one working store is still useful.
      if (!errorResult.ok && !logResult.ok) return errorResult;
      return { ok: true, value: undefined };
    },

    close: (): void => {
      rawErrors.close();
      rawLogs.close();
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

Then hand it over at initialisation. setupTelemetry is a narrow subset and does not accept repository, so this one uses initTelemetry with the flat aliases:

// src/telemetry.ts
import { initTelemetry } from '@codewithrajat/rm-logvault';
import { createEncryptedRepository } from './telemetry-repository';

const repository = await createEncryptedRepository();

export const telemetry = initTelemetry({
  appName: 'checkout',
  url: '/telemetry',
  repository,
});
Enter fullscreen mode Exit fullscreen mode

Which fields, and which to leave alone. Encryption changes a field's value, so encrypt what a human reads back and leave what the machinery keys on.

Field Encrypt? Why
message, stack, componentStack Yes the most likely place for a name, an id or a token
api.url Usually paths and query strings carry identifiers
tags values Sometimes but they are what you group and filter by
id, fingerprint No the row key and the grouping key
uploadStatus, timestamp, occurrenceCount No the outbox depends on them

The outbox is the reason. Pending counts and updateUploadStatus pass straight through the wrapper untouched, because they key on id, fingerprint and uploadStatus. Encrypting those would stop records being claimed for upload at all.

Aggregation is unaffected: createErrorRepository.save merges by fingerprint, which is computed on the plaintext record before the wrapper encrypts anything, and the merge spreads the existing stored row so encrypted fields survive.

Source note. fields accepts a plain name ('message') or a dotted path one level deep ('api.url'). Nested paths are cloned on write, so the record you pass is never mutated — which matters, because a by-reference store would otherwise un-encrypt its own vault on the next read.

What it costs.

  • Search. You can no longer search the vault for a message. If your support workflow is "find every record containing order 8842", encrypting message removes that.
  • The report. A support engineer reading a downloaded report needs the key. Decide that deliberately.
  • Derivation. PBKDF2-SHA256 with 250,000 iterations derives the key once, and each value gets a fresh AES operation. A chatty page with a large fields list will feel it.
  • Rotation. A record encrypted under an old key fails to decrypt, keeps its stored value, and calls onDecryptFailure. That is visible and diagnosable rather than silently empty, but it is still unreadable. Plan rotation before you need it.

The honest caveat. AES-GCM here is only as strong as where the key lives. A passphrase that ships in the same bundle as the code protects the database file, not the data from a determined reader of the page. There is no way around that in a browser without a server, and pretending otherwise is the actual bug. Redaction remains the primary control; this is defence in depth. Use it because a devtools screenshot should not be a data incident, not because it makes the browser a safe.

Try this now. Open one stored record in your current vault and read its message. If it contains a customer name, an account number, or a token you did not expect, you have just found the field to encrypt — and the reason the defaults page matters.

Teaser. There is one more kind of "I cannot see it" left: not the record, but the integration itself.

The map, the sinks, and the page that answers "what is it by default?"

Quick version. Three small things make the library easier to hold in your head.

A frozen map of every integration.

import { ADAPTERS, adapterFor, adapterFrameworks } from '@codewithrajat/rm-logvault';

ADAPTERS.map((adapter) => adapter.framework);
// ['react', 'vue', 'angular', 'axios', 'fetch', 'core', 'tanstack-query', 'core', 'core', 'core']

adapterFor('vue')?.entryPoint;
// '@codewithrajat/rm-logvault/vue'

adapterFrameworks();
// ['angular', 'axios', 'core', 'fetch', 'react', 'tanstack-query', 'vue']
Enter fullscreen mode Exit fullscreen mode

This is deliberately not a runtime registry. A Map that each adapter populates at import time reports [] for every adapter the application did not happen to import, which is the wrong answer in the common case. It also costs bundle size for information that is constant at build time. A frozen table is accurate by construction, tree-shakes away when nothing reads it, and is verified against package.json in the test suite.

A way to see what is attached. logger.addSink is still the installation API — it is what drives pre-init replay and the re-entrancy guard. What is new is the ability to ask what is there:

import { getSinkRegistry, logger } from '@codewithrajat/rm-logvault';

logger.addSink({ name: 'overlay', write: (record) => renderOverlay(record) });
logger.addSink({ name: 'remote', write: (record) => queueForShipping(record) });

getSinkRegistry().list().map((entry) => entry.name);
// ['@codewithrajat/rm-logvault-indexeddb', 'overlay', 'remote']

const overlay = getSinkRegistry()
  .list()
  .find((entry) => entry.name === 'overlay');

if (overlay !== undefined) {
  getSinkRegistry().unregister(overlay.key);
}
Enter fullscreen mode Exit fullscreen mode

Keys are ${sink.name ?? 'sink'}#${sequence}, so two sinks that declare the same name do not replace each other. Re-registering an existing key replaces that sink and returns a fresh unsubscribe function; calling the older one afterwards is safe and does not remove the replacement.

A page that answers the question people actually ask. The 1.0.3 documentation adds docs/DEFAULTS.md: one row per option and per environment variable, with three columns — the option, the value in force when the key is absent, and what that value does in practice.

The defaults that surprise people most:

Default What it means
shortcut is installed You opted into nothing, and Ctrl+Shift+Alt+D already downloads a report. Disable it with shortcut: false.
env is off A .env full of VITE_ERROR_TRACKING_* variables does nothing until you pass env: true (or env: 'VITE_').
logs.level is 'warn' logger.info(...) calls are not stored by default.
appName is omitted The field is missing, not empty. A report with no app name cannot be filtered by app.
consoleLevel is undefined Initialising telemetry does not change your console output.
mode is 'local' With no URL, the library makes zero network requests.

The page also lists the options that deliberately have no default — logs.consoleLevel, consent, the before* hooks, onInternalError, getHeaders, onTerminalFailure — because a default there would be a decision the library must not make for you. And it documents the invalid-value rules, including the cases that fall back on purpose: 0 is meaningful for the rate limits and retention, rejected as a mistake for maxRecords and maxPayloadBytes.

Under the hood. The single most useful correction in this release is a documentation defect, not a code change. LOG_LEVEL was documented as console-only in six places. It is not. It sets logs.consoleLevel and is the last fallback for logs.level. So a build that sets only LOG_LEVEL=debug prints and persists debug lines, and LOG_LEVEL=error persists at error rather than at the warn default.

The behaviour was always correct. The docs were wrong. That is the version of a bug that costs the most time, because the code is doing something you have been told it is not doing — and you have no reason to go looking.

The environment layer itself is built so adoption can be incremental: an unset variable is indistinguishable from an absent option, because the layer only ever supplies a value and has no defaults of its own. That is what makes it safe to add one variable at a time.

You can confirm the whole set at runtime instead of trusting a table:

import {
  DEFAULT_OPTIONS,
  getTelemetryStatus,
  resolveOptions,
} from '@codewithrajat/rm-logvault';

console.log(resolveOptions({})); // the full resolved configuration
console.log(DEFAULT_OPTIONS); // the built-in defaults
console.log(getTelemetryStatus()); // what is happening right now
Enter fullscreen mode Exit fullscreen mode

Try this now. Open your .env and pick one variable. Ask: is env: true set in the code that reads it? If not, that variable is not doing anything. This is the single most common "my configuration is ignored" report, and it is answered by one line in the defaults page.

Teaser. Here is the whole thing in one module, plus the answer to the question I asked at the start.

The full integration, and the answer to the question from the top

This is the complete version of the running example, in one place. Every option is optional. The comments matter more than the values.

// src/telemetry.ts
import {
  initTelemetry,
  logger,
  type TelemetryHandle,
} from '@codewithrajat/rm-logvault';
import { createAuthHeaderProvider } from '@codewithrajat/rm-logvault/http';
import { createEncryptedRepository } from './telemetry-repository';

export const auth = createAuthHeaderProvider({
  getToken: () => sessionStore.token,
  refreshToken: async () => (await refreshSession()).token,
  isTokenExpired: (token) => jwtExpiry(token) < Date.now(),
  onUnauthorized: () => router.navigate('/login'),
});

let handle: TelemetryHandle | undefined;

export async function startTelemetry(): Promise<TelemetryHandle> {
  if (handle !== undefined) return handle;

  // Encryption is initialisation-time wiring. The repository must exist
  // before the first capture, so this is not a hook and not an effect.
  const repository = await createEncryptedRepository();

  handle = initTelemetry({
    // Identity. Everything on a record that says which build produced it.
    appName: 'checkout',
    appVersion: '2.4.1',
    buildId: '9c1a2f4',
    environment: 'production',

    // Local by default. Adding a URL is the only thing that turns uploads on.
    url: '/telemetry',
    headers: auth.getHeaders,

    errors: {
      maxRecords: 1000,
      retentionDays: 14,
      maxEventsPerMinute: 120,
      maxRepeatsPerMinute: 12,
      captureResources: true,
      captureCsp: true,
      captureChunkErrors: true,
      beforeCapture: (record) =>
        record.message.includes('ResizeObserver loop') ? null : record,
    },

    logs: {
      level: 'info',
      consoleLevel: 'warn',
      maxRecords: 5000,
      retentionDays: 7,
    },

    redaction: {
      allowedQueryParams: ['page', 'locale'],
    },

    rest: {
      intervalMs: 30_000,
      batchSize: 50,
      onTerminalFailure: (status) => {
        logger.warn(`[Telemetry] batch rejected with status ${String(status)}`);
      },
    },

    shortcut: {
      filenamePrefix: 'checkout-diagnostics',
      allow: () => isInternalUser(),
    },

    // Consent is evaluated before every capture, persist and upload.
    consent: () => hasAnalyticsConsent(),

    onInternalError: (stage, error) => {
      logger.warn(`[Telemetry] internal failure in ${stage}`, error);
    },

    repository,
  });

  // Subscribe AFTER initialisation. `on` is a no-op on a handle whose
  // telemetry is not initialised yet.
  handle.events.on('record:dropped', (event) => {
    if (import.meta.env.DEV) {
      console.debug('[telemetry] dropped', event.reason, event.count);
    }
  });

  return handle;
}
Enter fullscreen mode Exit fullscreen mode
// src/http.ts
import { captureError } from '@codewithrajat/rm-logvault';
import {
  createAuthInterceptor,
  createFetchHttpClient,
} from '@codewithrajat/rm-logvault/http';
import { auth } from './telemetry';

export const http = createFetchHttpClient({
  baseUrl: '/api',
  timeoutMs: 10_000,
  retry: 1,
  onError: (error, context) => {
    captureError(error, context);
  },
});

http.setInterceptors([createAuthInterceptor(auth)]);
Enter fullscreen mode Exit fullscreen mode

Now the question from the top: if your tracker caught an error right now, how would you know?

Before 1.0.3, the honest answer was "I would not, until someone downloaded the report." The record was there; the observation channel was not. There was no supported way to say "tell me when a record is accepted" without polling a snapshot that does not mean what it looks like.

Now there are five answers, and they compose:

  1. events tells your UI the moment a record is accepted, with the fields a badge or a store needs.
  2. onError on the HTTP client turns a failed request into a record at the place the request was made, instead of relying on every caller to remember a catch block.
  3. Context builders make that record say something your application recognises, even when the capture came from a global handler.
  4. The sink registry lets a debug panel list what is attached and detach one sink without restarting the app.
  5. docs/DEFAULTS.md removes the guesswork about what an unset option is doing while you read the report.

The Monday incident now goes differently. The panel shows one new error. The fingerprint is stable. The source is api, not manual, because the HTTP client captured it with its context. The tag says status=502, the page route says /checkout/:id, and the message names the upstream provider. Someone downloads the report, filters it to appName=checkout, and the ninety seconds of guessing are gone.

The one thing most teams get wrong. They treat telemetry as a write-only sink. They audit it when the dashboard is empty, then go back to not looking at it. The release is a reminder that observability is a loop: capture, store, observe, fix. A recorder you cannot observe is a diary you never open, and no amount of storage durability makes up for that.

When this is the wrong tool. If you need session replay, stack traces symbolicated from uploaded source maps, alerting with on-call routing, or a hosted dashboard that somebody else maintains, a hosted SDK will get you there faster. This library captures and stores browser-side failures and hands you a report. 1.0.3 does not change that. It makes the local half better: one-line setup, a live event stream, an HTTP seam, encryption at rest, and documentation that tells you what the defaults are. That list of non-goals is written down in the README rather than left for you to discover.

Bonus tips. One per level.

Beginner: set appName. It is the single highest-value line in the configuration, because IndexedDB is scoped to an origin and several applications on one host share the same two databases. Without it, the report's "Only this app" button has nothing to narrow on.

Intermediate: subscribe to record:dropped and surface it in a development-only panel. A drop is not always a bug — a repeat-limit drop means the failure is already in the report — but a rate-limit drop means records are genuinely missing, and that is worth seeing before a user tells you.

Advanced: use createAuthHeaderProvider for both the HTTP client and rest.headers. One refresh policy, one single-flight guard, one place where a lost session is reported. Two independent refresh implementations is how a page ends up refreshing ten times at once.

Recap.

  • A tracker you cannot observe is a write-only diary. handle.events is the missing observation seam, and it is safe to hand to a UI because a throwing or async listener cannot break a capture.
  • Flat aliases make the configuration short enough to review. setupTelemetry forwards to initTelemetry, so the two are interchangeable and there is no second configuration system.
  • The HTTP client is the place where a failed request stops being a console line and becomes a record with a category, a status and a route. onError is the one-way edge into captureError.
  • Encryption at rest is real AES-GCM when crypto.subtle exists, and Base64 is encoding, not encryption. Encrypt what a human reads; leave the keys the outbox needs.
  • Documentation is a feature when the failure mode is a wrong default you did not know you had. docs/DEFAULTS.md answers "what is it when I did not set it?" for every option and every environment variable.

What did you think? Did this match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.

Found this helpful? If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.

Want more tips like this? I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.

Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.

Follow Me for More Angular & Frontend Goodness:

I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.

  • 💼 LinkedIn — Let’s connect professionally
  • 🎥 Threads — Short-form frontend insights
  • 🐦 X (Twitter) — Developer banter + code snippets
  • 👥 BlueSky — Stay up to date on frontend trends
  • 🌟 GitHub Projects — Explore code in action
  • 🌐 Website — Everything in one place
  • 📚 Medium Blog — Long-form content and deep-dives
  • 💬 Dev Blog — Free Long-form content and deep-dives
  • ✉️ Substack — Weekly frontend stories & curated resources
  • 🧩 Portfolio — Projects, talks, and recognitions
  • ✍️ Hashnode — Developer blog posts & tech discussions
  • ✍️ Reddit — Developer blog posts & tech discussions

Top comments (0)