OpenClaw 与 Next.js 集成有多种方法,具体取决于您的使用场景,以下是主要集成方式:

作为独立微服务集成
方案 A:API 网关模式
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/claw/:path*',
destination: 'http://openclaw-service/api/:path*',
},
];
},
};
方案 B:直接 API 调用
// lib/openclaw-client.js
export class OpenClawClient {
constructor(baseURL) {
this.baseURL = process.env.OPENCLAW_API_URL;
}
async executeWorkflow(workflowId, data) {
const response = await fetch(`${this.baseURL}/workflows/${workflowId}/execute`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return response.json();
}
}
作为 React 组件集成
方案 A:iframe 嵌入
// components/OpenClawEmbed.jsx
'use client';
export default function OpenClawEmbed({ workflowId }) {
return (
<iframe
src={`${process.env.NEXT_PUBLIC_OPENCLAW_URL}/embed/${workflowId}`}
className="w-full h-[500px] border-0"
allow="clipboard-write"
/>
);
}
方案 B:SDK 集成(OpenClaw 提供)
// pages/workflow-runner.jsx
'use client';
import { OpenClawRunner } from '@openclaw/react-sdk';
import { useState } from 'react';
export default function WorkflowPage() {
const [result, setResult] = useState(null);
return (
<div>
<OpenClawRunner
workflowId="your-workflow-id"
apiKey={process.env.NEXT_PUBLIC_OPENCLAW_API_KEY}
onComplete={(data) => setResult(data)}
/>
{result && <pre>{JSON.stringify(result, null, 2)}</pre>}
</div>
);
}
Serverless Function 集成
API Route 封装
// app/api/workflow/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// 调用 OpenClaw API
const response = await fetch(
`${process.env.OPENCLAW_API_URL}/workflows/execute`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENCLAW_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
}
);
const data = await response.json();
return NextResponse.json(data);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to execute workflow' },
{ status: 500 }
);
}
}
环境配置
OPENCLAW_API_URL=http://openclaw-service:8080
OPENCLAW_API_KEY=your-api-key
// lib/config.js
export const openclawConfig = {
apiUrl: process.env.OPENCLAW_API_URL,
publicUrl: process.env.NEXT_PUBLIC_OPENCLAW_URL,
apiKey: process.env.OPENCLAW_API_KEY,
};
完整集成示例
工作流执行页面
// app/workflow/page.tsx
import OpenClawForm from '@/components/OpenClawForm';
import { executeWorkflow } from '@/actions/workflow';
export default function WorkflowPage() {
async function handleSubmit(formData: FormData) {
'use server';
const data = Object.fromEntries(formData);
const result = await executeWorkflow('data-processing', data);
// 处理结果...
return result;
}
return (
<div className="container mx-auto p-8">
<h1 className="text-2xl font-bold mb-6">OpenClaw 工作流</h1>
<OpenClawForm
workflowId="data-processing"
onSubmit={handleSubmit}
/>
</div>
);
}
Server Action
// actions/workflow.ts
'use server';
import { openclawConfig } from '@/lib/config';
export async function executeWorkflow(workflowId: string, data: any) {
try {
const response = await fetch(
`${openclawConfig.apiUrl}/workflows/${workflowId}/execute`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${openclawConfig.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ inputs: data }),
}
);
if (!response.ok) {
throw new Error('Failed to execute workflow');
}
return await response.json();
} catch (error) {
console.error('Workflow execution error:', error);
throw error;
}
}
安全考虑
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// 验证 OpenClaw webhook 签名
if (request.nextUrl.pathname.startsWith('/api/openclaw/webhook')) {
const signature = request.headers.get('x-openclaw-signature');
const isValid = verifySignature(signature, request.body);
if (!isValid) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
}
return NextResponse.next();
}
// 配置中间件匹配路径
export const config = {
matcher: '/api/openclaw/:path*',
};
部署配置
Docker Compose(本地开发)
# docker-compose.yml
version: '3.8'
services:
nextjs-app:
build: .
ports:
- "3000:3000"
environment:
- OPENCLAW_API_URL=http://openclaw:8080
depends_on:
- openclaw
openclaw:
image: openclaw/openclaw:latest
ports:
- "8080:8080"
environment:
- DATABASE_URL=postgresql://...
最佳实践建议
- API 版本控制:在集成时指定 OpenClaw API 版本
- 错误处理:实现完善的错误处理和重试机制
- 监控:集成日志和监控
- 缓存:对频繁调用结果进行缓存
- 类型安全:为 OpenClaw API 响应定义 TypeScript 类型
选择哪种集成方式取决于:
- OpenClaw 的部署方式(独立服务 vs 嵌入)
- 性能要求
- 安全需求
- 团队的技术栈偏好
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。