api-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Integration Specialist (v2026.1)

API集成专家(v2026.1)

Expert guidance for integrating external APIs and LLMs into modern applications with production-ready patterns, security best practices, and autonomous agent capabilities.
为将外部API和LLM集成到现代应用提供专业指导,涵盖生产就绪模式、安全最佳实践和自主Agent能力。

1. Executive Summary: The 2026 Standard

1. 执行摘要:2026年标准

As of January 2026, API integration has shifted from simple REST calls to Autonomous Orchestration. Systems must now support:
  • Edge-First Execution: Minimum latency via Vercel Edge/Cloudflare Workers.
  • Agentic Logic: Integration with the GPT-5 family for complex reasoning.
  • Context-Aware Architecture: Using tools like Repomix to provide full repository context to AI agents.
  • High-Velocity Authentication: Migrating to Auth.js v5 for 25% faster session handling.
截至2026年1月,API集成已从简单的REST调用转变为自主编排。系统现在必须支持:
  • 边缘优先执行:通过Vercel Edge/Cloudflare Workers实现最低延迟。
  • Agent逻辑:与GPT-5系列集成以处理复杂推理。
  • 上下文感知架构:使用Repomix等工具为AI Agent提供完整的仓库上下文。
  • 高速身份验证:迁移到Auth.js v5,实现会话处理速度提升25%。

2. Core Integration Pillars

2. 核心集成支柱

2.1 Authentication & Security (Auth.js v5)

2.1 身份验证与安全(Auth.js v5)

The gold standard for 2026 is Auth.js v5, which provides a unified, secret-first approach optimized for the Edge.
2026年的黄金标准是Auth.js v5,它提供了针对边缘环境优化的统一、密钥优先方法。

The
AUTH_
Prefix Standard

AUTH_
前缀标准

All environment variables MUST now use the
AUTH_
prefix for automatic discovery by the framework. This ensures that the framework can securely handle these variables across different environments (Preview, Staging, Production) without manual mapping in your code.
bash
undefined
所有环境变量现在必须使用
AUTH_
前缀,以便框架自动发现。这确保框架可以在不同环境(预览、 staging、生产)中安全处理这些变量,无需在代码中手动映射。
bash
undefined

.env.local

.env.local

AUTH_SECRET=your_signing_secret_here # REQUIRED: Used for JWT signing AUTH_URL=https://myapp.com/api/auth # Base URL for the auth system AUTH_GOOGLE_ID=google_client_id # Provider specific AUTH_GOOGLE_SECRET=google_client_secret AUTH_GITHUB_ID=github_client_id AUTH_GITHUB_SECRET=github_client_secret
undefined
AUTH_SECRET=your_signing_secret_here # REQUIRED: Used for JWT signing AUTH_URL=https://myapp.com/api/auth # Base URL for the auth system AUTH_GOOGLE_ID=google_client_id # Provider specific AUTH_GOOGLE_SECRET=google_client_secret AUTH_GITHUB_ID=github_client_id AUTH_GITHUB_SECRET=github_client_secret
undefined

Edge-Compatible Configuration

边缘兼容配置

The configuration is designed to be lightweight. Heavy database adapters should be used sparingly in the main configuration file to ensure the Edge middleware remains performant.
typescript
// auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [Google],
  // 2026 Best Practice: Use JWT strategy for stateless, Edge-compatible sessions
  session: { strategy: "jwt" }, 
  pages: {
    signIn: "/auth/signin",
    error: "/auth/error",
  },
  callbacks: {
    async jwt({ token, user, account }) {
      // Persist the OAuth access_token to the token right after signin
      if (account && user) {
        token.accessToken = account.access_token;
        token.id = user.id;
      }
      return token;
    },
    async session({ session, token }) {
      // Send properties to the client, like an access_token from a provider.
      session.accessToken = token.accessToken as string;
      session.user.id = token.id as string;
      return session;
    },
    // The authorized callback is used to verify if the request is authorized via Next.js Middleware.
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isApiRoute = nextUrl.pathname.startsWith("/api")
      const isPublicPath = nextUrl.pathname === "/public"
      
      if (isApiRoute && !isLoggedIn) return false
      if (isPublicPath) return true
      
      return isLoggedIn
    },
  },
})
配置设计为轻量级。主配置文件中应尽量少用重型数据库适配器,以确保边缘中间件保持高性能。
typescript
// auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [Google],
  // 2026 Best Practice: Use JWT strategy for stateless, Edge-compatible sessions
  session: { strategy: "jwt" }, 
  pages: {
    signIn: "/auth/signin",
    error: "/auth/error",
  },
  callbacks: {
    async jwt({ token, user, account }) {
      // Persist the OAuth access_token to the token right after signin
      if (account && user) {
        token.accessToken = account.access_token;
        token.id = user.id;
      }
      return token;
    },
    async session({ session, token }) {
      // Send properties to the client, like an access_token from a provider.
      session.accessToken = token.accessToken as string;
      session.user.id = token.id as string;
      return session;
    },
    // The authorized callback is used to verify if the request is authorized via Next.js Middleware.
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isApiRoute = nextUrl.pathname.startsWith("/api")
      const isPublicPath = nextUrl.pathname === "/public"
      
      if (isApiRoute && !isLoggedIn) return false
      if (isPublicPath) return true
      
      return isLoggedIn
    },
  },
})

