Skip to Content

TanStack Start

Send traces, logs, metrics, errors, and profiles from a TanStack Start app to Everr, with route templates and server functions on both sides. Hand the setup to your agent, or wire it up yourself.

Sendstraceslogsmetricserrorsprofiles

This guide shows you how to send traces, logs, metrics, and errors from your TanStack Start app to Everr, from both the server and the browser. You'll use the OpenTelemetry Node SDK on the server, @everr/tanstack-start-otel for Start's requests and server functions, and @everr/otel-web in the browser.

Once it's set up, you get:

  • A span for every request, named after its route, such as GET /blog/$slug
  • A span for every server function call, such as serverFn getPost
  • Errors from server functions, failed requests, and crashes, grouped by where they happened
  • One trace from a click in the browser all the way to your database

Prerequisites

  • A TanStack Start app running on Node.js
  • The Everr CLI, with the local collector running (everr local start)
  • A public key for browser telemetry, if you plan to send it to Everr Cloud (see Browser telemetry)

Let your agent wire it up

/everr-setup-telemetry Instrument this TanStack Start app, server and browser, and send traces, logs, metrics, and errors to Everr

The Agent sets up both the server and the browser, then checks in your local collector that their spans share a trace.

Wire it up by hand

Step 1. Install the packages

npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @everr/otel-errors @everr/tanstack-start-otel @everr/otel-web

Step 2. Start the Node SDK

Create src/telemetry/node.ts:

src/telemetry/node.ts
import { ErrorsInstrumentation } from "@everr/otel-errors";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { NodeSDK } from "@opentelemetry/sdk-node";

// `vite dev` re-evaluates this module on reload, so start the SDK once per process.
const state = globalThis as { __acmeTelemetry?: NodeSDK };

if (!state.__acmeTelemetry) {
  const sdk = new NodeSDK({
    serviceName: "acme-server",
    instrumentations: [
      new ErrorsInstrumentation(),
      getNodeAutoInstrumentations({
        "@opentelemetry/instrumentation-fs": { enabled: false },
        // The Start middleware creates the request span instead.
        "@opentelemetry/instrumentation-http": { disableIncomingRequestInstrumentation: true },
      }),
    ],
  });
  sdk.start();
  state.__acmeTelemetry = sdk;
  process.once("SIGTERM", () => void sdk.shutdown());
}

Replace acme-server with a name that identifies your server.

Then import it at the top of your server entry, so it loads before the code it instruments. If your app doesn't have a src/server.ts yet, create one:

src/server.ts
import "./telemetry/node";
import handler, { createServerEntry } from "@tanstack/react-start/server-entry";

export default createServerEntry({
  fetch(request) {
    return handler.fetch(request);
  },
});

Step 3. Add the Start middlewares

Register the request and server function middlewares on your start instance:

src/start.ts
import {
  createRequestTelemetryMiddleware,
  createServerFnTelemetryMiddleware,
  type RouterLike,
} from "@everr/tanstack-start-otel";
import { createCsrfMiddleware, createStart } from "@tanstack/react-start";
import { getRouter } from "./router";
import { isExpectedError } from "./telemetry/expected-errors";

export const startInstance = createStart(() => ({
  requestMiddleware: [
    createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === "serverFn" }),
    createRequestTelemetryMiddleware({ router: (): RouterLike => getRouter() }),
  ],
  functionMiddleware: [createServerFnTelemetryMiddleware({ isExpectedError })],
}));

Once your app has a src/start.ts, Start no longer adds its CSRF protection for you, so keep createCsrfMiddleware() in the list. Its filter limits the check to server functions, as in Start's middleware guide: without it, opening a page from a bookmark or the address bar returns 403. Pass your app's own getRouter too, rather than creating a new router, because the server shares one route tree across the whole process.

isExpectedError tells the middleware which thrown values are normal control flow, like redirect() and notFound(), so they don't show up as errors. Add any routine failures of your own to the list:

src/telemetry/expected-errors.ts
import { isNotFound, isRedirect } from "@tanstack/react-router";

const EXPECTED = new Set(["Unauthenticated"]);

export function isExpectedError(error: unknown): boolean {
  return (
    isRedirect(error) ||
    isNotFound(error) ||
    (error instanceof Error && EXPECTED.has(error.message))
  );
}

Step 4. Add the browser SDK

Create src/telemetry/client.ts:

src/telemetry/client.ts
import { errors, interactions, network, pageviews, performance, WebSDK } from "@everr/otel-web";

