server-actions-vs-api-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Server Actions vs API Routes Optimizer

Server Actions vs API Routes 优化器

Analyze existing routes and recommend whether to use Server Actions or traditional API routes based on specific use case patterns, including authentication flows, data revalidation, external API calls, and client requirements.
根据认证流程、数据重新验证、外部API调用和客户端需求等特定用例模式,分析现有路由并推荐使用Server Actions还是传统API routes。

Core Capabilities

核心能力

1. Analyze Existing Routes

1. 分析现有路由

To analyze current route architecture:
  • Scan app directory for route handlers and Server Actions
  • Identify patterns in request/response handling
  • Detect authentication, revalidation, and external API usage
  • Use
    scripts/analyze_routes.py
    for automated analysis
要分析当前路由架构:
  • 扫描app目录中的route handler和Server Actions
  • 识别请求/响应处理模式
  • 检测认证、重新验证和外部API的使用情况
  • 使用
    scripts/analyze_routes.py
    进行自动化分析

2. Provide Recommendations

2. 提供推荐方案

Based on analysis, provide recommendations using the decision matrix from
references/decision_matrix.md
:
  • Server Actions: Form submissions, mutations with revalidation, simple data updates
  • API Routes: External API proxying, webhooks, third-party integrations, non-form mutations
  • Hybrid Approach: Complex flows requiring both patterns
基于分析结果,使用
references/decision_matrix.md
中的决策矩阵提供推荐:
  • Server Actions:表单提交、带重新验证的数据变更、简单数据更新
  • API Routes:外部API代理、Webhook、第三方集成、非表单类变更操作
  • 混合方案:需要同时使用两种模式的复杂流程

3. Generate Migration Plans

3. 生成迁移计划

When refactoring is recommended:
  • Identify specific routes to convert
  • Provide step-by-step migration instructions
  • Show before/after code examples
  • Highlight breaking changes and client updates needed
当推荐进行重构时:
  • 识别需要转换的特定路由
  • 提供分步迁移说明
  • 展示代码示例的前后对比
  • 突出说明破坏性变更和需要更新的客户端内容

When to Use Server Actions

何时使用Server Actions

Prefer Server Actions for:
  1. Form Submissions: Direct form action handling with progressive enhancement
  2. Data Mutations with Revalidation: Operations that need
    revalidatePath()
    or
    revalidateTag()
  3. Simple CRUD Operations: Direct database mutations from components
  4. Authentication in RSC: Auth checks in Server Components
  5. File Uploads: Handling FormData directly
  6. Optimistic Updates: Client-side optimistic UI with server validation
Benefits:
  • Automatic POST request handling
  • Built-in CSRF protection
  • Type-safe with TypeScript
  • Progressive enhancement (works without JS)
  • Direct access to server-side resources
  • Simpler code for common patterns
优先选择Server Actions的场景:
  1. 表单提交:支持渐进式增强的直接表单动作处理
  2. 带重新验证的数据变更:需要使用
    revalidatePath()
    revalidateTag()
    的操作
  3. 简单CRUD操作:从组件直接进行数据库变更
  4. RSC中的认证:在Server Components中进行权限检查
  5. 文件上传:直接处理FormData
  6. 乐观更新:客户端乐观UI结合服务端验证
优势:
  • 自动处理POST请求
  • 内置CSRF保护
  • 与TypeScript兼容的类型安全
  • 渐进式增强(无JS环境下也可运行)
  • 可直接访问服务端资源
  • 常见模式下代码更简洁

When to Use API Routes

何时使用API Routes

Prefer API routes for:
  1. External API Proxying: Hiding API keys, rate limiting, response transformation
  2. Webhooks: Third-party service callbacks (Stripe, GitHub, etc.)
  3. Non-POST Operations: GET, PUT, DELETE, PATCH endpoints
  4. Third-Party Integrations: OAuth callbacks, external service authentication
  5. Public APIs: Endpoints called by external clients
  6. Complex Response Headers: Custom headers, cookies, redirects
  7. Non-Form Client Requests: fetch() calls from client components
  8. SSE/Streaming: Server-sent events or custom streaming
