# @frontman-ai/nextjs 中文文档

规范地址：https://npmcn.com/package/%40frontman-ai/nextjs/

版本：2\.0\.4
npm 元数据更新时间：2026-10-26T19:53:53.890Z
中文译文更新时间：2026-11-15T16:06:32.477Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40frontman-ai/nextjs
原文对照：https://npmcn.com/package/%40frontman-ai/nextjs/?lang=original
项目主页：https://frontman.sh/
源码仓库：https://github.com/frontman-ai/frontman

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：561 kB，7 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：5 个
- peer 依赖：next ^15\.5\.0 \|\| ^16\.0\.0，react ^18\.2\.0 \|\| ^19\.0\.0，react-dom ^18\.2\.0 \|\| ^19\.0\.0，@opentelemetry/api ^1\.9\.0，@opentelemetry/sdk-logs \>=0\.52\.0 \<1\.0\.0，@opentelemetry/sdk-trace-base \>=1\.25\.0 \<3\.0\.0
- 首次发布：2026-01-30T09:05:42.985Z
- 最新版本发布：2026-10-26T19:53:52.512Z
- 近 30 天下载量：2463（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：41（近 12 个月 41 个）

## 中文简介

Next.js Frontman的集成 - AI动力发展工具和可观察性

## 安装

```sh
npm install @frontman-ai/nextjs
```

也可以使用：`pnpm add @frontman-ai/nextjs`、`yarn add @frontman-ai/nextjs`、`bun add @frontman-ai/nextjs`

## README

# @ frontman-ai/ nextjs (英语)

Next.js 为Frontman集成 - 为Next.js应用程序提供开发工具和可观察性.

## 安装

### 快速安装( 建议)

安装Frontman的最快方法是使用我们的CLI安装器:

```bash
npx @frontman-ai/nextjs install

# Or with a custom server host
npx @frontman-ai/nextjs install --server frontman.company.com
```

安装器会:

-   检测您的 Next.js 版本( 15. x, 至少15.5, 或16. x)
-   创建合适的中间软件/代理文件
-   设置 OpenTelection 仪器
-   配置要连接到您的 Frontman 服务器的一切

### CLI 选项

```bash
npx @frontman-ai/nextjs install [options]

Options:
  --server <host>   Frontman server host (default: api.frontman.sh)
  --prefix <path>   Target directory (default: current directory)
  --dry-run         Preview changes without writing files
  --skip-deps       Skip dependency installation
  --help            Show help message
```

### 手动安装

如果您喜欢手动设置或需要与现有配置整合 :

```bash
npm install @frontman-ai/nextjs
```