Performance Gains

性能提升

  • 25% Faster Sessions: v5 reduces database lookups by caching JWTs aggressively.
  • Edge Runtime: Full support for
    middleware.ts
    without Node.js polyfills, reducing cold starts to < 100ms.
  • 会话速度提升25%:v5通过主动缓存JWT减少数据库查询。
  • 边缘运行时:完全支持
    middleware.ts
    ,无需Node.js polyfill,将冷启动时间缩短至<100ms。

2.2 AI & Model Orchestration (GPT-5 & o3)

2.2 AI与模型编排(GPT-5 & o3)

Integrating the GPT-5 family requires understanding "Reasoning Tokens" and autonomous agent loops.
集成GPT-5系列需要理解“推理令牌”和自主Agent循环。

GPT-5 Reasoning Integration

GPT-5推理集成

GPT-5 models use "internal thought processes" before emitting tokens. This requires a different approach to timeouts and token limits.
typescript
import { generateText } from "ai"
import { gpt5 } from "@ai-sdk/openai"

/**
 * Executes a complex task using GPT-5 Reasoning.
 * reasoningTokens: Specifies the intensity of the "thought" process.
 */
async function executeAutonomousTask(goal: string) {
  // 1. Planning with GPT-5 Reasoning
  const plan = await generateText({
    model: gpt5("gpt-5-reasoning"),
    system: "You are a master architect. Plan the solution step-by-step.",
    prompt: goal,
    // Higher maxTokens for the "thought" process (RT - Reasoning Tokens)
    maxTokens: 8000 
  })

  console.log("GPT-5 Thought Process Completed. Executing Plan...");

  // 2. Execution with specialised sub-agents
  const result = await processPlanSteps(plan.text)
  return result
}
GPT-5模型在生成令牌前会进行“内部思考过程”。这需要不同的超时和令牌限制处理方式。
typescript
import { generateText } from "ai"
import { gpt5 } from "@ai-sdk/openai"

/**
 * Executes a complex task using GPT-5 Reasoning.
 * reasoningTokens: Specifies the intensity of the "thought" process.
 */
async function executeAutonomousTask(goal: string) {
  // 1. Planning with GPT-5 Reasoning
  const plan = await generateText({
    model: gpt5("gpt-5-reasoning"),
    system: "You are a master architect. Plan the solution step-by-step.",
    prompt: goal,
    // Higher maxTokens for the "thought" process (RT - Reasoning Tokens)
    maxTokens: 8000 
  })

  console.log("GPT-5 Thought Process Completed. Executing Plan...");

  // 2. Execution with specialised sub-agents
  const result = await processPlanSteps(plan.text)
  return result
}

o3-deep-research for Autonomous Data Gathering

o3-deep-research用于自主数据收集

The o3 model is designed for long-running, iterative research.
typescript
import { o3 } from "@ai-sdk/research"

/**
 * Conducts iterative deep research on a codebase or technical topic.
 */
const researchAgent = async (topic: string) => {
  const deepResearch = await o3.conductResearch({
    query: topic,
    maxDepth: 10,
    allowedTools: ["search", "arxiv", "github", "file_reader"],
    autonomousMode: true,
    // Reporting interval for progress updates
    onProgress: (update) => {
      console.log(`[Research Progress]: ${update.message}`);
    }
  })
  
  return deepResearch.summary
}
O3模型专为长期、迭代研究设计。
typescript
import { o3 } from "@ai-sdk/research"