Benefits:
  • Full HTTP method support
  • Custom response handling
  • External accessibility
  • Middleware support
  • Standard REST API patterns
优先选择API Routes的场景:
  1. 外部API代理:隐藏API密钥、限流、响应转换
  2. Webhook:第三方服务回调(如Stripe、GitHub等)
  3. 非POST操作:GET、PUT、DELETE、PATCH端点
  4. 第三方集成:OAuth回调、外部服务认证
  5. 公开API:供外部客户端调用的端点
  6. 复杂响应头:自定义头、Cookie、重定向
  7. 非表单客户端请求:客户端组件中的fetch()调用
  8. SSE/流式传输:Server-sent events或自定义流式传输
优势:
  • 支持完整的HTTP方法
  • 自定义响应处理
  • 外部可访问性
  • 支持中间件
  • 标准REST API模式

Analysis Workflow

分析流程

1. Run Automated Analysis

1. 运行自动化分析

Use the analysis script to scan your codebase:
bash
python scripts/analyze_routes.py --path /path/to/app --output analysis-report.md
The script identifies:
  • Existing API routes and their patterns
  • Server Actions usage
  • Authentication patterns
  • Revalidation calls
  • External API integrations
  • Potential optimization opportunities
使用分析脚本扫描代码库:
bash
python scripts/analyze_routes.py --path /path/to/app --output analysis-report.md
该脚本会识别:
  • 现有API路由及其模式
  • Server Actions的使用情况
  • 认证模式
  • 重新验证调用
  • 外部API集成
  • 潜在的优化机会

2. Review Decision Matrix

2. 查看决策矩阵

Consult
references/decision_matrix.md
for detailed decision criteria:
  • Use case patterns
  • Trade-offs analysis
  • Performance considerations
  • Security implications
  • Developer experience factors
参考
references/decision_matrix.md
获取详细决策标准:
  • 用例模式
  • 权衡分析
  • 性能考量
  • 安全影响
  • 开发者体验因素

3. Generate Recommendations

3. 生成推荐方案

For each route, determine:
  • Current implementation pattern
  • Recommended pattern (Server Action or API route)
  • Reasoning based on use case
  • Migration complexity (low/medium/high)
  • Potential benefits of refactoring
针对每个路由,确定:
  • 当前实现模式
  • 推荐模式(Server Action或API route)
  • 基于用例的理由
  • 迁移复杂度(低/中/高)
  • 重构的潜在收益

4. Create Migration Plan

4. 创建迁移计划

For routes requiring changes:
  • Prioritize high-impact, low-complexity migrations
  • Document breaking changes
  • Provide code transformation examples
  • Update client-side code if needed
针对需要变更的路由:
  • 优先处理高影响、低复杂度的迁移
  • 记录破坏性变更
  • 提供代码转换示例
  • 必要时更新客户端代码

Common Patterns and Recommendations

常见模式与推荐方案

Pattern: Form Submission with DB Update

模式:表单提交结合数据库更新

Current: API route with fetch from client Recommended: Server Action Reason: Simpler, built-in CSRF protection, progressive enhancement
typescript
// Before (API Route)
// app/api/entities/route.ts
export async function POST(request: Request) {
  const data = await request.json();
  await db.entity.create(data);
  return Response.json({ success: true });
}

// After (Server Action)
// app/actions.ts
'use server';
export async function createEntity(formData: FormData) {
  await db.entity.create(Object.fromEntries(formData));
  revalidatePath('/entities');
}
当前实现:客户端通过fetch调用API路由 推荐方案:Server Action 理由:更简洁、内置CSRF保护、支持渐进式增强
typescript
// Before (API Route)
// app/api/entities/route.ts
export async function POST(request: Request) {
  const data = await request.json();
  await db.entity.create(data);
  return Response.json({ success: true });
}

