# Observability in SvelteKit

- Published: 2026-12-02
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-18-observability-in-sveltekit/

> Part 18 of a series on Svelte in 2026. [Part 17](/writing/why-svelte-17-testing-svelte-components/) tested components before they ship. This part looks at what a SvelteKit app tells you once it's running.

The docs' tracing setup worked in dev and broke my production build. I copied the instrumentation file from SvelteKit's observability page into a fresh app, ran `vite dev`, and got exactly what the docs promise: a span for `handle`, one for each function in my `sequence`, one for the `load`. Then I ran `vite build` and `node build`, and every request, including a JSON endpoint that returns one number, came back as a 500 with the body `Internal Server Error`. The server printed nothing. My `handleError` never ran.

The culprit was one line from the docs, `register()`, and how much it hooks. I'll get to the fix. First, what SvelteKit 3 traces once you turn it on, because that part is good. I built the lab on SvelteKit 3.1.0 with adapter-node 6.0.0 (Svelte 5.57.3, Vite 8.3.5, Node 24.22.1) and OpenTelemetry's Node SDK 0.300.0, and wrote spans to a JSON file instead of running Jaeger.

## One flag, and a file that loads first

Tracing arrived in SvelteKit 2.31 behind two experimental flags. In Kit 3 it's a top-level option of the Vite plugin, and the instrumentation file needs no flag at all: if `src/instrumentation.server.ts` exists, it runs.[^migrate]

```ts title="vite.config.ts"
export default defineConfig({
  plugins: [
    sveltekit({
      adapter: adapter(),
      tracing: { server: true },
    }),
  ],
});
```

That flag makes Kit emit spans through `@opentelemetry/api`. Something still has to collect them, and that's what the instrumentation file is for. It has to run before your app's modules load, since OpenTelemetry's auto-instrumentation works by wrapping libraries as they're imported.[^obs] adapter-node arranges that. My built entry point was three lines: import the env initializer, import `instrumentation.server.js`, then `await import("./start.js")`.

Turn the flag on without the SDK installed and you don't get silent no-op spans. The server starts, and the first request kills the process with `tracing_api_missing`. That's the right call; of everything that failed in my lab, it's the only one that tells you what's wrong.

## What a request looks like

Here's the tree for `GET /` in my lab, where `handle` is `sequence(auth, timing)` and the page's server `load` calls one endpoint through `event.fetch` and the same endpoint through the global `fetch`:

```text
GET                                  (http, auto-instrumentation)
  sveltekit.handle.root              http.route=/
    sveltekit.handle.sequenced.auth
      sveltekit.handle.sequenced.timing
        sveltekit.resolve            http.response.status_code=200
          sveltekit.load             src/routes/+page.server.ts
            sveltekit.handle.root    /api/time, is_sub_request=true
              … sveltekit.endpoint
            GET                      (undici)
              sveltekit.handle.root  /api/time, is_sub_request=false
                … sveltekit.endpoint
          sveltekit.load             src/routes/+page.ts
```

Two things in there I wouldn't have guessed. `event.fetch` to your own route never touches the network, so it appears as a whole second request nested inside the `load`, flagged `is_sub_request`. And the universal `+page.ts` load gets its own span when it runs on the server, which makes it obvious when a slow page is slow because of the half you thought ran in the browser.

Turn `tracing.server` off and keep the SDK, and the same request is three spans: an http `GET`, the undici `GET` inside it, and the second http `GET` it triggered. No route, no `load`, no `handle`. That's the difference the flag makes.

You can write to these spans yourself. `event.tracing.root` is the `handle.root` span and `event.tracing.current` is whichever one you're inside; `getRequestEvent()` reaches them from helper code:

```ts title="src/hooks.server.ts"
const auth: Handle = async ({ event, resolve }) => {
  const user = await getUser(event.cookies);
  event.tracing.root.setAttribute("app.user", user.id);
  return resolve(event);
};
```

Every span in that request's tree then sits under a root that says whose request it was, which is the one attribute I'd add on day one.

## What the spans call an error

Kit records the outcome of a `load`, action or endpoint on its span as `result.type`. I tried each kind:

