@frontman-ai/nextjs

中文文档
2.0.4发布于 2026/10/27Apache-2.0TypeScriptES Module近 30 天下载 2463

Next.js integration for Frontman - AI-powered development tools and observability

原始使用文档
文档目录38 节
  1. Installation
  2. Quick Install (Recommended)
  3. CLI Options
  4. Manual Installation
  5. Quick Start
  6. Manual Setup
  7. Next.js 15.x (middleware.ts, 15.5 minimum)
  8. Next.js 16.x (proxy.ts)
  9. OpenTelemetry Setup (Recommended)
  10. Adding to Existing Files
  11. Existing middleware.ts (Next.js 15.x, 15.5 minimum)
  12. Existing proxy.ts (Next.js 16.x)
  13. Existing instrumentation.ts
  14. What Gets Captured
  15. Automatic Console Patching (Node.js only)
  16. Via OpenTelemetry Spans (Optional)
  17. Storage & Cross-Context Sharing
  18. Configuration Options
  19. Middleware Options
  20. Understanding the host Option
  21. Supported Next.js Versions
  22. Architecture
  23. Key Technical Details
  24. Advanced Usage
  25. Custom OTEL Configuration
  26. Without OpenTelemetry
  27. Custom LogCapture Configuration
  28. Troubleshooting
  29. Logs not being captured
  30. Console logs appear twice
  31. Build output not captured
  32. Installer shows "manual modification required"
  33. API
  34. createMiddleware(options)
  35. setup()
  36. initialize(config?)
  37. getLogs(options?)
  38. License

@frontman-ai/nextjs

Next.js integration for Frontman - provides development tools and observability for Next.js applications.

Installation

The fastest way to install Frontman is using our CLI installer:

npx @frontman-ai/nextjs install

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

The installer will:

  • Detect your Next.js version (15.x with a 15.5 minimum, or 16.x)
  • Create the appropriate middleware/proxy file
  • Set up OpenTelemetry instrumentation
  • Configure everything to connect to your Frontman server

CLI Options

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

Manual Installation

If you prefer to set things up manually or need to integrate with an existing configuration:

npm install @frontman-ai/nextjs

Then follow the Manual Setup instructions below.

Quick Start

After running the installer, you're ready to go! Start your Next.js dev server:

npm run dev

Then open your browser to http://localhost:3000/frontman to access the Frontman UI.

With the default hosted setup, Frontman redirects you to api.frontman.sh to sign in with GitHub or Google, then returns you to the local /frontman URL. Before your first prompt, connect a supported AI provider with OAuth or add an API key. If you configured another Frontman server, sign in on that server instead.

Frontman routes are enabled only when process.env.NODE_ENV === 'development' by default. Set FRONTMAN_ENABLE_IN_PRODUCTION=1 or FRONTMAN_ENABLED=1 to opt in outside development. Set FRONTMAN_ENABLED=0 to force Frontman off in any environment.

Manual Setup

Next.js 15.x (middleware.ts, 15.5 minimum)

Create middleware.ts in your project root:

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 (proxy.ts)

Create proxy.ts in your project root:

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*'],
};

Create instrumentation.ts in your project root (or src/ if you use that directory):

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();
  }
}

That's it! Frontman will now:

  • Capture console logs, build output, and errors
  • Track Next.js HTTP requests, API routes, and rendering
  • Make all logs available via the Frontman UI at /frontman

Adding to Existing Files

If you already have middleware.ts, proxy.ts, or instrumentation.ts files, the installer will show you manual integration steps. Here's how to add Frontman to existing files:

Existing middleware.ts (Next.js 15.x, 15.5 minimum)

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*'],
};

Existing proxy.ts (Next.js 16.x)

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*'],
};

Existing instrumentation.ts

If you don't have OpenTelemetry set up yet:

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
}

If you already have OpenTelemetry set up, add the Frontman processors to your existing configuration:

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();
  }
}

What Gets Captured

Automatic Console Patching (Node.js only)

LogCapture automatically initializes when the module is imported and patches:

  • All console methods: console.log(), console.error(), console.warn(), console.info(), console.debug()
  • process.stdout.write() for build output (webpack/turbopack compilation messages)
  • process.on('uncaughtException') for unhandled errors
  • process.on('unhandledRejection') for unhandled promise rejections

Browser environments are automatically skipped - no console patching occurs in the browser.

Via OpenTelemetry Spans (Optional)

When you set up instrumentation.ts:

  • HTTP requests (BaseServer.handleRequest)
  • Route rendering (AppRender.getBodyResult)
  • API route execution (AppRouteRouteHandlers.runHandler)
  • Request method, path, status code, duration

Storage & Cross-Context Sharing

All captured data is stored in a circular buffer (1024 entries by default) using a globalThis singleton pattern. This ensures logs are shared across Next.js/Turbopack execution contexts:

  • Instrumentation context (startup)
  • Page render context
  • API route context
  • Middleware context (Edge runtime - read-only)