/**
 * Conducts iterative deep research on a codebase or technical topic.
 */
const researchAgent = async (topic: string) => {
  const deepResearch = await o3.conductResearch({
    query: topic,
    maxDepth: 10,
    allowedTools: ["search", "arxiv", "github", "file_reader"],
    autonomousMode: true,
    // Reporting interval for progress updates
    onProgress: (update) => {
      console.log(`[Research Progress]: ${update.message}`);
    }
  })
  
  return deepResearch.summary
}

2.3 Financial Engineering (Stripe SDK v13+)

2.3 金融工程(Stripe SDK v13+)

Stripe SDK v13+ introduces native auto-pagination and expanded object types with deep TypeScript support.
Stripe SDK v13+引入原生自动分页和扩展对象类型,支持深度TypeScript。

Auto-Pagination Example

自动分页示例

Gone are the days of manual limit/starting_after loops.
typescript
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2025-10-14', // Ensure 2026 compatibility
});

async function cleanupStaleSubscriptions() {
  // list() returns an auto-paging iterable
  const subscriptions = stripe.subscriptions.list({
    status: 'past_due',
    limit: 100, // Still use limit for request chunking
  });

  // Native async iterator handles cursors automatically
  for await (const sub of subscriptions) {
    console.log(`Processing sub: ${sub.id}`);
    
    // Check if sub is older than 30 days
    const thirtyDaysAgo = Math.floor(Date.now() / 1000) - (30 * 24 * 60 * 60);
    if (sub.created < thirtyDaysAgo) {
      console.log(`Cancelling sub: ${sub.id} for customer ${sub.customer}`);
      await stripe.subscriptions.cancel(sub.id);
    }
  }
}
手动处理limit/starting_after循环的时代已一去不复返。
typescript
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2025-10-14', // Ensure 2026 compatibility
});

async function cleanupStaleSubscriptions() {
  // list() returns an auto-paging iterable
  const subscriptions = stripe.subscriptions.list({
    status: 'past_due',
    limit: 100, // Still use limit for request chunking
  });

  // Native async iterator handles cursors automatically
  for await (const sub of subscriptions) {
    console.log(`Processing sub: ${sub.id}`);
    
    // Check if sub is older than 30 days
    const thirtyDaysAgo = Math.floor(Date.now() / 1000) - (30 * 24 * 60 * 60);
    if (sub.created < thirtyDaysAgo) {
      console.log(`Cancelling sub: ${sub.id} for customer ${sub.customer}`);
      await stripe.subscriptions.cancel(sub.id);
    }
  }
}

Expanded Objects with Type Safety

带类型安全的扩展对象

typescript
/**
 * Retrieve a payment intent with full customer and payment method details.
 * The SDK automatically types the expanded fields.
 */
const paymentIntent = await stripe.paymentIntents.retrieve('pi_123', {
  expand: ['customer', 'payment_method'],
});

// Accessing expanded data safely with type narrowing
if (paymentIntent.customer && typeof paymentIntent.customer !== 'string') {
  console.log(`Customer Email: ${paymentIntent.customer.email}`);
}
typescript
/**
 * Retrieve a payment intent with full customer and payment method details.
 * The SDK automatically types the expanded fields.
 */
const paymentIntent = await stripe.paymentIntents.retrieve('pi_123', {
  expand: ['customer', 'payment_method'],
});

// Accessing expanded data safely with type narrowing
if (paymentIntent.customer && typeof paymentIntent.customer !== 'string') {
  console.log(`Customer Email: ${paymentIntent.customer.email}`);
}

3. Architectural Excellence

3. 架构卓越性

3.1 Monorepo Strategy (Bun & pnpm)

3.1 单仓库策略(Bun & pnpm)

Modern 2026 projects use Bun for execution speed and pnpm for strict dependency management.
2026年的现代项目使用Bun提升执行速度,使用pnpm进行严格的依赖管理。

Bun Workspace Configuration (
package.json
)

