Frontend tracing for React with OpenTelemetry

The @maple-dev/browser SDK records a span for every fetch and sends traceparent to your API. Hook it into React Router and each click becomes one trace: the navigation, its loaders, their requests and the backend spans behind them.

navigate /projects/:projectId 5 spans · 212ms
DurationStatus
navigate /projects/:projectIdacme-web
212msOk
loader project
196msOk
HTTP GET
188msOk
/api/projects/{id}projects-api
140msOk
SELECT projects
22.0msOk

Example: one navigation from the click to the database

Quick start

Set up React

1

Install the browser SDK

bash
npm install @maple-dev/browser
2

Initialize it, with loader spans and route errors

typescript
// src/maple.ts
import { MapleBrowser } from "@maple-dev/browser"
import {
	type ClientInstrumentation,
	type ClientOnErrorFunction,
	type InstrumentationHandlerResult,
	isRouteErrorResponse,
} from "react-router"

MapleBrowser.init({
	ingestKey: import.meta.env.VITE_MAPLE_INGEST_KEY, // public key, maple_pk_...
	serviceName: "acme-web",
	environment: import.meta.env.MODE,
	tracing: {
		// APIs on another origin that should receive `traceparent`
		propagateTraceHeaderCorsUrls: [/^https:\/\/api\.acme\.com\//],
	},
})

// A span for every loader and action, under the open navigation
export const mapleInstrumentation: ClientInstrumentation = {
	route(route) {
		route.instrument({
			loader: (callLoader) => traceHandler(`loader ${route.id}`, callLoader),
			action: (callAction) => traceHandler(`action ${route.id}`, callAction),
		})
	},
}

async function traceHandler(name: string, call: () => Promise<InstrumentationHandlerResult>) {
	// The first page's loaders start before the page load opens: wait one tick to nest under it
	await Promise.resolve()
	return MapleBrowser.traced(name, async () => {
		const result = await call()
		// A navigation that was superseded aborts its loaders: not a failure
		if (result.status === "error" && result.error.name !== "AbortError") throw result.error
	}).catch(() => {}) // recorded on the span; React Router still handles the error
}

// Errors React Router catches for your ErrorBoundary
export const reportRouteError: ClientOnErrorFunction = (error, { pattern }) => {
	if (isRouteErrorResponse(error)) return // thrown responses: 404s, redirects
	MapleBrowser.captureException(error, { name: "react_router.error", attributes: { "app.route": pattern } })
}
3

Pass the instrumentation to the router

typescript
// src/router.tsx
import { createBrowserRouter } from "react-router"
import { fetchProject, ProjectPage, RootLayout } from "./app"
import { mapleInstrumentation } from "./maple"

export const router = createBrowserRouter(
	[
		{
			path: "/",
			Component: RootLayout,
			children: [
				{
					// Loader spans are named after the route id, so give routes with loaders a readable one
					id: "project",
					path: "projects/:projectId",
					loader: ({ params }) => fetchProject(params.projectId!),
					Component: ProjectPage,
				},
			],
		},
	],
	{ instrumentations: [mapleInstrumentation] },
)
4

Trace navigations from the entry

typescript
// src/main.tsx
import "./maple" // first, before anything renders
import { instrumentReactRouter } from "@maple-dev/browser/react"
import { createRoot } from "react-dom/client"
import { RouterProvider } from "react-router/dom"
import { reportRouteError } from "./maple"
import { router } from "./router"

instrumentReactRouter(router)

createRoot(document.getElementById("root")!).render(<RouterProvider router={router} onError={reportRouteError} />)

This is the short path. The full React guide covers the rest.

Organization in the EU region? Pass region: "eu" to MapleBrowser.init. An ingest key only works in its own region.

What you get

What a React app sends to Maple

Navigations by route pattern

pageload /projects/:projectId for the first route, navigate /projects/:projectId after it. The concrete path is in url.path.

Loader and action spans

Each loader and action runs in its own span under the navigation. A thrown Error marks it failed; a thrown redirect does not.

fetch and XMLHttpRequest

Every request is a span. Requests to your own APIs carry traceparent, so the backend's spans join the browser's trace.

Route errors

Errors React Router catches for your ErrorBoundary are reported through onError, once each, with the route pattern attached.

Uncaught errors

init() records uncaught errors and unhandled rejections from outside the router.

Session replay

init() also starts session replay, so a slow navigation can be watched from the user's side.

What is different in the browser

CORS has to allow traceparent

An API on another origin must list traceparent in Access-Control-Allow-Headers, or the browser blocks the request. List only your own APIs in propagateTraceHeaderCorsUrls.

No async context

Only requests a loader starts before its first await nest under its span. Start independent requests together with Promise.all.

Another router?

This is data mode in React Router 7.15 and later. Framework mode, TanStack Router and hand-rolled routers each have a guide in the frontend docs.

통합

다른 통합

오늘 첫 트레이스를 확인하세요.

SDK를 추가하고 OTLP 익스포터를 Maple로 향하게 하면 트레이스가 도착합니다.

maple.dev: OpenTelemetry 위의 옵저버빌리티