The buffer persists for the lifetime of the Node.js process and is accessible through the Frontman UI and get_logs tool.

Configuration Options

Middleware Options

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())
})

Understanding the host Option

The host option specifies the Frontman server that the client UI will connect to for AI capabilities. When you visit /frontman in your Next.js app:

  1. The middleware serves the Frontman UI HTML
  2. The UI loads the client JavaScript with ?host=<your-host>
  3. The client establishes a WebSocket connection to wss://<host>/socket
  4. AI interactions and tool calls flow through this connection

The middleware itself doesn't connect to the Frontman server - it only passes the host to the client.

Examples:

  • Production: host: 'api.frontman.sh' → client connects to wss://api.frontman.sh/socket
  • Local dev: host: 'frontman.local:4000' → client connects to wss://frontman.local:4000/socket

Supported Next.js Versions

VersionMiddleware FileStatus
Next.js 15.x (15.5 minimum)middleware.tsFully supported
Next.js 16.xproxy.tsFully supported

Both versions have built-in OpenTelemetry support with no additional configuration required.

Architecture

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

Key Technical Details

Cross-Context Buffer Sharing

  • Supported Next.js versions with Turbopack run code in multiple isolated contexts
  • globalThis.__FRONTMAN_INSTANCE__ stores the singleton buffer instance
  • All contexts read/write to the same circular buffer
  • Console patching happens only once (protected by __FRONTMAN_CONSOLE_PATCHED__ flag)

Circular Buffer

  • Fixed capacity: 1024 entries (configurable)
  • Oldest entries automatically evicted when full
  • Entries include: timestamp, level, message, attributes, consoleMethod
  • Thread-safe for concurrent writes from different contexts

Advanced Usage

Custom OTEL Configuration

If you need more control over OpenTelemetry setup:

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();
  }
}

Without OpenTelemetry

Frontman works without OpenTelemetry! If you only set up middleware (skip instrumentation.ts):

  • Console logs are still captured (auto-initialized at module import)
  • Build output is tracked
  • Errors are logged
  • Frontman UI available at /frontman
  • HTTP spans are not captured (requires OTEL)

LogCapture auto-initializes when the module is imported, so console patching happens automatically in Node.js environments - no explicit initialization needed.

Custom LogCapture Configuration

You can customize the buffer size and stdout patterns:

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'],
});

Note: Configuration only takes effect on the first call. Subsequent calls are ignored because the singleton instance is already created.

Troubleshooting

Logs not being captured

Check 1: Verify module is imported LogCapture only initializes when the module is imported in a Node.js context. Make sure either:

  • You have instrumentation.ts that imports from @frontman-ai/nextjs/Instrumentation
  • OR you have middleware.ts that imports from @frontman-ai/nextjs

Check 2: Verify Node.js runtime LogCapture doesn't run in browser or Edge runtime. Check your environment:

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

Check 3: Verify buffer contents Query the buffer directly to see if logs are present:

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

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

Check 4: Multiple contexts In supported Next.js versions, code may run in different contexts. Verify that all contexts share the same buffer:

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

Console logs appear twice

This is normal behavior - LogCapture captures logs AND calls the original console method so logs still appear in your terminal/browser console.

Build output not captured

By default, only these patterns are captured from process.stdout:

  • "webpack"
  • "turbopack"
  • "Compiled"
  • "Failed"

To capture additional patterns, use custom configuration (see above).

Installer shows "manual modification required"

This happens when you have existing middleware, proxy, or instrumentation files that don't already include Frontman. The installer won't overwrite your existing code. Follow the Adding to Existing Files instructions to manually integrate Frontman.

API

createMiddleware(options)

Creates a Next.js middleware handler that serves the Frontman UI and connects to your Frontman server.

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())
});

Returns: (request: NextRequest) => Promise<NextResponse | undefined>

setup()

Initializes LogCapture (console patching, error handlers) and returns OTEL processors for use with OpenTelemetry SDK.

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

const [logProcessor, spanProcessor] = setup();

Returns: [LogRecordProcessor, SpanProcessor]

initialize(config?)

Manually initialize LogCapture with custom configuration. Usually not needed since auto-initialization happens at module import.

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

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

Returns: void

getLogs(options?)

Query the log buffer with optional filters.

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
});

Returns: LogEntry[]

LogEntry type:

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
};

License

MIT

版本与发布记录

@frontman-ai/nextjs 共发布 41 个版本,首次发布于 2026/01/30;过去 12 个月发布了 41 个版本。

版本发布日期距今
2.0.4latest2026/10/2720 天前
2.0.32026/10/2125 天前
2.0.22026/10/071 个月前
2.0.12026/09/291 个月前
2.0.02026/09/042 个月前
1.0.62026/08/282 个月前

关于 @frontman-ai/nextjs 的常见问题

@frontman-ai/nextjs 是什么?

Next.js integration for Frontman - AI-powered development tools and observability

如何安装 @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 和提交记录判断。