Skip to Content
Xeonr Developer Docs

Browsers and React

Report a web app's errors, failed requests, web vitals and spans to Lantern with @lntrn/web, upload source maps so its stacks read as source, and send from React Native with a device token.

A web page can't keep a secret, so it sends with none. @lntrn/web posts to Lantern's client ingest, https://in.lntrn.dev. The ingest accepts the records only for a client project whose public-origin key lists the page's origin. React Native, which has no origin to check, sends with a short-lived device token instead (below).

Already on OpenTelemetry? Add this

An app on the OpenTelemetry web SDK keeps it, and adds @lntrn/web/otel. Set up a client project first, as in Before you start. The add-on gives the stock providers everything init() has:

  • exporters that send without a credential, checked against the page's origin, buffer offline and flush with sendBeacon when the page is hidden;
  • a processor that stamps session.id and url.path on every span and record;
  • instrumentations for uncaught errors (with breadcrumbs) and web vitals;
  • CLIENT spans and client.request.failed records for fetch and Connect calls, from the global tracer.
npm install @lntrn/web @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/sdk-logs @opentelemetry/resources @opentelemetry/instrumentation
import { logs, trace } from "@opentelemetry/api";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
import { LoggerProvider, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { LanternWeb } from "@lntrn/web/otel";
import { wrapFetch } from "@lntrn/web";
import { telemetryInterceptor } from "@lntrn/web/connect";

const lantern = new LanternWeb({ service: "checkout-web", product: "checkout" });
const resource = resourceFromAttributes(lantern.resourceAttributes());

trace.setGlobalTracerProvider(new TracerProvider({
  resource,
  spanProcessors: [lantern.processor, new SimpleSpanProcessor({ exporter: lantern.spanExporter })],
}));
logs.setGlobalLoggerProvider(new LoggerProvider({
  resource,
  processors: [lantern.processor, new SimpleLogRecordProcessor({ exporter: lantern.logRecordExporter })],
}));
registerInstrumentations({ instrumentations: lantern.instrumentations() });

export const api = wrapFetch(fetch, lantern);           // requests as CLIENT spans
const interceptors = [telemetryInterceptor(lantern)];    // Connect calls, the same

Notes on this setup:

  • Processors: Lantern's exporters queue and batch themselves, so use the Simple processors in front of them, not the batching ones.
  • Routes: call lantern.trackRoute(path) on every route change, for url.path and the breadcrumb trail.
  • React: <TelemetryErrorBoundary client={lantern}> reports render errors through it.
  • Dependencies: @lntrn/web/otel imports only @opentelemetry/api at runtime, and init() stays free of the SDK.

Or use the stock exporters as they are. The client ingest speaks plain OTLP/HTTP, so a stock exporter works on its own:

new OTLPTraceExporter({ url: "https://in.lntrn.dev/v1/traces?service=checkout-web" });

The page's origin must be on the project's public-origin key, and the ingest answers the CORS preflight. You get none of the above.

Before you start

In your organisation's console, https://<org>.lntrn.dev, as an editor:

  1. Client projects → New. Give it a name, a service name (checkout-web; it is the service.name of everything the project receives), an environment and a retention class.
  2. In the project's Keys, add a Public origin key and list every origin the app is served from, exactly as the browser sends it: scheme, host and port, no path. For example https://app.example.com, or http://localhost:5173 while developing. One wildcard form is accepted, for apps served on many subdomains: https://*.example.com matches any single label in front of example.com (https://eu.example.com), but not https://example.com itself or https://a.b.example.com. The scheme and port still match exactly.
  3. If you will upload source maps from CI, add a Release (CI) key too. Its secret is shown once; store it as a CI secret, LANTERN_RELEASE_KEY.

Checked with @lntrn/web 0.4.0 and @lntrn/device 1.3.0, and with OpenTelemetry's sdk-trace and sdk-logs 3.0. @lntrn/web was published as @xeonr/telemetry-web up to 0.2.2, with the same API.

Install and start

npm install @lntrn/web
import { init } from "@lntrn/web";

init({
  service: "checkout-web", // the client project's service name
  product: "checkout",     // service.namespace
  // release:  default <meta name="lantern-release">, else "dev"
  // enabled:  default on, except on localhost, *.localhost and *.test
});

Call it once, as early as the page starts. A second call returns the first client. Nothing the SDK does throws into your page, and it never reports its own requests.

To try it on a development server, pass enabled: true and make sure that origin is on the key's list.

What it sends

RecordWhen
An exception (error)an uncaught error or unhandled rejection, a React error boundary, captureException
client.request.failed (warn)a request through wrapFetch or the Connect interceptor that timed out, got no answer, or failed server-side
web_vital (info)LCP, INP, CLS, FCP and TTFB, as the page is hidden
page_view, route_change (info)the page loading, and trackRoute(path)
A client spanevery request through wrapFetch or the interceptor

Exceptions carry exception.type, exception.message and exception.stacktrace, plus the route and the last 20 breadcrumbs. Lantern groups them into Issues. Messages lose query strings, email addresses and bearer-looking strings before they leave the page.

Every record carries:

  • session.id, one per tab;
  • service.instance.id, one per browser install.

Records are batched every 5 seconds. A batch that cannot be sent is kept in localStorage and sent on the next page load. Whatever is left when the page is hidden goes by sendBeacon.

Errors you catch

import { captureException } from "@lntrn/web";

try {
  await placeOrder();
} catch (err) {
  captureException(err, { extra: { "order.step": "payment" } });
  throw err;
}

Records of your own

The client has no general-purpose logger. For things you want to find later, send an event:

import { getClient } from "@lntrn/web";

getClient()?.event("checkout.completed", { "order.items": 3 });
getClient()?.event("checkout.retry", { "order.step": "payment" }, { severity: "WARN", body: "payment retried" });

Attributes other than OpenTelemetry's own (url.*, http.*, exception.* and the like) are kept only if the client project declares them as fields. An undeclared one is dropped and counted, never refused (see Custom fields).

React

import { TelemetryErrorBoundary } from "@lntrn/web/react";

<TelemetryErrorBoundary
  resetKeys={[location.pathname]}
  fallback={({ traceId, reset }) => <ErrorPage traceId={traceId} onRetry={reset} />}
>
  <App />
</TelemetryErrorBoundary>;

The boundary reports what it catches, with React's component stack, and renders the fallback. Tell the SDK when the route changes, so records carry the route the user was on:

import { trackRoute } from "@lntrn/web";

useEffect(() => trackRoute(location.pathname), [location.pathname]);

Requests and traces

import { wrapFetch } from "@lntrn/web";

const api = wrapFetch(); // the global fetch, instrumented
await api("/api/orders");

For ConnectRPC, put the interceptor first, so it times what the others do:

import { createConnectTransport } from "@connectrpc/connect-web";
import { telemetryInterceptor } from "@lntrn/web/connect";

const transport = createConnectTransport({
  baseUrl: "https://api.example.com",
  interceptors: [telemetryInterceptor()],
});

Each request becomes a client span. A same-origin request also carries a W3C traceparent header. If your backend sends its own traces to Lantern (see Server telemetry), the browser span then heads the server's trace. A cross-origin API gets the header only when you ask, and its CORS policy must allow traceparent first:

init({
  service: "checkout-web",
  getTraceHeaders: (url, { traceparent }) =>
    url.hostname === "api.example.com" ? { traceparent } : undefined,
});

Source maps

Production bundles are minified, so their stack traces name nothing useful until Lantern has the release's source maps. With Vite, the plugin does all of it:

vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { lanternTelemetry } from "@lntrn/web/vite";

export default defineConfig({
  plugins: [react(), lanternTelemetry({ service: "checkout-web" })],
});

On vite build it:

  1. writes <meta name="lantern-service"> and <meta name="lantern-release"> into index.html, so init needs neither option. The release is VERSION, else VITE_APP_VERSION, else dev;
  2. builds with sourcemap: "hidden": maps are written, and no bundle links to them;
  3. with LANTERN_RELEASE_KEY set, registers the release and uploads every map, keyed by the file it belongs to;
  4. deletes the .map files from the output, so they are never served.
VERSION=1.4.2 LANTERN_RELEASE_KEY=… npm run build

Lantern applies the maps when it shows a stack, so a map uploaded after the error still works. A failed upload warns and never fails the build. The release stays dev, and nothing is uploaded, until VERSION is set.

From @lntrn/web 0.3.2 the release key always wins: when LANTERN_RELEASE_KEY is set, the plugin sends it from any CI, GitLab included. Without it, the plugin sends a GitLab job's CI_JOB_TOKEN only on Xeonr's own GitLab (git.prod.wtf), the only instance Lantern accepts job tokens from. On 0.3.1 and earlier, a GitLab job's token was sent instead of the key, so on another GitLab either upgrade or build with env -u CI_JOB_TOKEN.

Without Vite, build with hidden source maps and upload them yourself, with the release key as a bearer:

curl -fsS https://in.lntrn.dev/v1/releases \
  -H "authorization: Bearer $LANTERN_RELEASE_KEY" -H 'content-type: application/json' \
  -d '{"service":"checkout-web","version":"1.4.2"}'

# once per map; path is the .js file it belongs to, relative to the site root
gzip -c dist/assets/index-3f9a.js.map | curl -fsS --data-binary @- \
  "https://in.lntrn.dev/v1/sourcemaps?service=checkout-web&release=1.4.2&path=assets/index-3f9a.js" \
  -H "authorization: Bearer $LANTERN_RELEASE_KEY" \
  -H 'content-type: application/json' -H 'content-encoding: gzip'

The release on the records must match the one the maps were uploaded under, so pass the same version to init({ release }).

React Native

@lntrn/web needs a browser, so React Native uses the device SDK, @lntrn/device, which has no dependencies and runs on React Native as it is. A device cannot hold a credential either. Your backend mints it a short-lived device token from a Device secret key on the client project (see Authentication), and the app asks for a fresh one whenever it needs to:

npm install @lntrn/device
import { Lantern } from "@lntrn/device";

export const lantern = new Lantern({
  token: async () => (await api.telemetryToken()).token, // your endpoint, which calls mintToken
  release: "1.4.2",
});

lantern.info("app started");
lantern.event("checkout_completed", { plan: "pro" });
lantern.metric("cold_start_ms", 840);

captureErrors() hooks the browser's and Node's global error events, and React Native has neither. Use its own global handler instead:

const previous = ErrorUtils.getGlobalHandler();
ErrorUtils.setGlobalHandler((error, isFatal) => {
  lantern.error(error);
  void lantern.flush();
  previous(error, isFatal);
});

The full API is on Devices.

An app already on the OpenTelemetry JS SDK keeps it. Give the stock exporters headers: deviceTokenHeaders(() => api.telemetryToken()) from @lntrn/device/otel (see Devices).

Release builds on Hermes report stack frames as bytecode offsets in the bundle (address at index.android.bundle:1:9876). Lantern maps them with the Hermes source map your build composes. Upload it with the request above, keyed by the bundle's file name: path=index.android.bundle on Android, path=main.jsbundle on iOS.

Verify

Load a page of the app (or start the app), then open Client projects → your project in the console. Its records today should be climbing. To check errors, throw one from the browser console with setTimeout(() => { throw new Error("lantern test") }); it appears under Issues within a minute. From a terminal:

lntrn --org <org> query logs 'service.name:checkout-web' --since 15m

If nothing arrives, open the browser's network panel and look at the requests to in.lntrn.dev:

  • no requests at all: the SDK is disabled. Is it on localhost without enabled: true, or did init get no service?
  • 403: the page's origin is not on the public-origin key's list. Compare the request's Origin header with it, character for character.
  • 401 on a device: the token was refused, and the response says why (see Authentication).

On this page