// After (Server Action)
// app/actions.ts
'use server';
export async function createEntity(formData: FormData) {
  await db.entity.create(Object.fromEntries(formData));
  revalidatePath('/entities');
}

Pattern: External API Proxy

模式:外部API代理

Current: Client-side fetch to external API (exposes keys) Recommended: API route Reason: Hide API keys, rate limiting, response transformation
typescript
// Recommended: API Route
// app/api/external-service/route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const query = searchParams.get('query');

  const response = await fetch(`https://api.external.com?key=${process.env.API_KEY}&q=${query}`);
  const data = await response.json();

  return Response.json(data);
}
当前实现:客户端直接调用外部API(暴露密钥) 推荐方案:API路由 理由:隐藏API密钥、限流、响应转换
typescript
// Recommended: API Route
// app/api/external-service/route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const query = searchParams.get('query');

  const response = await fetch(`https://api.external.com?key=${process.env.API_KEY}&q=${query}`);
  const data = await response.json();

  return Response.json(data);
}

Pattern: Webhook Handler

模式:Webhook处理器

Current: None (new feature) Recommended: API route Reason: External service calls, needs public URL
typescript
// Recommended: API Route
// app/api/webhooks/stripe/route.ts
export async function POST(request: Request) {
  const signature = request.headers.get('stripe-signature');
  const body = await request.text();

  // Verify webhook signature
  // Process webhook event

  return Response.json({ received: true });
}
当前实现:无(新功能) 推荐方案:API路由 理由:外部服务调用,需要公开URL
typescript
// Recommended: API Route
// app/api/webhooks/stripe/route.ts
export async function POST(request: Request) {
  const signature = request.headers.get('stripe-signature');
  const body = await request.text();

  // Verify webhook signature
  // Process webhook event

  return Response.json({ received: true });
}

Pattern: Data Mutation with Revalidation

模式:带重新验证的数据变更

Current: API route with manual cache invalidation Recommended: Server Action Reason: Built-in revalidation, simpler code
typescript
// Before (API Route)
// app/api/entities/[id]/route.ts
export async function PATCH(request: Request, { params }) {
  const data = await request.json();
  await db.entity.update({ where: { id: params.id }, data });
  revalidatePath('/entities');
  return Response.json({ success: true });
}

// After (Server Action)
// app/actions.ts
'use server';
export async function updateEntity(id: string, data: any) {
  await db.entity.update({ where: { id }, data });
  revalidatePath('/entities');
  revalidateTag(`entity-${id}`);
}
当前实现:手动缓存失效的API路由 推荐方案:Server Action 理由:内置重新验证,代码更简洁
typescript
// Before (API Route)
// app/api/entities/[id]/route.ts
export async function PATCH(request: Request, { params }) {
  const data = await request.json();
  await db.entity.update({ where: { id: params.id }, data });
  revalidatePath('/entities');
  return Response.json({ success: true });
}

// After (Server Action)
// app/actions.ts
'use server';
export async function updateEntity(id: string, data: any) {
  await db.entity.update({ where: { id }, data });
  revalidatePath('/entities');
  revalidateTag(`entity-${id}`);
}

Pattern: Authentication Check

模式:权限检查

Current: API middleware Recommended: Server Action for mutations, API route for public endpoints Reason: Simpler auth in Server Components
typescript
// Server Action (for mutations)
'use server';
export async function protectedAction() {
  const session = await auth();
  if (!session) throw new Error('Unauthorized');
  // Perform action
}

// API Route (for public/external access)
export async function POST(request: Request) {
  const token = request.headers.get('authorization');
  if (!validateToken(token)) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }
  // Process request
}
当前实现:API中间件 推荐方案:变更操作使用Server Action,公开端点使用API路由 理由:Server Components中的认证更简洁
typescript
// Server Action (for mutations)
'use server';
export async function protectedAction() {
  const session = await auth();
  if (!session) throw new Error('Unauthorized');
  // Perform action
}

