> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js

> 面向 ClickHouse Observability 和自管理部署的 Next.js 设置与配置。

请为您的 Next.js 部署选择服务端插桩方式：

* **自托管，Node.js 运行时：** 使用 ClickStack Node.js SDK。
* **Vercel 或 Edge 运行时：** 使用 `@vercel/otel`。

如需采集浏览器遥测数据和会话回放，请参阅[浏览器 SDK 指南](https://clickhouse.com/docs/zh/clickstack/observability/ingesting-data/sdks/browser.md)。

本指南集成了：

## 自托管 Next.js

使用 Node.js 22.15 或更高版本，并安装 SDK：

```shell theme={null}
npm install @clickhouse/clickstack-node
```

在项目根目录下创建 `instrumentation.ts`；如果您的应用使用 `src` 目录，则在 `src` 下创建。仅在 Node.js 运行时中初始化 SDK：

```typescript theme={null}
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { init } = await import('@clickhouse/clickstack-node');
    init();
  }
}
```

在现有的 Next.js 配置中，将该 SDK 添加到 `serverExternalPackages`，使其在服务端打包产物之外加载：

```javascript theme={null}
// next.config.mjs
export default {
  serverExternalPackages: ['@clickhouse/clickstack-node'],
};
```

在下方配置目标端，并设置 `OTEL_SERVICE_NAME` 以标识您的应用程序。请勿再预加载该 SDK，也不要初始化其他 OpenTelemetry SDK。如需了解更多选项，请参阅 [Node.js 指南](https://clickhouse.com/docs/zh/clickstack/observability/ingesting-data/sdks/nodejs.md)。

有关进程终止和部署方面的注意事项，请参阅 [该 SDK 的 Next.js 指南](https://github.com/ClickHouse/clickstack-node#nextjs)。

## Vercel 与 Edge 运行时

请按照 [Next.js OpenTelemetry 设置指南](https://nextjs.org/docs/app/guides/open-telemetry)使用 `@vercel/otel`。请改用此方式，而不要使用上文所述的 ClickStack Node.js SDK 初始化方式。

使用下方的连接设置配置 [OTLP 导出](https://github.com/vercel/otel/tree/main/packages/otel#registerotelconfig-configuration)。替换所有示例目标端以及针对特定信号的端点覆盖配置，并在部署配置中设置这些变量。

如果您的 Vercel 部署已在使用某个追踪集成，请为此目标端配置[自定义导出器](https://nextjs.org/docs/app/guides/open-telemetry#custom-exporters)；仅设置端点环境变量无法覆盖该集成。

## 配置目标端

无论选择哪种插桩方式，都需要设置服务名称：

```shell theme={null}
export OTEL_SERVICE_NAME='my-nextjs-app'
```

> [tab] 全托管
>
> [Beta 版产品](https://clickhouse.com/docs/reference/settings/beta-and-experimental-features.md#beta-features)
>
> 在您的服务中打开 **团队设置 → 数据 → Managed Telemetry**，复制 **OTLP HTTP 端点** 和 **API key**。请使用包含端口号的完整 HTTPS 端点：
>
> ```shell theme={null}
> export OTEL_EXPORTER_OTLP_ENDPOINT='https://YOUR_OTEL_ENDPOINT:4318'
> export OTEL_EXPORTER_OTLP_HEADERS='authorization=Bearer%20YOUR_INGESTION_API_KEY'
> export OTEL_EXPORTER_OTLP_PROTOCOL='http/protobuf'
> ```

> [tab] 自管理
>
> 使用采集器的 OTLP HTTP 端点和摄取密钥。如果采集器未配置 TLS，请使用 `http://` 代替 `https://`。有关采集器的设置方法，请参阅[使用 OpenTelemetry 摄取数据](https://clickhouse.com/docs/zh/clickstack/observability/ingesting-data/opentelemetry.md#self-managed)。
>
> ```shell theme={null}
> export OTEL_EXPORTER_OTLP_ENDPOINT='https://YOUR_COLLECTOR_HOST:4318'
> export OTEL_EXPORTER_OTLP_HEADERS='authorization=YOUR_INGESTION_API_KEY'
> export OTEL_EXPORTER_OTLP_PROTOCOL='http/protobuf'
> ```

## 验证数据摄取

启动应用程序，并向服务端渲染的页面或 API 路由发送请求。在 ClickHouse Observability 中选择最近的时间范围，然后在 Traces 中找到应用程序的服务名称。
