理解 Next.js API Routes 机制、rewrites 代理、Agent/MCP/Prompt 等核心 API
本课程聚焦 src/app/api/ 目录,它是 Kuai 前端的后端接口层。Next.js App Router 的 API Routes 运行在服务端,可以直接访问数据库、调用外部服务,是前端和 Java 后端/MongoDB 之间的桥梁。
route.js 文件的作用在 Next.js App Router 中,src/app/api/ 目录下的 route.js 文件自动成为 API 端点。文件路径就是 URL 路径:
| 文件路径 | API 端点 | HTTP 方法 |
|---|---|---|
src/app/api/agents/route.js |
GET /api/agents |
GET |
src/app/api/agents/[id]/chat/route.js |
POST /api/agents/:id/chat |
POST |
src/app/api/share/[shareId]/chat/route.js |
POST /api/share/:shareId/chat |
POST |
src/app/api/session-data/[sessionId]/route.js |
GET /api/session-data/:sessionId |
GET |
// src/app/api/agents/route.js
// 运行时配置
export const runtime = 'nodejs'; // 使用 Node.js runtime(非 Edge)
// 导出 HTTP 方法处理函数
export async function GET(request) {
// request: NextRequest 对象
const { searchParams } = new URL(request.url);
const agentId = searchParams.get('id');
// 业务逻辑...
const agents = await agentRegistry.getAll();
// 返回 JSON 响应
return NextResponse.json(agents, {
status: 200,
headers: { 'Access-Control-Allow-Origin': '*' },
});
}
// src/app/api/agents/[id]/chat/route.js
// params 是动态路由参数
export async function POST(request, { params }) {
const { id: agentId } = await params; // 注意:需要 await
// ...
}
在 Next.js 16 中,params 是一个 Promise,需要使用 await 解构。这是从 Next.js 15 开始的变化。
// Next.js 16 正确写法
const { id } = await params;
// 旧写法(Next.js 14 及之前)
const { id } = params; // 不需要 await
架构设计 前端 API 层并不是所有请求都自己处理,很多请求通过 next.config.js 的 rewrites 配置代理到 Java 后端。
/api/xxx,不需要关心后端地址// next.config.js (简化)
module.exports = {
async rewrites() {
return [
// 排除规则:这些路径由 Next.js 自己处理,不代理
// (必须放在 rewrites 数组前面)
// 代理规则:其他 /api/xxx 请求转发到 Java 后端
{
source: '/api/:path*',
destination: 'http://kuai-backend:8080/api/:path*',
},
];
},
};
如果新增一个 Next.js API Route(如 /api/my-feature),必须在 rewrites 中添加排除规则,否则请求会被代理到 Java 后端:
// next.config.js
async rewrites() {
return [
// 1. 先排除 Next.js 自己处理的路径
{ source: '/api/my-feature/:path*', destination: '/api/my-feature/:path*' },
{ source: '/api/agents/:path*', destination: '/api/agents/:path*' },
// ...其他排除规则
// 2. 最后是通用代理规则
{ source: '/api/:path*', destination: 'http://kuai-backend:8080/api/:path*' },
];
}
src/app/api/agents/route.js 提供已注册 Agent 的元数据查询。
// 查询参数
// ?public=true → 只返回公开 Agent(默认)
// ?public=false → 返回所有 Agent
// ?id=xxx → 返回特定 Agent
export async function GET(request) {
const { searchParams } = new URL(request.url);
const agentId = searchParams.get('id');
const showPublic = searchParams.get('public') !== 'false';
if (agentId) {
// 查询单个 Agent
const definition = await agentRegistry.getDefinition(agentId);
if (!definition) {
return NextResponse.json(
{ error: { code: 'AGENT_NOT_FOUND' } },
{ status: 404 }
);
}
return NextResponse.json(definition);
}
// 查询 Agent 列表
const agents = await agentRegistry.getAll();
const filtered = showPublic
? agents.filter(a => a.isPublic)
: agents;
return NextResponse.json(filtered);
}
src/app/api/agents/[id]/chat/route.js 是最核心的 API,处理 Agent 对话请求。
// 请求体结构
{
"message": "帮我分析这个代码", // 用户消息
"sessionId": "abc123", // 可选,续接已有会话
"userId": "user1", // 用户 ID
"userName": "张三", // 用户名
"initialFormData": {}, // 表单数据(Agent 初始化参数)
"runtimeSkills": [], // 运行时技能
"modelKey": "gpt-4", // 模型选择
"xmindData": {} // XMind 数据(测试用例 Agent)
}
agentRegistry 获取 Agent 定义createAgentStreamResponse() 启动流式响应// Agent 对话 API 的特殊配置
export const runtime = 'nodejs'; // 必须用 Node.js(不能用 Edge)
export const maxDuration = 1800; // 最大执行时间 30 分钟
// 为什么是 30 分钟?
// Agent 可能执行复杂的多步骤任务(代码分析、文件操作等)
// 普通 API 通常 10 秒就够了,但 Agent 对话需要长时间运行
API MCP 相关的 API 通过代理方式实现。
src/app/api/proxy/mcphub/[...path]/route.js 是一个全能代理,支持所有 HTTP 方法:
// 支持的 HTTP 方法
export async function GET(request, { params }) { ... }
export async function POST(request, { params }) { ... }
export async function PUT(request, { params }) { ... }
export async function DELETE(request, { params }) { ... }
export async function PATCH(request, { params }) { ... }
export async function OPTIONS(request, { params }) { ... }
// 使用示例
// GET /api/proxy/mcphub/servers → MCPHub 的服务器列表
// POST /api/proxy/mcphub/servers → 创建 MCP Server
// GET /api/proxy/mcphub/servers/:id → 获取 Server 详情
// PUT /api/proxy/mcphub/servers/:id → 更新 Server
MCP 工具在 Agent 中的实际加载通过 src/agents/tools/mcpLoader.js 完成,它使用 @langchain/mcp-adapters 库直接连接 MCP Server,不经过这个代理。代理主要用于 MCP 管理页面的 CRUD 操作。
Prompt 管理的 API 全部在 Java 后端,前端通过服务层 src/services/modules/prompt.js 调用。由于 rewrites 配置,前端调用 /api/prompts/xxx 会被自动代理到 Java 后端。
// src/services/modules/prompt.js (示意)
import { get, post, put, del } from '@/services/request';
// 获取 Prompt 列表
export const getPrompts = (params) => get('/api/prompts', params);
// 获取 Prompt 详情
export const getPromptById = (id) => get(`/api/prompts/${id}`);
// 创建 Prompt
export const createPrompt = (data) => post('/api/prompts', data);
// 更新 Prompt
export const updatePrompt = (id, data) => put(`/api/prompts/${id}`, data);
// 获取版本列表
export const getPromptVersions = (id) => get(`/api/prompts/${id}/versions`);
除了前端页面的 CRUD,Agent 运行时也有 Prompt 管理逻辑(src/lib/agents/prompt.js):
{{variable}})| 端点 | 方法 | 说明 |
|---|---|---|
/api/chat-history/[sessionId] |
GET | 获取会话的完整聊天历史 |
/api/session-data/[sessionId] |
GET | 获取会话的元数据 |
| 端点 | 方法 | 说明 |
|---|---|---|
/api/share/[shareId]/chat |
POST | 通过分享链接进行对话 |
/api/share/[shareId]/sessions |
GET | 获取分享的会话列表 |
/api/share/[shareId]/skill |
GET | 获取分享的技能 |
| 端点 | 方法 | 说明 |
|---|---|---|
/api/knowledge |
GET/POST | 知识库 CRUD |
/api/knowledge/[userId] |
GET | 用户知识库 |
/api/knowledge/extract |
POST | 知识提取(AI 辅助) |
| 端点 | 方法 | 说明 |
|---|---|---|
/api/agent-schedules |
GET/POST | Agent 定时任务管理 |
// 大多数 API 使用这种模式
export async function GET(request) {
const data = await fetchData();
return NextResponse.json(data, { status: 200 });
}
// Agent 对话 API 使用流式响应
export async function POST(request) {
// ...
return createAgentStreamResponse(stream);
// 返回的是 ReadableStream,前端通过 SSE 消费
}
// 需要跨域访问的 API 添加 CORS 头
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};
当你在 src/app/api/ 下新增一个 /api/my-feature/route.js,但没有在 next.config.js 中添加排除规则,会发生什么?
next.config.js 中有通用代理规则 { source: '/api/:path*', destination: 'http://kuai-backend:8080/api/:path*' },所有 /api/ 开头的请求都会被代理到 Java 后端。Next.js API Route 不会自动"优先匹配",必须在 rewrites 中添加排除规则才能让 Next.js 自己处理。这是项目中最容易踩的坑之一。
Agent Chat API 的 maxDuration 设置为 1800 秒(30 分钟),为什么要这么长?
maxDuration 设置为 1800 秒(30 分钟)。同时 runtime = 'nodejs' 确保不使用 Edge Runtime(Edge 有执行时间限制)。
以下哪种说法正确描述了项目的 API 架构?
rewrites 配置,前端统一调用 /api/xxx,不需要知道实际处理请求的是哪个服务。Next.js API Route 优先级需要通过排除规则来控制。