---
url: https://lit-ui-router.dev/guides/tracing.md
description: >-
  Trace UI-Router transitions in production with OpenTelemetry: wiring
  OtelPlugin, privacy and param redaction, active spans across resolves and
  hooks, and shipping to an OTLP backend or the devtools Timeline
---

# Tracing Transitions

Once an app ships, slow resolves, failing route guards, and redirect loops happen
in users' browsers rather than your own tab.
[`ui-router-otel`](/packages/ui-router-otel) reports every `@uirouter/core`
transition as [OpenTelemetry](https://opentelemetry.io) spans — one span per
transition, with child spans for phases and, when opted in, resolves and lazy
loads — on the tracer provider your app already owns.

## Devtools vs. OpenTelemetry

Both [`ui-router-devtools`](/packages/ui-router-devtools) and
[`ui-router-otel`](/packages/ui-router-otel) observe a `@uirouter/core` router
through the same internal event adapter, and neither package depends on the
other. They serve different stages of the app's lifecycle:

* **`ui-router-devtools`** is development tooling for inspecting a single
  session while you build: an in-page panel (state map, transition log, views,
  and Timeline), console and browser Performance reporters, and exportable
  session files.
* **`ui-router-otel`** is production telemetry for understanding what routing
  does across real users: it ships no UI and no exporter, reads neither `window`
  nor `document`, and attaches to headless routers as well as browser ones.

You can use both together during development so spans from your OpenTelemetry
provider appear directly inside the devtools Timeline; see
[Pairing with the devtools Timeline](#pairing-with-the-devtools-timeline).

## Wiring `OtelPlugin` to a `TracerProvider`

Install `ui-router-otel` alongside `@opentelemetry/api` (plus the OpenTelemetry
SDK and exporter packages your app uses):

```bash
npm install ui-router-otel @opentelemetry/api
```

`ui-router-otel` peers only on `@uirouter/core` and `@opentelemetry/api`. Your
app owns the `TracerProvider`, its span processors, its context manager, and its
exporter; `OtelPlugin` takes a `Tracer` and starts every span on it:

```ts check
import { trace } from '@opentelemetry/api';
import type { UIRouter } from '@uirouter/core';
import { OtelPlugin } from 'ui-router-otel';

declare const router: UIRouter;

const otel = router.plugin(OtelPlugin, {
  tracer: trace.getTracer('my-app'),
  redaction: {
    params: ['folderId'],
    messages: false,
  },
});

// Later, when tearing down the router or disabling tracing:
otel.dispose();
```

Register `OtelPlugin` before calling `router.urlService.listen()` and
`router.urlService.sync()` so the initial navigation is traced too.
`otel.dispose()` ends any open spans and unregisters the plugin's listeners;
`router.dispose()` disposes it automatically.

## Privacy and redaction

Route parameters and thrown error messages routinely carry user data — email
addresses, search queries, session tokens, account identifiers, or raw server
error responses. By default, `OtelPlugin` uses
`redaction: { params: [], messages: true }`. Configure both fields explicitly
before shipping traces outside the browser:

```ts check
import { trace } from '@opentelemetry/api';
import type { UIRouter } from '@uirouter/core';
import { OtelPlugin } from 'ui-router-otel';

declare const router: UIRouter;

router.plugin(OtelPlugin, {
  tracer: trace.getTracer('my-app'),
  redaction: {
    // Only allowlisted param keys become attributes; all others are omitted.
    params: ['folderId', 'tab'],
    // Keep free-text error messages out of span status and exception events.
    messages: false,
  },
});
```

* **Param allowlist (`redaction.params`).** Only the keys listed in `params`
  (or `'all'`, suitable only for local development or sanitized environments)
  are written as `uirouter.transition.param.<key>` attributes. List parameters
  are emitted as string arrays.
* **Omitted rather than placeholder-redacted.** A
  [`ui-router-devtools` session export](/packages/ui-router-devtools#session-files-and-redaction)
  keeps every unlisted param key with `[redacted]` as its value so a developer
  inspecting the file can see which params a transition carried. `ui-router-otel`
  drops unlisted params instead: emitting placeholder attributes adds storage
  and cardinality to your tracing backend while telling nobody anything beyond
  the param's name.
* **Error messages (`redaction.messages`).** Messages come from arbitrary
  errors thrown in hooks and resolves and can embed emails, IDs, or upstream
  payloads. Set `messages: false` whenever traces leave the browser; that omits
  the message from the span's status description and suppresses its `exception`
  event.
* **What always stays.** Span names never include parameter values or URLs. Even
  with `params: []` and `messages: false`, `error.type` (the thrown `Error`'s
  `name`, `_OTHER`, or `invalid`) stays on failed transitions, resolves, and
  lazy loads, and `uirouter.transition.invalid_params` stays on invalid
  transitions — those names come from your state declarations rather than user
  data, and an invalid transition is otherwise impossible to diagnose.

## Active spans and context propagation

By default, `OtelPlugin` emits transition and phase spans (and, with
`timeResolves: true`, passive resolve timing spans) without making them the
active OpenTelemetry span. That default avoids wrapping `@uirouter/core`
callbacks and state objects.

When you want spans started by your own code — such as an instrumented `fetch()`
or a manual `tracer.startActiveSpan(...)` — to become children of the router
span that triggered them, opt into any combination of the three active-span
options:

* **`activateResolveSpans`** runs each resolve function with its
  `resolve <token>` span active. It spans resolves itself, so `timeResolves` is
  redundant alongside it (and enabling both never double-spans).
* **`activateHookSpans`** runs each app-registered transition hook (on
  `transitionService`, on individual transitions, and state `onEnter`, `onExit`,
  and `onRetain` callbacks) with its phase span active — for example `before` or
  `enter users`. Core's own internal hooks (including state `redirectTo`),
  `onCreate` hooks, and instrumentation hooks at `±Number.MAX_SAFE_INTEGER` are
  left untouched. Because an `onBefore` hook runs before core checks whether a
  transition is a no-op, a transition whose `onBefore` hook ran with an active
  span is still reported with outcome `ignored` so child spans keep their
  parent.
* **`activateLazyLoadSpans`** runs each state's `lazyLoad` callback with a
  `lazy load <state>` span active.

How far an active span propagates into your code depends on the OpenTelemetry
context manager your app installs. `OtelPlugin` installs none:

| Context manager                                                                                                                                              | Span stays active for                                                                                                                       |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| None (default `@opentelemetry/api` no-op manager)                                                                                                            | Nothing: `context.active()` stays empty, so spans started inside resolves, hooks, or lazy loads start separate traces                       |
| Synchronous stack manager (`StackContextManager` from `@opentelemetry/sdk-trace`)                                                                            | Only synchronous code before the first `await`: a `fetch()` called before the first `await` is a child; one started after an `await` is not |
| Async-aware manager (`@opentelemetry/context-zone` in browsers; `AsyncLocalStorageContextManager` from `@opentelemetry/context-async-hooks` on Node/servers) | The entire async callback, across `await` boundaries                                                                                        |

```ts check
import { context, trace } from '@opentelemetry/api';
import { StackContextManager, TracerProvider } from '@opentelemetry/sdk-trace';
import type { UIRouter } from '@uirouter/core';
import { OtelPlugin } from 'ui-router-otel';

declare const router: UIRouter;

const provider = new TracerProvider();
context.setGlobalContextManager(new StackContextManager().enable());
trace.setGlobalTracerProvider(provider);

router.plugin(OtelPlugin, {
  tracer: trace.getTracer('my-app'),
  activateResolveSpans: true,
  activateHookSpans: true,
  activateLazyLoadSpans: true,
});
```

If your resolves or hooks perform work after an `await` and you want those
follow-up spans nested under the same router span in the browser, register
`ZoneContextManager` from `@opentelemetry/context-zone` instead of
`StackContextManager` (or `AsyncLocalStorageContextManager` on Node). The sample
app's
[`telemetry.ts`](https://github.com/simshanith/lit-ui-router/blob/main/apps/sample-app-shared/src/app/global/telemetry.ts)
uses `StackContextManager` with `activateResolveSpans: true` so resolves that
kick off their requests before the first `await` nest cleanly without adding
`zone.js` to the bundle.

## Shipping spans to a trace backend

Because `OtelPlugin` produces ordinary OpenTelemetry spans, you ship them with
any standard OTLP/HTTP exporter — Honeycomb, Grafana Tempo, Jaeger, or your own
OpenTelemetry Collector — paired with `BatchSpanProcessor`:

```ts check
import { context, trace } from '@opentelemetry/api';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import {
  defaultResource,
  resourceFromAttributes,
} from '@opentelemetry/resources';
import {
  BatchSpanProcessor,
  StackContextManager,
  TracerProvider,
} from '@opentelemetry/sdk-trace';
import type { UIRouter } from '@uirouter/core';
import { OtelPlugin } from 'ui-router-otel';

declare const router: UIRouter;
declare const ingestKey: string;

const provider = new TracerProvider({
  resource: defaultResource().merge(
    resourceFromAttributes({ 'service.name': 'my-web-app' }),
  ),
  spanProcessors: [
    new BatchSpanProcessor({
      exporter: new OTLPTraceExporter({
        // Point at your collector or vendor OTLP/HTTP endpoint, e.g.
        // 'https://api.honeycomb.io/v1/traces' or 'http://localhost:4318/v1/traces'.
        url: 'https://api.honeycomb.io/v1/traces',
        headers: {
          'x-honeycomb-team': ingestKey,
        },
      }),
    }),
  ],
});

context.setGlobalContextManager(new StackContextManager().enable());
trace.setGlobalTracerProvider(provider);

router.plugin(OtelPlugin, {
  tracer: trace.getTracer('my-web-app'),
  activateResolveSpans: true,
  redaction: {
    params: ['folderId'],
    messages: false,
  },
});
```

Two browser details matter when exporting directly from pages:

* **CORS and ingest keys.** Any OTLP/HTTP receiver accepting browser traffic
  must allow the page's origin (`Access-Control-Allow-Origin` and preflight
  `OPTIONS` for `Content-Type` and any custom headers). Because browser request
  headers are visible to anyone inspecting the network tab, either send traces
  through a same-origin collector proxy or use a write-only ingest key scoped to
  trace submission.
* **Unloads and teardown.** In browsers, `BatchSpanProcessor` flushes when the
  page is hidden and `OTLPTraceExporter` sends with `keepalive` where supported.
  When tearing down a router in tests or embedded widgets, call
  `provider.shutdown()` (or `provider.forceFlush()`) after `router.dispose()`.

For a working example that loads the OTLP exporter lazily only when an endpoint
is configured, see
[`apps/sample-app-shared/src/app/global/otlpExport.ts`](https://github.com/simshanith/lit-ui-router/blob/main/apps/sample-app-shared/src/app/global/otlpExport.ts)
and
[`telemetry.ts`](https://github.com/simshanith/lit-ui-router/blob/main/apps/sample-app-shared/src/app/global/telemetry.ts).

## Pairing with the devtools Timeline

In development, you can feed the [`ui-router-devtools`](/packages/ui-router-devtools#timeline)
Timeline from the same `TracerProvider` by adding `DevtoolsSpanProcessor` beside
(or instead of) your OTLP processor:

```ts check
import { context, trace } from '@opentelemetry/api';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import {
  BatchSpanProcessor,
  StackContextManager,
  TracerProvider,
} from '@opentelemetry/sdk-trace';
import type { UIRouter } from '@uirouter/core';
import {
  DevtoolsSpanProcessor,
  OtelPlugin,
  type SpanSink,
} from 'ui-router-otel';

declare const router: UIRouter;
declare const exportUrl: string | undefined;

const provider = new TracerProvider({
  spanProcessors: [
    new DevtoolsSpanProcessor(() =>
      document.querySelector<HTMLElement & SpanSink>('ui-router-devtools'),
    ),
    ...(exportUrl
      ? [
          new BatchSpanProcessor({
            exporter: new OTLPTraceExporter({ url: exportUrl }),
          }),
        ]
      : []),
  ],
});

context.setGlobalContextManager(new StackContextManager().enable());
trace.setGlobalTracerProvider(provider);

router.plugin(OtelPlugin, {
  tracer: trace.getTracer('my-web-app'),
  activateResolveSpans: true,
  // Scrub free-text error messages whenever spans also leave the browser.
  ...(exportUrl && { redaction: { messages: false } }),
});
```

`DevtoolsSpanProcessor` calls its sink getter on each span, so the
`<ui-router-devtools>` element can be mounted lazily after the provider starts;
spans with no mounted panel are dropped harmlessly. Add `DevtoolsSpanProcessor`
to the same provider that supplies `OtelPlugin`'s tracer so the router's spans
and your app's spans reach the Timeline together.

The two views complement each other: the devtools Timeline focuses on one
transition at a time with its redirect chain, phases, resolves, and joined
spans, whereas an OTLP trace viewer supports search, attribute filtering,
latency percentiles, and server-side span correlation across every trace.

## Querying transition traces

A transition trace is structured for filtering in any OpenTelemetry backend:

* **One span per transition**, named after the target state (never a raw URL or
  parameter value), with child spans for lifecycle phases, resolves (when
  `timeResolves` or `activateResolveSpans` is enabled), and lazy loads (when
  `activateLazyLoadSpans` is enabled).
* **Normal control flow vs. real failures.** Redirects, supersedes, and aborts
  are expected routing outcomes and leave span status `UNSET`. Only thrown
  errors and invalid transitions (or invalid targets) set span status `ERROR`
  and record `error.type`. Filtering on error status or `error.type` surfaces
  real failures without noise from users clicking a second link mid-transition.
* **Redirect and supersede links.** A redirect's successor carries an
  OpenTelemetry span link back to the transition it replaced, and a superseded
  transition links forward to the transition that superseded it, letting you
  follow auth-guard redirects and interrupted navigations across traces.
* **Consistent transition attributes.** Attributes describing the transition sit
  under the `uirouter.transition.*` prefix — including on `invalid target`
  spans, so querying by destination state also catches typos in
  `stateService.go()`.

For the full span hierarchy, `uirouter.*` attribute list, and outcome status
table, see [`ui-router-otel` — Spans](/packages/ui-router-otel#spans) and the
[`ui-router-otel` API reference](/reference/ui-router-otel/).

## Current scope

`ui-router-otel` traces transitions on any `@uirouter/core` router today,
including headless ones, but server-side transitions, SSR rendering, and trace
continuity from a server-rendered response into the first client transition are
tracked in
[issue #2098](https://github.com/simshanith/lit-ui-router/issues/2098). See
[Not covered](/packages/ui-router-otel#not-covered) for the remaining
boundaries.