Bun工作区配置(
package.json

json
{
  "name": "squaads-monorepo",
  "workspaces": [
    "apps/*",
    "packages/*",
    "skills/*",
    "agents/*"
  ],
  "scripts": {
    "dev": "bun --filter \"*\" dev",
    "test": "bun test --recursive",
    "build": "bun x tsc --noEmit && bun run build:all"
  }
}
json
{
  "name": "squaads-monorepo",
  "workspaces": [
    "apps/*",
    "packages/*",
    "skills/*",
    "agents/*"
  ],
  "scripts": {
    "dev": "bun --filter \"*\" dev",
    "test": "bun test --recursive",
    "build": "bun x tsc --noEmit && bun run build:all"
  }
}

pnpm for Dependency Integrity

pnpm确保依赖完整性

bash
undefined
bash
undefined

Ensure no phantom dependencies

Ensure no phantom dependencies

pnpm install --frozen-lockfile
pnpm install --frozen-lockfile

Run a command in all packages

Run a command in all packages

pnpm -r exec bun run lint
undefined
pnpm -r exec bun run lint
undefined

3.2 Context Packing (Repomix)

3.2 上下文打包(Repomix)

To enable AI agents (like Gemini CLI) to understand the codebase, we use Repomix to pack context into a single, structured file.
bash
undefined
为了让AI Agent(如Gemini CLI)理解代码库,我们使用Repomix将上下文打包成单个结构化文件。
bash
undefined

Generate context for GPT-5 or o3 models

Generate context for GPT-5 or o3 models

This includes all logic while excluding noise

This includes all logic while excluding noise

bun x repomix --include "src//*.ts,lib//*.ts,package.json"
--exclude "node_modules,dist,.next,tests"
--output codebase-summary.md
undefined
bun x repomix --include "src//*.ts,lib//*.ts,package.json"
--exclude "node_modules,dist,.next,tests"
--output codebase-summary.md
undefined

3.3 Large Codebase Indexing (The "Archive" Pattern)

3.3 大型代码库索引(“归档”模式)

When the codebase exceeds 50,000 lines, context packing becomes too large. We implement Context Indexing.
typescript
// scripts/generate-index.ts
import { glob } from "bun";

/**
 * Generates a lightweight index of all functions and classes.
 * This file is what the agent reads first to "know where to look".
 */
async function generateIndex() {
  const files = glob.scan("src/**/*.ts");
  const index = [];

  for await (const file of files) {
    const content = await Bun.file(file).text();
    const matches = content.matchAll(/(export (class|function|interface) (\w+))/g);
    for (const match of matches) {
      index.push({ symbol: match[3], type: match[2], path: file });
    }
  }

  await Bun.write("CODEBASE_INDEX.json", JSON.stringify(index, null, 2));
}
当代码库超过50000行时,上下文打包会变得过大。我们实现上下文索引
typescript
// scripts/generate-index.ts
import { glob } from "bun";

/**
 * Generates a lightweight index of all functions and classes.
 * This file is what the agent reads first to "know where to look".
 */
async function generateIndex() {
  const files = glob.scan("src/**/*.ts");
  const index = [];

  for await (const file of files) {
    const content = await Bun.file(file).text();
    const matches = content.matchAll(/(export (class|function|interface) (\w+))/g);
    for (const match of matches) {
      index.push({ symbol: match[3], type: match[2], path: file });
    }
  }

  await Bun.write("CODEBASE_INDEX.json", JSON.stringify(index, null, 2));
}

4. Resilience & Implementation Patterns

4. 弹性与实现模式

4.1 Exponential Backoff & Circuit Breaker

4.1 指数退避与断路器

Preventing "Retry Cascades" is critical in distributed systems.
typescript
import { CircuitBreaker } from 'opossum';

/**
 * Standard API Fetcher with integrated Resilience.
 */
const apiCall = async (endpoint: string) => {
  const response = await fetch(endpoint, {
    signal: AbortSignal.timeout(5000) // Hard 5s timeout
  });
  
  if (!response.ok) {
    if (response.status === 429) throw new Error('RATE_LIMITED');
    throw new Error(`API_ERROR_${response.status}`);
  }
  return response.json();
};

const breaker = new CircuitBreaker(apiCall, {
  timeout: 6000,
  errorThresholdPercentage: 50, // Open circuit if 50% calls fail
  resetTimeout: 30000, // Wait 30s before trying again
  capacity: 10 // Max 10 concurrent requests
});

breaker.on('open', () => console.error('!!! CIRCUIT BREAKER OPEN - FAILING FAST !!!'));
breaker.fallback(() => ({ status: 'unavailable', cached: true, data: [] }));

async function fetchWithResilience(url: string) {
  try {
    return await breaker.fire(url);
  } catch (err) {
    console.log("Handled Error via Circuit Breaker Fallback");
    return breaker.fallback();
  }
}
防止“重试级联”在分布式系统中至关重要。
typescript
import { CircuitBreaker } from 'opossum';

/**
 * Standard API Fetcher with integrated Resilience.
 */
const apiCall = async (endpoint: string) => {
  const response = await fetch(endpoint, {
    signal: AbortSignal.timeout(5000) // Hard 5s timeout
  });
  
  if (!response.ok) {
    if (response.status === 429) throw new Error('RATE_LIMITED');
    throw new Error(`API_ERROR_${response.status}`);
  }
  return response.json();
};

const breaker = new CircuitBreaker(apiCall, {
  timeout: 6000,
  errorThresholdPercentage: 50, // Open circuit if 50% calls fail
  resetTimeout: 30000, // Wait 30s before trying again
  capacity: 10 // Max 10 concurrent requests
});

breaker.on('open', () => console.error('!!! CIRCUIT BREAKER OPEN - FAILING FAST !!!'));
breaker.fallback(() => ({ status: 'unavailable', cached: true, data: [] }));

async function fetchWithResilience(url: string) {
  try {
    return await breaker.fire(url);
  } catch (err) {
    console.log("Handled Error via Circuit Breaker Fallback");
    return breaker.fallback();
  }
}

4.2 Webhook Signature Verification (Edge Ready)

4.2 Webhook签名验证(边缘就绪)

Verification must be fast and secure. We use
crypto.subtle
for Web-native performance.
typescript
/**
 * Verifies a webhook signature using Web Crypto API.
 * Optimized for Vercel Edge / Cloudflare Workers.
 */
async function verifySignature(payload: string, signature: string, secret: string) {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify']
  );

  const verified = await crypto.subtle.verify(
    'HMAC',
    key,
    hexToBytes(signature),
    encoder.encode(payload)
  );

  return verified;
}