那就跟着 [手动设置](https://npmcn.com/package/%40frontman-ai/nextjs/#readme-manual-setup) 指示如下.

## 快速启动

运行安装器后,你就可以出发了! 启动您的 Next.js dev 服务器 :

```bash
npm run dev
```

然后打开您的浏览器 `http://localhost:3000/frontman` 进入前线部队.

随着默认主机设置,Frontman将您重定向到 `api.frontman.sh` 然后将您送回本地 `/frontman` URL (中文(简体) ). 在您的第一个提示前, 连接一个支持的 AI 提供者与 OAuth 或者添加 API 密钥 。 如果您配置了另一个Frontman服务器, 请在服务器上签名 .

只有在 `process.env.NODE_ENV === 'development'` 默认。 设定 `FRONTMAN_ENABLE_IN_PRODUCTION=1` 或者说 `FRONTMAN_ENABLED=1` 选择外部发展。 设定 `FRONTMAN_ENABLED=0` 在任何环境下强迫Frontman离开.

## 手动设置

### Next.js 15.x(中件,最低为15.5个)

创建 `middleware.ts` 在您的工程根中 :

```typescript
import { createMiddleware } from '@frontman-ai/nextjs';
import { NextRequest, NextResponse } from 'next/server';

const frontman = createMiddleware({
  host: 'api.frontman.sh', // or 'frontman.local:4000' for local development
});
// Handles routes only when NODE_ENV === 'development' by default.
// Set FRONTMAN_ENABLE_IN_PRODUCTION=1 or FRONTMAN_ENABLED=1 to opt in elsewhere.

export async function middleware(req: NextRequest) {
  const response = await frontman(req);
  if (response) return response;
  return NextResponse.next();
}

export const config = {
  matcher: ['/frontman', '/frontman/:path*'],
};
```

### Next.js 16.x (代名词.ts) (中文(简体) )

创建 `proxy.ts` 在您的工程根中 :

```typescript
import { createMiddleware } from '@frontman-ai/nextjs';
import { NextRequest, NextResponse } from 'next/server';

const frontman = createMiddleware({
  host: 'api.frontman.sh', // or 'frontman.local:4000' for local development
});
// Handles routes only when NODE_ENV === 'development' by default.
// Set FRONTMAN_ENABLE_IN_PRODUCTION=1 or FRONTMAN_ENABLED=1 to opt in elsewhere.

export function proxy(req: NextRequest): NextResponse | Promise<NextResponse> {
  if (req.nextUrl.pathname === '/frontman' || req.nextUrl.pathname.startsWith('/frontman/')) {
    return frontman(req) || NextResponse.next();
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/frontman', '/frontman/:path*'],
};
```

### OpenTelemet 设置( 建议)

创建 `instrumentation.ts` 在项目根中(或 `src/` 如果您使用该目录 :

```typescript
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { NodeSDK } = await import('@opentelemetry/sdk-node');
    const { setup } = await import('@frontman-ai/nextjs/Instrumentation');
    const [logProcessor, spanProcessor] = setup();
    new NodeSDK({
      logRecordProcessors: [logProcessor],
      spanProcessors: [spanProcessor],
    }).start();
  }
}
```

**就这样!** 前线现在:

-   抓取控制台日志、构建输出和出错
-   跟踪 Next.js HTTP 请求、 API 路径和渲染
-   通过 Frontman 用户界面提供所有日志 `/frontman`

## 添加到已有文件

如果你已经有 `middleware.ts`, (中文(简体) ), `proxy.ts`,或 `instrumentation.ts` 文件,安装器将显示手工集成步骤。 如何在现有文件中添加 Frontman :

### 已存在的中间器件.t (Next.js 15.x, 15.5 最低)

```typescript
import { createMiddleware } from '@frontman-ai/nextjs';
import { NextRequest, NextResponse } from 'next/server';
// ... your other imports

const frontman = createMiddleware({
  host: 'api.frontman.sh', // or 'frontman.local:4000' for local development
});

export async function middleware(req: NextRequest) {
  // Add Frontman handler first - it will handle /frontman/* routes
  const response = await frontman(req);
  if (response) return response;

  // ... your existing middleware logic below
  return NextResponse.next();
}

export const config = {
  // Add Frontman matcher alongside your existing matchers
  matcher: ['/frontman', '/frontman/:path*', '/your-other-routes/:path*'],
};
```

### 已存在的代理.ts(Next.js 16.x)

```typescript
import { createMiddleware } from '@frontman-ai/nextjs';
import { NextRequest, NextResponse } from 'next/server';
// ... your other imports

const frontman = createMiddleware({
  host: 'api.frontman.sh', // or 'frontman.local:4000' for local development
});

export function proxy(req: NextRequest): NextResponse | Promise<NextResponse> {
  // Add Frontman handler first - it will handle /frontman/* routes
  if (req.nextUrl.pathname === '/frontman' || req.nextUrl.pathname.startsWith('/frontman/')) {
    return frontman(req) || NextResponse.next();
  }

  // ... your existing proxy logic below
  return NextResponse.next();
}

export const config = {
  // Add Frontman matcher alongside your existing matchers
  matcher: ['/frontman', '/frontman/:path*', '/your-other-routes/:path*'],
};
```

### 现有仪器

狦 **没有开放的几何** 尚未设置:

```typescript
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { NodeSDK } = await import('@opentelemetry/sdk-node');
    const { setup } = await import('@frontman-ai/nextjs/Instrumentation');
    const [logProcessor, spanProcessor] = setup();

    new NodeSDK({
      logRecordProcessors: [logProcessor],
      spanProcessors: [spanProcessor],
    }).start();
  }

  // ... your existing instrumentation logic
}
```

狦 **已拥有 OpenTelemeth** 设置, 在您的现有配置中添加 Frontman 处理器 :

```typescript
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { setup } = await import('@frontman-ai/nextjs/Instrumentation');
    const [logProcessor, spanProcessor] = setup();

    new NodeSDK({
      // ... your existing OTEL config
      logRecordProcessors: [logProcessor, ...yourExistingLogProcessors],
      spanProcessors: [spanProcessor, ...yourExistingSpanProcessors],
    }).start();
  }
}
```

## 获取什么

### 自动控制台补丁(仅节点.js)

LogCapture 在模块导入和补丁时自动初始化 :

-   所有控制台方法 : `console.log()`, (中文(简体) ), `console.error()`, (中文(简体) ), `console.warn()`, (中文(简体) ), `console.info()`, (中文(简体) ), `console.debug()`
-   `process.stdout.write()` 用于构建输出(网页包/涡轮包汇编信息)
-   `process.on('uncaughtException')` 未处理错误
-   `process.on('unhandledRejection')` 对于无所施舍的诺言

**浏览器环境自动跳过** - 浏览器中不发生控制台补丁.

### Via OpenTeleometry Spans (可选) (可选)

当你设置 `instrumentation.ts`数字 :

-   HTTP 请求 (`BaseServer.handleRequest`(中文(简体) )
-   路由渲染( R)`AppRender.getBodyResult`(中文(简体) )
-   API 路由执行`AppRouteRouteHandlers.runHandler`(中文(简体) )
-   请求方法、路径、状态代码、持续时间

### 存储和跨文本共享

所有捕获的数据都储存在 **循环缓冲器** (默认情况下为1024个条目) `globalThis` 单通图案. 这将确保日志在 Next.js/ Turbopack 执行上下文中共享:

-   仪器环境(启动)
-   页面渲染上下文
-   API 路由上下文
-   中间软件上下文( Edge 运行时间 - 只读)

该缓冲器持续了Node.js进程的生命期,可通过Frontman UI和F `get_logs` 工具.

## 配置选项

### 中间软件选项

```typescript
createMiddleware({
  host: string,                // Frontman server host (required) - the client UI connects here via WebSocket
  basePath: string,            // Base path for Frontman routes (default: "frontman")
  serverName: string,          // Server name (default: "frontman-nextjs")
  serverVersion: string,       // Server version (default: package version)
  clientUrl: string,           // Custom client bundle URL
  clientCssUrl: string,        // Custom client CSS URL
  entrypointUrl: string,       // Custom entrypoint URL
  projectRoot: string,         // Project root directory (default: process.cwd())
})
```

### 理解 `host` 选项

这个 `host` 选项指定客户端 UI 将连接的 Frontman 服务器用于AI 能力。 你来的时候 `/frontman` 在您的 Next.js 应用程序中 :

1.  中间软件服务于 Frontman UI HTML
2.  用户界面加载客户端 JavaScript `?host=<your-host>`
3.  客户端建立WebSocket连接 `wss://<host>/socket`
4.  AI 交互和工具调用通过此连接流出

中间软件本身不连接到Frontman服务器——它只传递主机给客户端.

**实例:**

-   生产: `host: 'api.frontman.sh'` • 客户端连接 `wss://api.frontman.sh/socket`
-   本地 dev : `host: 'frontman.local:4000'` • 客户端连接 `wss://frontman.local:4000/socket`

## 支持的 Next.js 版本

| 版本 | 中间软件文件 | 状态 |
| --- | --- | --- |
| Next.js 15.x(最低15.5个) | `middleware.ts` | 已完全支持 |
| 下一个.js 16.x | `proxy.ts` | 已完全支持 |

两个版本都有内置的OpenTeleometry支持,不需要额外的配置.

## 建筑

```
Next.js App (Turbopack/Webpack)
│
├─> Module Import (first context - instrumentation)
│   └─> LogCapture auto-initializes at module level
│       ├─> Creates globalThis.__FRONTMAN_INSTANCE__
│       ├─> Patches console.log/warn/error/info/debug
│       ├─> Intercepts process.stdout.write
│       └─> Listens to uncaughtException/unhandledRejection
│
├─> Module Import (second context - page render)
│   └─> LogCapture reuses existing globalThis.__FRONTMAN_INSTANCE__
│       └─> Same buffer, no re-patching (guarded by __FRONTMAN_CONSOLE_PATCHED__ flag)
│
├─> instrumentation.ts (startup) - OPTIONAL
│   └─> setup() returns OTEL processors that write to same buffer
│
├─> middleware.ts / proxy.ts (per-request)
│   └─> Serves Frontman UI at /frontman
│       └─> Connects to Frontman server for AI tools
│
└─> OpenTelemetry SDK (optional)
    ├─> LogRecordProcessor → globalThis.__FRONTMAN_INSTANCE__.buffer
    └─> SpanProcessor → globalThis.__FRONTMAN_INSTANCE__.buffer
```

### 关键技术细节

**交叉连接缓冲共享**

-   支持 Next.js 版本的 Turbopack 在多个孤立背景下运行代码
-   `globalThis.__FRONTMAN_INSTANCE__` 存储单通缓冲实例
-   所有上下文读取/写入相同的循环缓冲
-   控制台补丁只发生一次( 由 `__FRONTMAN_CONSOLE_PATCHED__` 旗帜)

**循环缓冲**

-   固定容量:1024个条目(可配置)
-   最旧的条目在满后自动被删除
-   条目包括:时间戳、关卡、消息、属性、控制台方法
-   来自不同背景的并行写作的线索安全

## 高级使用

### 自定义 OTEL 配置

如果您需要更多控制 OpenTeleometry 设置 :

```typescript
import { setup } from '@frontman-ai/nextjs/Instrumentation';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const [logProcessor, spanProcessor] = setup();

    new NodeSDK({
      serviceName: 'my-app',
      resource: resourceFromAttributes({
        'service.version': '1.0.0',
      }),
      traceExporter: new OTLPTraceExporter({
        url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
      }),
      logRecordProcessors: [logProcessor],
      spanProcessors: [spanProcessor],
    }).start();
  }
}
```

### 无开口遥测

前锋在不开放遥测的情况下工作! 如果您只设置了中间软件( skip) `instrumentation.ts`:

-   控制台日志仍被捕获( 模块导入时自动初始化)
-   构建输出跟踪
-   错误已登录
-   Frontman UI 可用时间 `/frontman`
-   未捕获 HTTP 跨度( 需要 OTEL)

LogCapture在模块被导入时自动初始化,所以控制台补丁在Node.js环境中自动发生-不需要明确初始化.

### 自定义日志能力配置

您可以自定义缓冲大小和 stdout 模式 :

```typescript
import { initialize } from '@frontman-ai/nextjs/LogCapture';

// Call this BEFORE any console.log() calls (e.g., in instrumentation.ts)
initialize({
  bufferCapacity: 2048,  // Default: 1024
  stdoutPatterns: ['webpack', 'turbopack', 'Compiled', 'Failed', 'custom-pattern'],
});
```

**说明:** 配置只在第一次通话时生效 。 后来的呼声被忽略了,因为单通实例已经创建了.

## 解决问题

### 未捕获日志

**检查 1: 输入校验模块** LogCapture只在模块在节点.js上下文被导入时初始化. 确定其中之一:

-   你有过 `instrumentation.ts` 从 `@frontman-ai/nextjs/Instrumentation`
-   或者你已经 `middleware.ts` 从 `@frontman-ai/nextjs`

**检查 2: 验证节点. js 运行时间** LogCapture不运行在浏览器或Edge运行时间. 检查您的环境 :

```javascript
console.log('Runtime:', process.env.NEXT_RUNTIME); // Should be 'nodejs'
```

**检查 3: 验证缓冲内容** 直接查询缓冲器以查看是否有日志 :

```typescript
import { getLogs } from '@frontman-ai/nextjs/LogCapture';

const allLogs = getLogs();
console.log('Buffer contains', allLogs.length, 'logs');
```

**请检查4:多种上下文** 在所支持的"Next.js"版本中,代码可能在不同的上下文中运行. 校验所有上下文是否共享同一缓冲 :

```javascript
console.log('Instance:', globalThis.__FRONTMAN_INSTANCE__);
console.log('Buffer size:', globalThis.__FRONTMAN_INSTANCE__?.buffer.contents.items.length);
```

### 控制台日志出现两次

这是正常的行为 - LogCapture 捕获日志并调用原始控制台方法,因此日志仍然出现在您的终端/浏览器控制台上.

### 构建未捕获的输出

默认情况下,只有这些模式从 `process.stdout`数字 :

-   "网络包装"
-   "涡轮"
-   "编译"
-   "失败"

要获取额外的模式,请使用自定义配置(见上文).

### 安装器显示“ 需要手动修改 ”

这发生在您已有的中间件,代理件,或未包含Frontman的仪器文件. 安装者不会覆盖您的已有代码 。 跟着 [添加到已有文件](https://npmcn.com/package/%40frontman-ai/nextjs/#readme-adding-to-existing-files) 命令手动整合Frontman.

## API 密码

### `createMiddleware(options)`

创建 Next.js 中间软件处理器,为 Frontman UI 服务并连接到您的 Frontman 服务器 .

```typescript
import { createMiddleware } from '@frontman-ai/nextjs';

const middleware = createMiddleware({
  host: string,                // Frontman server host (required)
  basePath: string,            // Base path (default: "frontman")
  serverName: string,          // Server name (default: "frontman-nextjs")
  serverVersion: string,       // Version (default: package version)
  projectRoot: string,         // Project root (default: process.cwd())
});
```

**回返情况:** `(request: NextRequest) => Promise<NextResponse | undefined>`

### `setup()`

初始化了LogCapture(Console补丁,出错处理器)并返回OTEL处理器,用于OpenTeleometry SDK.

```typescript
import { setup } from '@frontman-ai/nextjs/Instrumentation';

const [logProcessor, spanProcessor] = setup();
```

**回返情况:** `[LogRecordProcessor, SpanProcessor]`

### `initialize(config?)`

用自定义配置手动初始化日志 Capture 。 通常不需要,因为自动初始化发生在模块导入时.

```typescript
import { initialize } from '@frontman-ai/nextjs/LogCapture';

initialize({
  bufferCapacity: number,           // Buffer size (default: 1024)
  stdoutPatterns: string[],         // Patterns to capture from stdout
});
```

**回返情况:** `void`

### `getLogs(options?)`

使用可选过滤器查询日志缓冲器 .

```typescript
import { getLogs } from '@frontman-ai/nextjs/LogCapture';

const logs = getLogs({
  pattern: string,        // Regex pattern to match messages (case-insensitive)
  level: 'console' | 'build' | 'error',  // Filter by log level
  since: number,          // Unix timestamp - only logs after this time
  tail: number,           // Limit to last N logs
});
```

**回返情况:** `LogEntry[]`

**日志输入类型 :**

```typescript
type LogEntry = {
  timestamp: string;                           // ISO 8601 timestamp
  level: 'console' | 'build' | 'error';       // Log level
  message: string;                             // Log message (ANSI codes stripped)
  attributes?: Record<string, any>;            // Additional attributes
  resource?: Record<string, any>;              // Resource info
  consoleMethod?: 'log' | 'info' | 'warn' | 'error' | 'debug';  // Original console method
};
```

## 许可证

麻省理工学院

## 常见问题

### @frontman-ai/nextjs 是什么？

Next\.js Frontman的集成 - AI动力发展工具和可观察性

### 如何安装 @frontman-ai/nextjs？

在项目目录运行 npm install @frontman-ai/nextjs，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：next（^15\.5\.0 \|\| ^16\.0\.0）、react（^18\.2\.0 \|\| ^19\.0\.0）、react-dom（^18\.2\.0 \|\| ^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。它还提供命令行工具 nextjs、frontman-nextjs，可以用 npx nextjs 直接运行。

### @frontman-ai/nextjs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @frontman-ai/nextjs 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @frontman-ai/nextjs 可以商用吗？

@frontman-ai/nextjs 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @frontman-ai/nextjs 的下载量有多少？

根据 npm 官方下载统计，@frontman-ai/nextjs 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,463 次，日均约 82 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @frontman-ai/nextjs 还在维护吗？

最新版本 2\.0\.4 发布于 2026/10/27（20 天前）；至今共发布 41 个版本，其中过去 12 个月发布了 41 个；首次发布于 2026/01/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

