guides

分析

追踪哪些 AI 爬虫读取了你的内容,哪些 agent 调用了你的 action。

next-ai-ready 提供两个 hook 来追踪 AI 消费者活动,无需添加外部依赖。

设置

Next.js 会在 Node.js 和 Edge 两种运行时加载 instrumentation.ts。请通过 `next-ai-ready/hooks` 子路径(不要用主包入口)在 Node 专用文件中注册 hook,避免 Turbopack 把构建期的 Node 模块打进 Edge bundle。

`instrumentation.ts`

ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    await import("./instrumentation-node");
  }
}

`instrumentation-node.ts`

ts
import "server-only";
import { registerAiHooks } from "next-ai-ready/hooks";

registerAiHooks({
  onAiRequest: (info) => {
    console.log("AI 请求:", info.bot, info.artifact, info.path);
  },
  onInvoke: (info) => {
    console.log("Action 调用:", info.action, info.ok, info.latencyMs);
  },
});

npx next-ai-ready init 会自动生成这两个文件。

`onAiRequest`

当 AI 爬虫读取知识平面产物时触发。回调接收:

字段类型说明
botstring?检测到的爬虫名称(如 "GPTBot""ClaudeBot")。未识别时为 undefined
pathstring请求路径(如 /llms.txt/docs/intro.md)。
artifactstring产物类型:"llms-txt""page-md""page-ai-json""openapi""tools"
uastring原始 User-Agent 头。
methodstringHTTP 方法。

爬虫检测匹配以下 user agent:GPTBotOAI-SearchBotChatGPT-UserPerplexityBotClaudeBotanthropic-aiGoogle-ExtendedCCBotBytespiderApplebot-Extended

`onInvoke`

当通过 HTTP 或 MCP 调用 action 时触发。回调接收:

字段类型说明
actionstringAction 名称(如 "search_products")。
okboolean调用是否成功。
latencyMsnumberHandler 执行时间(毫秒)。
errorstring?okfalse 时的错误信息。
callerstring?"http""mcp"

示例:发送到分析服务

instrumentation-node.ts 中接入你的 SDK:

ts
import "server-only";
import { registerAiHooks } from "next-ai-ready/hooks";

registerAiHooks({
  onAiRequest: (info) => {
    analytics.track("ai_request", {
      bot: info.bot,
      artifact: info.artifact,
      path: info.path,
    });
  },
  onInvoke: (info) => {
    analytics.track("ai_invoke", {
      action: info.action,
      ok: info.ok,
      latencyMs: info.latencyMs,
      caller: info.caller,
    });
  },
});

Hook 机制

Hook 全局注册,由 route handler 在请求时调用。它们在 handler 执行上下文中同步运行——如果 hook 抛出异常,请求仍然正常完成(错误被吞掉)。

不需要外部依赖。Hook 被设计为薄集成点——自行引入你的分析 SDK。