function hexToBytes(hex: string) {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
  }
  return bytes;
}
验证必须快速且安全。我们使用
crypto.subtle
实现Web原生性能。
typescript
/**
 * Verifies a webhook signature using Web Crypto API.
 * Optimized for Vercel Edge / Cloudflare Workers.
 */
async function verifySignature(payload: string, signature: string, secret: string) {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify']
  );

  const verified = await crypto.subtle.verify(
    'HMAC',
    key,
    hexToBytes(signature),
    encoder.encode(payload)
  );

  return verified;
}

function hexToBytes(hex: string) {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
  }
  return bytes;
}

4.3 Bulkheading & Load Shedding

4.3 舱壁模式与负载削减

Bulkheading isolates different parts of the system so a failure in one doesn't bring down others.
typescript
// Use separate client instances for different API services
const billingClient = new APIClient({ timeout: 2000, maxConnections: 5 });
const searchClient = new APIClient({ timeout: 10000, maxConnections: 20 });

// If searchClient hangs, billingClient remains responsive.
舱壁模式隔离系统的不同部分,避免一个部分的故障影响其他部分。
typescript
// Use separate client instances for different API services
const billingClient = new APIClient({ timeout: 2000, maxConnections: 5 });
const searchClient = new APIClient({ timeout: 10000, maxConnections: 20 });

// If searchClient hangs, billingClient remains responsive.

5. Large Codebase Search & Fast Navigation

5. 大型代码库搜索与快速导航

When working with massive repositories, standard
grep
is insufficient.
处理大型仓库时,标准
grep
不够用。

5.1 Git Grep (The Speed King)

5.1 Git Grep(速度之王)

Leverage the git index for searches that are 10x faster than standard grep.
bash
undefined
利用Git索引进行搜索,速度比标准grep快10倍。
bash
undefined

Find all occurrences of AUTH_SECRET in the src directory

Find all occurrences of AUTH_SECRET in the src directory

git grep "AUTH_SECRET" -- src/
git grep "AUTH_SECRET" -- src/

Find where a specific function is used across the whole repo

Find where a specific function is used across the whole repo

git grep -w "calculateTotal"
undefined
git grep -w "calculateTotal"
undefined