// API Route (for public/external access)
export async function POST(request: Request) {
  const token = request.headers.get('authorization');
  if (!validateToken(token)) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }
  // Process request
}

Resource Files

资源文件

scripts/analyze_routes.py

scripts/analyze_routes.py

Automated route analysis tool that scans your Next.js app directory to identify route patterns, Server Actions, authentication usage, revalidation calls, and external API integrations. Generates a detailed report with recommendations.
自动化路由分析工具,扫描Next.js app目录以识别路由模式、Server Actions、认证使用情况、重新验证调用和外部API集成。生成包含推荐方案的详细报告。

references/decision_matrix.md

references/decision_matrix.md

Comprehensive decision matrix with detailed criteria for choosing between Server Actions and API routes. Includes use case patterns, trade-offs, performance considerations, security implications, and real-world examples.
全面的决策矩阵,包含选择Server Actions和API routes的详细标准。包括用例模式、权衡因素、性能考量、安全影响和实际示例。

Best Practices

最佳实践

  1. Default to Server Actions for Forms: Simpler, more secure, better UX
  2. Use API Routes for External Integration: Webhooks, proxies, third-party APIs
  3. Consider Progressive Enhancement: Server Actions work without JavaScript
  4. Optimize for Revalidation: Server Actions have built-in revalidation
  5. Evaluate Client Requirements: If external clients need access, use API routes
  6. Think About Method Requirements: Non-POST operations need API routes
  7. Consider Type Safety: Server Actions are fully type-safe
  8. Plan for Migration: Start with new features, gradually refactor existing
  1. 表单默认使用Server Actions:更简洁、更安全、用户体验更好
  2. 外部集成使用API Routes:Webhook、代理、第三方API
  3. 考虑渐进式增强:Server Actions在无JavaScript环境下也可运行
  4. 针对重新验证优化:Server Actions内置重新验证功能
  5. 评估客户端需求:如果需要供外部客户端访问,使用API routes
  6. 考虑方法需求:非POST操作需要使用API routes
  7. 考虑类型安全:Server Actions完全支持类型安全
  8. 规划迁移:从新功能开始,逐步重构现有内容

Integration with Worldbuilding App

与世界构建应用的集成

Common patterns in worldbuilding applications:
世界构建应用中的常见模式:

Entity CRUD Operations

实体CRUD操作

  • Create/Update/Delete entities: Server Actions (form submissions with revalidation)
  • Get entity list for external dashboard: API route (external client access)
  • 创建/更新/删除实体:Server Actions(带重新验证的表单提交)
  • 为外部仪表板获取实体列表:API route(供外部客户端访问)

Relationship Management

关系管理

  • Add/remove relationships: Server Actions (mutations with revalidation)
  • Export relationship graph: API route (complex response, streaming)
  • 添加/移除关系:Server Actions(带重新验证的变更操作)
  • 导出关系图:API route(复杂响应、流式传输)

Timeline Operations

时间线操作

  • Create/edit timeline events: Server Actions (form submissions)
  • Timeline data feed for visualization: API route (GET requests, caching)
  • 创建/编辑时间线事件:Server Actions(表单提交)
  • 用于可视化的时间线数据源:API route(GET请求、缓存)

Search and Filtering

搜索与筛选

  • Filter entities in app: Server Actions (with revalidation)
  • Public search API: API route (external access, rate limiting)
  • 应用内筛选实体:Server Actions(带重新验证)
  • 公开搜索API:API route(外部访问、限流)

Import/Export

导入/导出

  • Import data files: Server Action (FormData handling)
  • Export to external format: API route (custom headers, streaming)
Consult
references/decision_matrix.md
for detailed analysis of each pattern.
  • 导入数据文件:Server Action(处理FormData)
  • 导出为外部格式:API route(自定义头、流式传输)
参考
references/decision_matrix.md
获取每种模式的详细分析。