<!-- Next.js — Heystack docs. Rendered: https://heystack.dev/docs/nextjs · Index: https://heystack.dev/llms.txt -->
# Next.js

Use the `@heystack/otel/next` entry for **any** Next.js deploy target — Vercel/Node and Cloudflare/OpenNext alike. `registerHeystack` is runtime-aware: it auto-detects Node vs Cloudflare workerd and picks the right exporter, so you don't need to know your deploy target ahead of time.

## Install

```bash
npm install "@heystack/otel@>=0.19.1"
```

## Wire up `instrumentation.ts`

Create or extend `instrumentation.ts` (or `src/instrumentation.ts`) at your project root:

```ts
export async function register() {
  const { registerHeystack } = await import("@heystack/otel/next");
  await registerHeystack({ service: "my-app" }); // apiKey from process.env.HEYSTACK_API_KEY
}
```

`apiKey` defaults to `process.env.HEYSTACK_API_KEY`. `registerHeystack` is safe to call unconditionally:

- **Vercel / Node deploys** → uses the Node OTel SDK (auto-instrumentations).
- **Cloudflare / OpenNext (workerd)** → Next still reports `NEXT_RUNTIME === "nodejs"`, but the code actually runs on workerd, where the Node SDK's `node:http` OTLP exporter can't send (it initializes and silently exports nothing). `registerHeystack` detects workerd and registers the **fetch-based** exporter instead, so framework spans actually ship. No separate setup or import needed.
- **Edge runtime** → no-op (neither SDK can run there).

## Set the key

```bash
# .env.local (and gitignore it)
HEYSTACK_API_KEY=sk_live_…
```

For OpenNext on Cloudflare, also set it on the host: `wrangler secret put HEYSTACK_API_KEY`.

## Flushing on workerd

On workerd there's no per-request `ExecutionContext`, so spans are **not** auto-flushed and the export `fetch()` can be cut off when the isolate is torn down — silently dropping the trace. For guaranteed delivery, import `flushHeystack` and call it from a response hook (or `ctx.waitUntil(flushHeystack())` if you have a ctx):

```ts
import { flushHeystack } from "@heystack/otel/workers";

// after handling a request
await flushHeystack(); // awaits the export fetch
```

This requires `@heystack/otel >=0.19.1`. On Vercel/Node deploys you don't need to do anything — the Node SDK flushes on shutdown.

## Session replay (browser)

The steps above trace the **server**. Session replay records the **browser**, via a
separate entry — `@heystack/otel/web` — that must run client-side. A server component
can't call it, so wrap it in a `"use client"` component and mount it once in your root
layout. The rrweb recorder ships **inside** `@heystack/otel` (nothing else to install)
and uploads are **CORS-free**.

```tsx
// app/HeystackReplay.tsx
"use client";
import { useEffect } from "react";
import { instrumentWeb } from "@heystack/otel/web";

export function HeystackReplay() {
  useEffect(() => {
    const apiKey = process.env.NEXT_PUBLIC_HEYSTACK_WEB_KEY;
    if (!apiKey) return;             // no key → no-op
    let stop: (() => void) | undefined;
    let cancelled = false;
    // tracing: true also traces the browser — each fetch to your API becomes a
    // CLIENT span, so browser→API shows as ONE trace + a service-map edge.
    // If your API is a DIFFERENT origin, list it in tracePropagationTargets (and
    // allow `traceparent` in that API's CORS) — trace headers are never sent to
    // any other origin, so third parties (Clerk, Stripe, …) are never broken.
    instrumentWeb({
      apiKey,
      service: "my-app",
      tracing: true,
      traceSampleRate: 0.25,
      tracePropagationTargets: ["api.my-app.com"], // omit if your API is same-origin
    })
      .then((s) => (cancelled ? s() : (stop = s)))
      .catch(() => {});              // best-effort; never break the app
    return () => { cancelled = true; stop?.(); };
  }, []);
  return null;
}
```

```tsx
// app/layout.tsx — mount once, inside <body>
import { HeystackReplay } from "./HeystackReplay";
// …
<HeystackReplay />
```

The browser needs its own key. Anything with the `NEXT_PUBLIC_` prefix ships in the
client bundle and is public, so use a **Browser key** (`hs_web_…`) there — mint one
under your app's **Settings → Connection & keys → Browser key**. A Browser key is write-only:
it can send browser traces, logs, replays and bug reports, and nothing else (no reads,
no app management, no dSYM upload).

```bash
# .env.local
HEYSTACK_API_KEY=sk_live_…            # server only — never NEXT_PUBLIC_
NEXT_PUBLIC_HEYSTACK_WEB_KEY=hs_web_…  # public Browser key
```

> **Never put the server key (`sk_live_…`) in a `NEXT_PUBLIC_` variable or any
> client code.** If you already shipped one to the browser, switch the client to a
> Browser key, then **revoke and rotate** the exposed server key in Settings.

Recording is **server-gated**: nothing is captured until you enable replay for the app
in the console (**Settings → Data & privacy → Session replay**), so it's safe to ship this before turning
it on. See [Session replay](https://heystack.dev/docs/replay) for masking and privacy controls.

**Distributed tracing (`tracing: true`).** With tracing on, a browser call to your API
propagates W3C `traceparent`, so the browser CLIENT span and your API's SERVER span share
one trace — the request shows as a single connected waterfall, and the pair appears as a
`web → api` edge on the **Service Map** (switch it to **All apps** to see every service in
your org connected). It adds browser span volume, so it's opt-in and head-sampled
(`traceSampleRate`); start low on busy apps. Your server (`registerHeystack`) and Workers
API (`instrument`) already continue the incoming trace automatically.

For safety, `traceparent` is added **only** to same-origin requests and to origins you
list in `tracePropagationTargets` — never to third parties, so an unexpected CORS
preflight can't break calls to Clerk, Stripe, analytics, etc. If your API is a **different
origin** than the site, list it there **and** allow `traceparent` (and `tracestate`) in
that API's CORS `Access-Control-Allow-Headers`. Same-origin APIs need neither.