5.2 Advanced Grep with Pattern Files

5.2 使用模式文件的高级Grep

Use a file containing hundreds of patterns to scan for specific vulnerabilities or deprecated APIs.
bash
undefined
使用包含数百个模式的文件扫描特定漏洞或已弃用的API。
bash
undefined

patterns.txt

patterns.txt

dangerouslySetInnerHTML process.env.SECRET eval(
dangerouslySetInnerHTML process.env.SECRET eval(

Run search

Run search

grep -f patterns.txt -r ./src
undefined
grep -f patterns.txt -r ./src
undefined

6. Multi-Model Orchestration (Advanced Agentic Patterns)

6. 多模型编排(高级Agent模式)

In 2026, we rarely use a single model. We orchestrate.
typescript
/**
 * Orchestrator: Uses GPT-5 for Planning and o3 for execution.
 */
class AgentOrchestrator {
  async runMission(task: string) {
    // 1. Plan with GPT-5 (Reasoning)
    const plan = await gpt5.generatePlan(task);
    
    // 2. Execute Research steps with o3
    for (const step of plan.researchSteps) {
      const data = await o3.deepResearch(step.query);
      this.updateKnowledge(data);
    }
    
    // 3. Final synthesis with GPT-5
    return gpt5.synthesize(this.knowledgeBase);
  }
}
2026年,我们很少使用单一模型,而是进行编排。
typescript
/**
 * Orchestrator: Uses GPT-5 for Planning and o3 for execution.
 */
class AgentOrchestrator {
  async runMission(task: string) {
    // 1. Plan with GPT-5 (Reasoning)
    const plan = await gpt5.generatePlan(task);
    
    // 2. Execute Research steps with o3
    for (const step of plan.researchSteps) {
      const data = await o3.deepResearch(step.query);
      this.updateKnowledge(data);
    }
    
    // 3. Final synthesis with GPT-5
    return gpt5.synthesize(this.knowledgeBase);
  }
}

7. The "Do Not" List (Common Anti-Patterns)

7. “禁止”列表(常见反模式)

  1. DO NOT store API keys in the code. Use
    AUTH_
    prefixed environment variables for Auth.js.
  2. DO NOT use
    any
    for API responses. Use
    zod
    to validate and type all incoming data. This is the #1 cause of runtime crashes in 2026.
  3. DO NOT perform heavy processing in Webhook handlers. Acknowledge the receipt (200 OK) and queue the work (e.g., using Inngest or BullMQ).
  4. DO NOT use standard Node.js
    http
    modules in Edge functions. Use the
    fetch
    API exclusively.
  5. DO NOT assume API availability. Always implement timeouts and circuit breakers.
  6. DO NOT expose internal database IDs (e.g.,
    user_id: 123
    ). Use UUIDs or ULIDs for public-facing API resources to prevent enumeration attacks.
  7. DO NOT ignore rate limit headers (
    X-RateLimit-Remaining
    ). Implement client-side throttling to stay within limits and avoid 429 penalties.
  8. DO NOT use synchronous libraries (like
    fs.readFileSync
    ) in API routes. Always use async equivalents.
  9. DO NOT commit the
    codebase-context.md
    generated by Repomix to git. Add it to
    .gitignore
    .
  10. DO NOT hardcode API versions in strings. Use a central configuration object.
  1. 禁止在代码中存储API密钥。对于Auth.js,使用
    AUTH_
    前缀的环境变量。
  2. 禁止对API响应使用
    any
    类型。使用
    zod
    验证并为所有传入数据添加类型。这是2026年运行时崩溃的首要原因。
  3. 禁止在Webhook处理程序中执行重型处理。确认接收(返回200 OK)并将工作排入队列(例如使用Inngest或BullMQ)。
  4. 禁止在Edge函数中使用标准Node.js
    http
    模块。仅使用
    fetch
    API。
  5. 禁止假设API始终可用。始终实现超时和断路器。
  6. 禁止暴露内部数据库ID(例如
    user_id: 123
    )。对面向公众的API资源使用UUID或ULID,防止枚举攻击。
  7. 禁止忽略速率限制头(
    X-RateLimit-Remaining
    )。实现客户端节流以保持在限制内,避免429错误。
  8. 禁止在API路由中使用同步库(如
    fs.readFileSync
    )。始终使用异步等效方法。
  9. 禁止将Repomix生成的
    codebase-context.md
    提交到git。将其添加到
    .gitignore
  10. 禁止在字符串中硬编码API版本。使用中央配置对象。

8. Reference Directory Map

8. 参考目录映射

FileDescription
references/auth-next.md
Deep dive into Auth.js v5 and Edge integration.
references/ai-agents.md
GPT-5 family and o3-deep-research agentic patterns.
references/stripe-v13.md
Stripe SDK v13+ features (auto-pagination, etc.).
references/architect-archive.md
Repomix context packing and large codebase indexing.
references/resilience.md
Advanced retry strategies and circuit breakers.
references/nextjs-integration.md
Patterns for Next.js 16 Server Components & Actions.
文件描述
references/auth-next.md
Auth.js v5和边缘集成深度解析。
references/ai-agents.md
GPT-5系列和o3-deep-research Agent模式。
references/stripe-v13.md
Stripe SDK v13+特性(自动分页等)。
references/architect-archive.md
Repomix上下文打包与大型代码库索引。
references/resilience.md
高级重试策略与断路器。
references/nextjs-integration.md
Next.js 16 Server Components & Actions模式。

9. Troubleshooting Guide

9. 故障排除指南

9.1 Authentication Failures

9.1 身份验证失败

  • Symptom: "Invalid CSRF Token" in Auth.js.
  • Fix: Ensure
    AUTH_URL
    matches the request origin exactly. In Vercel, use
    AUTH_URL=${VERCEL_URL}
    .
  • Check: Verify
    AUTH_SECRET
    is at least 32 characters long.
  • 症状:Auth.js中出现“Invalid CSRF Token”。
  • 修复:确保
    AUTH_URL
    与请求源完全匹配。在Vercel中,使用
    AUTH_URL=${VERCEL_URL}
  • 检查:验证
    AUTH_SECRET
    至少32个字符长。

9.2 AI Hallucinations in API Calls

9.2 API调用中的AI幻觉

  • Symptom: GPT-5 generating invalid API parameters.
  • Fix: Provide the agent with the specific
    zod
    schema or the Stripe SDK TypeScript definitions in the context.
  • Technique: Use "Few-Shot" examples in the system prompt.
  • 症状:GPT-5生成无效的API参数。
  • 修复:在上下文中为Agent提供特定的
    zod
    schema或Stripe SDK TypeScript定义。
  • 技巧:在系统提示中使用“Few-Shot”示例。

9.3 Rate Limit Cascades

9.3 速率限制级联

  • Symptom: One service failing causes all upstream services to crash.
  • Fix: Implement the Circuit Breaker pattern (see Section 4.1) to fail fast and provide cached fallbacks.
  • 症状:一个服务故障导致所有上游服务崩溃。
  • 修复:实现断路器模式(见4.1节)以快速失败并提供缓存回退方案。

10. API Client Boilerplate (2026 Edition)

10. API客户端模板(2026版)

typescript
import { z } from 'zod';

const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email(),
  tier: z.enum(['free', 'pro', 'enterprise']),
});