**What one request traces.** The request is…

| Request | Spans, outermost first | What to notice |
| --- | --- | --- |
| GET / (a server load that calls event.fetch and the global fetch) | GET (http) › sveltekit.handle.root › sequenced.auth › sequenced.timing › sveltekit.resolve › sveltekit.load (+page.server.ts), which holds a whole second handle.root for event.fetch and an undici GET for the global fetch; then sveltekit.load (+page.ts) | event.fetch never leaves the process: it shows up as a nested handle.root with sveltekit.is_sub_request=true. The global fetch goes over HTTP, so it gets an undici span and a fresh handle.root with is_sub_request=false. |
| GET /boom (the load throws new Error('db down')) | GET (http, 500, error) › handle.root › … › resolve (500) › sveltekit.load (error) | The load span has status error, an exception event and result.type=unknown_error. handle.root and resolve have no error status. Only the load span and the http span say anything went wrong. |
| GET /missing (the load calls error(404, 'No such note')) | GET (http, 404) › handle.root › … › resolve (404) › sveltekit.load | No span has an error status. The load span records result.type=known_error, result.status=404 and the message. Kit only marks HttpError as an error from 500 up. |
| GET /away (the load calls redirect(303, '/')) | GET (http, 303) › handle.root › … › resolve (303) › sveltekit.load | result.type=redirect, result.status=303, result.location=/ on the load span. No error. |
| POST /form?/save with an empty title (the action returns fail(400)) | POST (http, 400) › handle.root › … › resolve (400) › sveltekit.form_action | form_action.name=save, result.type=failure, result.status=400. No error status. |
| GET /_app/remote/…/getNote (a query called from the browser) | GET (http) › handle.root › … › resolve › sveltekit.remote.call | remote.call.type=query, remote.call.name=getNote. http.route is unknown, since the remote endpoint isn't a route. |
| GET /remote (the same query awaited while rendering the page) | GET (http) › handle.root › … › sveltekit.resolve | No remote.call span at all. During server rendering the query runs in process, and nothing under resolve marks it. |
| GET /api/time with a traceparent header from an upstream service | handle.root › … › sveltekit.endpoint, in the caller's trace | Kit reads traceparent itself, so its spans join the upstream trace. The http span from auto-instrumentation joins it too, as a sibling of handle.root rather than its parent. |

The one that matters for alerting is `/boom`. The `load` threw, the response was a 500, and the error status sits only on the `sveltekit.load` span and on the auto-instrumented http span. `sveltekit.handle.root` and `sveltekit.resolve` both ended without one. A query like "root spans with status error" finds nothing. Query the http span's status code, or any span with `result.type=unknown_error`.

A 404 from `error()` and a `fail(400)` from an action aren't errors either, by design: Kit only marks an `HttpError` as an error from 500 up, and records the rest as attributes.[^code] That's the behaviour I'd want, but write your dashboards knowing it.

The gap I didn't expect is remote functions. Calling a `query` from the browser produced a `sveltekit.remote.call` span with the function's name. Awaiting the same query while the server rendered the page produced nothing under `resolve`; the time just disappears into the render. Remote functions are still experimental in Kit 3, so that may change.

**Quiz:** A form action calls error(503, 'Payments are down'). Which spans get an error status?

- None; error() is an expected error, so Kit records it as an attribute
- The sveltekit.form_action span, and handle.root above it
- The sveltekit.form_action span, plus the auto-instrumented http span for the 503

**Answer:** The sveltekit.form_action span, plus the auto-instrumented http span for the 503 — An HttpError at 500 or above gets an exception event and an error status on its own span. The http span marks it because of the status code. The Kit spans in between don't.

- Not "None; error() is an expected error, so Kit records it as an attribute": That's true for a 404, or a fail(400). The cut-off is the status code, not the function you called.
- Not "The sveltekit.form_action span, and handle.root above it": Kit sets the status on the span where the error was thrown. In my /boom test, handle.root stayed clean.

## The line that broke production

Back to the 500s. The docs' instrumentation file starts with `register()` from `import-in-the-middle`, which installs the loader hook OpenTelemetry uses to wrap imported modules. Called with no options, it wraps every ES module Node loads, including the chunks of your built app and SvelteKit's own runtime.