new WebSDK({
  serviceName: "acme-web",
  // In development the SDK sends to the local collector. A key sends to Everr Cloud instead.
  dev: import.meta.env.DEV,
  ingestKey: import.meta.env.PROD ? import.meta.env.VITE_EVERR_PUBLIC_INGEST_KEY : undefined,
  instrumentations: [errors(), pageviews(), interactions(), performance(), network()],
});

Give the browser its own service name, so you can query it separately from the server.

Import it at the top of your root route, so it starts as early as possible and catches errors while the app boots:

src/routes/__root.tsx
import "../telemetry/client";

Then register your router with the SDK, so page views and browser errors carry the route (/blog/$slug) instead of the full path. Records captured before the router exists, like the first page view, get their route when they're sent.

src/router.tsx
import { setRouteResolver } from "@everr/otel-web";
import { routeTemplate } from "@everr/tanstack-start-otel";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";

export function getRouter() {
  const router = createRouter({ routeTree });
  setRouteResolver({ page: (url) => routeTemplate(router, new URL(url).pathname) });
  return router;
}

network() connects each fetch to the server span that answers it, and names it after the server's route, so fetch("/api/orders/42") appears as GET /api/orders/$id.

Step 5. Configure the endpoint

For local development, set the otlp: URL from everr local status. The browser SDK already sends to the local collector, because of dev: import.meta.env.DEV in step 4.

.env
OTEL_EXPORTER_OTLP_ENDPOINT=<otlp-url-from-status>
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development

For production, use an API key with the Send telemetry capability for the server (see Production telemetry), and your public key for the browser:

.env
OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.everr.dev
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer%20<your-api-key>
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production
VITE_EVERR_PUBLIC_INGEST_KEY=<your-public-key>

Only the public key belongs in a VITE_ variable. Vite includes those in the browser bundle, so keep the API key in your server's environment.

Validate

  1. Start your app and open a page that calls a server function.
  2. Look for traces that contain spans from both the browser and the server:
everr local query "SELECT TraceId, groupUniqArray(SpanName) AS spans FROM traces WHERE ServiceName IN ('acme-web', 'acme-server') AND Timestamp >= now() - INTERVAL 15 MINUTE GROUP BY TraceId HAVING uniqExact(ServiceName) = 2 LIMIT 5"

Each row lists the browser's request span next to the server's POST /_serverFn/<name> and serverFn <name> spans.

Add profiles (optional)

With @everr/otel-profiler, you can see which code ran during each request. It needs Node.js 24 or later.

npm install @everr/otel-profiler @opentelemetry/exporter-trace-otlp-proto

Update src/telemetry/node.ts to add the profiler's context manager and span processor, then start the profiler:

src/telemetry/node.ts
import {
  ProfilingContextManager,
  ProfilingSpanProcessor,
  startProfiler,
} from "@everr/otel-profiler";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { NodeSDK, tracing } from "@opentelemetry/sdk-node";

const sdk = new NodeSDK({
  serviceName: "acme-server",
  contextManager: new ProfilingContextManager(),
  spanProcessors: [
    new ProfilingSpanProcessor(),
    // Listing span processors replaces the default trace exporter, so add it here.
    new tracing.BatchSpanProcessor(new OTLPTraceExporter()),
  ],
  // ...instrumentations from step 2
});
sdk.start();

const profiler = await startProfiler({ resourceAttributes: { "service.name": "acme-server" } });

Call profiler.shutdown() together with sdk.shutdown() when the server stops, so the last profile is sent.

What is sent

RecordExample nameAttributes
Request spanGET /blog/$slughttp.route, http.request.method, http.response.status_code, url.path, url.scheme
Server functionserverFn getPosteverr.server_function.name, everr.server_function.transport (http or in-process)
Errorexception log recordThrown errors (except isExpectedError), 5xx responses, uncaught exceptions and rejections
BrowserPage views, fetch spanseverr.route.pattern on page records, url.template on request spans

The Node auto-instrumentations also add spans for outgoing HTTP calls, databases, Redis, and the other libraries they support.

Troubleshooting

Each request has two server spans

Set disableIncomingRequestInstrumentation: true on the HTTP instrumentation, as in step 2. The Start middleware already creates the request span.

Every redirect shows up as an error

Pass isExpectedError to createServerFnTelemetryMiddleware, as in step 3.

Browser and server spans are in separate traces

Check that network() is in the browser SDK's instrumentations. If your API is on another origin, list it in network({ tracePropagationTargets }), and have the API allow traceparent in Access-Control-Allow-Headers and expose x-everr-route in Access-Control-Expose-Headers.

Tests send telemetry

Set OTEL_SDK_DISABLED=true in your test environment to turn the server SDK off.

Next steps