type User = z.infer<typeof UserSchema>;

/**
 * Standard API Client with Validation and Logging.
 */
export class SecureAPIClient {
  private baseURL: string;
  private apiKey: string;

  constructor() {
    this.baseURL = process.env.API_BASE_URL!;
    this.apiKey = process.env.API_SECRET_KEY!;
    
    if (!this.apiKey) throw new Error("CRITICAL: API_SECRET_KEY is missing");
  }

  private async request<T>(endpoint: string, schema: z.ZodSchema<T>, options: RequestInit = {}): Promise<T> {
    const startTime = Date.now();
    
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'X-Client-Version': '2026.1.0',
        ...options.headers,
      },
    });

    const duration = Date.now() - startTime;
    console.log(`[API] ${options.method || 'GET'} ${endpoint} - ${response.status} (${duration}ms)`);

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(`API Request Failed: ${response.status} - ${JSON.stringify(errorData)}`);
    }

    const data = await response.json();
    
    // Validate at the boundary - 2026 Mandatory Rule
    const result = schema.safeParse(data);
    if (!result.success) {
      console.error("[SCHEMA_VALIDATION_ERROR]", result.error);
      throw new Error("API returned invalid data format");
    }
    
    return result.data;
  }

  async getUser(id: string): Promise<User> {
    return this.request(`/users/${id}`, UserSchema);
  }
}
typescript
import { z } from 'zod';