SvelteKit keeps its hooks in a module-level variable that it fills in at startup: `export let hooks`, then `hooks = value` inside `set_hooks`. The wrapped copy of that module didn't see the reassignment, so when a request arrived Kit called `hooks.reroute(...)` on the stale value. I patched the built file to log the error it was catching, and got `TypeError: hooks.reroute is not a function`. Kit catches errors from `reroute` and returns a plain 500 without logging, which is why the server was silent.

`vite dev` worked because Vite loads your server code itself, outside Node's module loader, so the hook never wrapped Kit's runtime there. It failed with import-in-the-middle 3.5.2 and 3.5.3, with experimental async on or off, and with `tracing.server` off. The fix is to only hook packages, not your own relative imports. I took it from an open SvelteKit issue that hit the same wall through a different variable:[^issue]

```ts title="src/instrumentation.server.ts"
import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { register } from "import-in-the-middle/register-hooks.mjs";

// Hook packages like pg or undici, not the app's own chunks.
register({
  shouldInclude: (_url, specifier) => !specifier.startsWith("."),
});

new NodeSDK({
  serviceName: "my-app",
  traceExporter: new OTLPTraceExporter(),
  instrumentations: [getNodeAutoInstrumentations()],
}).start();
```

With that change every route answered as before, and the http and undici spans still showed up, so the packages I cared about were still instrumented. The one cost: a library imported only through a relative path in your own bundle won't be wrapped, which the docs' bundling section already warns about for other reasons (it's why they suggest `ssr.external`).

**Quiz:** Your app passes every test in vite dev with tracing on. What's the cheapest check that would have caught the 500s before deploying?

- Run svelte-check
- Run vite build, then start the built server with the instrumentation file and request any route
- Turn tracing.server off before building

**Answer:** Run vite build, then start the built server with the instrumentation file and request any route — The hook only wraps Kit's runtime when Node loads the built output, so only the built server shows it. One curl is enough.

- Not "Run svelte-check": It passed. Nothing about the types changed.
- Not "Turn tracing.server off before building": I tried that. The 500s stayed, because the problem is register() in the instrumentation file, not the spans.

## Next.js does this in a function you export

React itself has nothing to say about tracing; it's a framework job. Next.js has an `instrumentation.ts` file too, but you export a `register()` function that Next calls when a server starts, and its docs point you to `@vercel/otel` rather than wiring the Node SDK yourself.[^next] Next emits its own spans for rendering and route handlers, with more behind `NEXT_OTEL_VERBOSE=1`. The shape is close to Kit's. Kit's spans follow your code more closely: one per `load`, one per function in `sequence`, one per action by name. I didn't run Next for this part; that comparison is from its docs.

## What I'd set up

Turn on `tracing.server`, install the four packages from the docs, and write the instrumentation file with a filtered `register()`. Add `app.user` (or a tenant) to the root span in `handle`. Then run the built server and request one route before trusting any of it, because a broken loader hook looks exactly like a broken app. If the overhead worries you, and the docs say it can be nontrivial, enable it on preview deployments first.

Next: Svelte vs React, one component written both ways.

[^migrate]: SvelteKit docs, [Migrating to SvelteKit 3: Observability](https://svelte.dev/docs/kit/migrating-to-sveltekit-3#Observability).

[^obs]: SvelteKit docs, [Observability](https://svelte.dev/docs/kit/observability), including "Bundling caveats".

[^code]: `record_span` in `@sveltejs/kit/src/exports/internal/server/telemetry.js`, SvelteKit 3.1.0.

[^issue]: [sveltejs/kit#17004](https://github.com/sveltejs/kit/issues/17004), "experimental:tracing+async conflicts", open as of 2026-10-26. The reporter hit it through Svelte's `ssr_context` with async on; I hit it through Kit's `hooks` with async off.

[^next]: Next.js docs, [OpenTelemetry](https://nextjs.org/docs/app/guides/open-telemetry).

- **Part 19 — Svelte vs React: one component, two ways**: The same feature in both, with honest trade-offs