const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email(),
  tier: z.enum(['free', 'pro', 'enterprise']),
});

type User = z.infer<typeof UserSchema>;

/**
 * Standard API Client with Validation and Logging.
 */
export class SecureAPIClient {
  private baseURL: string;
  private apiKey: string;

  constructor() {
    this.baseURL = process.env.API_BASE_URL!;
    this.apiKey = process.env.API_SECRET_KEY!;
    
    if (!this.apiKey) throw new Error("CRITICAL: API_SECRET_KEY is missing");
  }

  private async request<T>(endpoint: string, schema: z.ZodSchema<T>, options: RequestInit = {}): Promise<T> {
    const startTime = Date.now();
    
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'X-Client-Version': '2026.1.0',
        ...options.headers,
      },
    });

    const duration = Date.now() - startTime;
    console.log(`[API] ${options.method || 'GET'} ${endpoint} - ${response.status} (${duration}ms)`);

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(`API Request Failed: ${response.status} - ${JSON.stringify(errorData)}`);
    }

    const data = await response.json();
    
    // Validate at the boundary - 2026 Mandatory Rule
    const result = schema.safeParse(data);
    if (!result.success) {
      console.error("[SCHEMA_VALIDATION_ERROR]", result.error);
      throw new Error("API returned invalid data format");
    }
    
    return result.data;
  }

  async getUser(id: string): Promise<User> {
    return this.request(`/users/${id}`, UserSchema);
  }
}

11. Production Readiness Checklist (2026)

11. 生产就绪清单(2026)

CategoryRequirementDone?
SecurityAuth.js v5 implemented with
AUTH_
prefix?
[ ]
SecurityWebhook signatures verified using
crypto.subtle
?
[ ]
ResilienceCircuit Breakers active for all 3rd party SDKs?[ ]
PerformanceAPI routes marked as
runtime: 'edge'
where possible?
[ ]
ObservabilityRequest/Response duration logged with Correlation IDs?[ ]
AI ReadinessRepomix config updated to exclude
.env
and
dist
?
[ ]
TypesZod schemas exist for every API entry/exit point?[ ]
FinancialStripe auto-pagination used for all bulk syncs?[ ]
类别要求已完成?
安全是否使用
AUTH_
前缀实现了Auth.js v5?
[ ]
安全是否使用
crypto.subtle
验证Webhook签名?
[ ]
弹性所有第三方SDK是否都启用了断路器?[ ]
性能API路由是否尽可能标记为
runtime: 'edge'
[ ]
可观测性是否记录了请求/响应持续时间和关联ID?[ ]
AI就绪Repomix配置是否已更新以排除
.env
dist
[ ]
类型每个API入口/出口点是否都有Zod schema?[ ]
金融所有批量同步是否都使用了Stripe自动分页?[ ]

12. Conclusion

12. 结论

Mastering API integration in 2026 requires a shift from manual coding to Architectural Orchestration. By leveraging Auth.js v5, GPT-5's reasoning capabilities, and the robust Stripe v13 SDK, developers can build systems that are not only faster but also more autonomous and resilient.
Always prioritize Context Packing via Repomix to ensure your AI agents have the clarity they need to assist in complex refactors and debugging sessions.

掌握2026年的API集成需要从手动编码转向架构编排。通过利用Auth.js v5、GPT-5的推理能力和强大的Stripe v13 SDK,开发人员可以构建不仅更快,而且更自主、更具弹性的系统。
始终优先通过Repomix进行上下文打包,确保你的AI Agent在复杂重构和调试会话中拥有所需的清晰上下文。

Integration with other Skills

与其他技能集成

  • next16-expert: Combine with
    auth-next.md
    for secure Server Actions.
  • db-enforcer: Use for ensuring schema alignment between API models and DB.
  • debug-master: Utilize trace-based debugging for failed API calls.
Updated: January 22, 2026 - 15:20
  • next16-expert:结合
    auth-next.md
    实现安全的Server Actions。
  • db-enforcer:用于确保API模型与数据库的schema对齐。
  • debug-master:利用基于跟踪的调试处理失败的API调用。
更新时间:2026年1月22日 15:20