cloudflare-nextjs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Next.js Deployment Skill

Cloudflare Next.js 部署技能

Deploy Next.js applications to Cloudflare Workers using the OpenNext Cloudflare adapter for production-ready serverless Next.js hosting.
使用OpenNext Cloudflare适配器将Next.js应用部署至Cloudflare Workers,实现生产就绪的无服务器Next.js托管。

When to Load References

何时加载参考文件

Load additional reference files based on your specific task:
  • references/error-catalog-extended.md
    - Load when encountering ANY error during setup, build, or deployment. Contains complete catalog of 11+ documented issues with root causes, solutions, and official sources.
  • references/service-integration-patterns.md
    - Load when integrating Cloudflare services (D1, R2, KV, Workers AI) with Next.js. Contains complete patterns for database queries, file uploads, caching, and AI inference.
  • references/troubleshooting.md
    - Load for general troubleshooting and debugging guidance beyond the error catalog.
  • references/feature-support.md
    - Load when checking if a specific Next.js feature is supported on Cloudflare Workers (e.g., "Can I use Server Actions?", "Does ISR work?").
  • references/database-client-example.ts
    - Load when integrating external database clients (Drizzle, Prisma, PostgreSQL, MySQL) with proper request-scoping patterns required by Workers.
  • references/open-next.config.ts
    - Load when configuring caching behavior, image optimization, or custom OpenNext settings.
  • references/package.json
    - Load when setting up a new project or migrating an existing Next.js application to Cloudflare Workers.
  • references/wrangler.jsonc
    - Load when configuring Worker settings, compatibility flags, environment bindings (D1, R2, KV, AI), or deployment options.
根据具体任务加载额外的参考文件:
  • references/error-catalog-extended.md
    - 在设置、构建或部署过程中遇到任何错误时加载。包含11+个已记录问题的完整目录,涵盖根本原因、解决方案和官方来源。
  • references/service-integration-patterns.md
    - 在将Cloudflare服务(D1、R2、KV、Workers AI)与Next.js集成时加载。包含数据库查询、文件上传、缓存和AI推理的完整模式。
  • references/troubleshooting.md
    - 加载以获取错误目录之外的常规故障排除和调试指南。
  • references/feature-support.md
    - 在检查特定Next.js功能是否支持Cloudflare Workers时加载(例如:“我能否使用Server Actions?”、“ISR是否可用?”)。
  • references/database-client-example.ts
    - 在集成外部数据库客户端(Drizzle、Prisma、PostgreSQL、MySQL)时加载,需遵循Workers要求的正确请求作用域模式。
  • references/open-next.config.ts
    - 在配置缓存行为、图片优化或自定义OpenNext设置时加载。
  • references/package.json
    - 在搭建新项目或将现有Next.js应用迁移至Cloudflare Workers时加载。
  • references/wrangler.jsonc
    - 在配置Worker设置、兼容性标志、环境绑定(D1、R2、KV、AI)或部署选项时加载。

Use This Skill When

何时使用此技能

  • Deploying Next.js applications (App Router or Pages Router) to Cloudflare Workers
  • Need server-side rendering (SSR), static site generation (SSG), or incremental static regeneration (ISR) on Cloudflare
  • Migrating existing Next.js apps from Vercel, AWS, or other platforms to Cloudflare
  • Building full-stack Next.js applications with Cloudflare services (D1, R2, KV, Workers AI)
  • Need React Server Components, Server Actions, or Next.js middleware on Workers
  • Want global edge deployment with Cloudflare's network
  • 将Next.js应用(App Router或Pages Router)部署至Cloudflare Workers
  • 需要在Cloudflare上实现服务器端渲染(SSR)、静态站点生成(SSG)或增量静态再生(ISR)
  • 将现有Next.js应用从Vercel、AWS或其他平台迁移至Cloudflare
  • 构建集成Cloudflare服务(D1、R2、KV、Workers AI)的全栈Next.js应用
  • 需要在Workers上使用React Server Components、Server Actions或Next.js中间件
  • 希望借助Cloudflare网络实现全局边缘部署

Key Differences from Standard Next.js

与标准Next.js的关键差异

OpenNext Adapter transforms Next.js builds for Workers. Critical requirements:
  • Node.js runtime (NOT Edge) via
    nodejs_compat
    flag
  • Request-scoped database clients (global clients fail)
  • Worker size limits: 3 MiB (free) / 10 MiB (paid)
  • Dual testing:
    next dev
    for speed,
    preview
    for production-like validation
OpenNext适配器会将Next.js构建产物转换为适配Workers的格式。关键要求
  • 通过
    nodejs_compat
    标志启用Node.js运行时(而非Edge运行时)
  • 请求作用域的数据库客户端(全局客户端会失效)
  • Worker大小限制:免费版3 MiB / 付费版10 MiB
  • 双重测试:
    next dev
    用于快速开发,
    preview
    用于类生产环境验证

Setup Patterns

搭建模式

New Project Setup

新项目搭建

Use Cloudflare's
create-cloudflare
(C3) CLI to scaffold a new Next.js project pre-configured for Workers:
bash
npm create cloudflare@latest -- my-next-app --framework=next
What this does:
  1. Runs Next.js official setup tool (
    create-next-app
    )
  2. Installs
    @opennextjs/cloudflare
    adapter
  3. Creates
    wrangler.jsonc
    with correct configuration
  4. Creates
    open-next.config.ts
    for caching configuration
  5. Adds deployment scripts to
    package.json
  6. Optionally deploys immediately to Cloudflare
Development workflow:
bash
npm run dev      # Next.js dev server (fast reloads)
npm run preview  # Test in workerd runtime (production-like)
npm run deploy   # Build and deploy to Cloudflare
使用Cloudflare的
create-cloudflare
(C3)CLI脚手架搭建预配置为Workers的Next.js新项目:
bash
npm create cloudflare@latest -- my-next-app --framework=next
该命令的作用
  1. 运行Next.js官方搭建工具(
    create-next-app
  2. 安装
    @opennextjs/cloudflare
    适配器
  3. 创建配置正确的
    wrangler.jsonc
  4. 创建用于缓存配置的
    open-next.config.ts
  5. package.json
    添加部署脚本
  6. 可选地立即部署至Cloudflare
开发工作流
bash
npm run dev      # Next.js开发服务器(快速重载)
npm run preview  # 在workerd运行时测试(类生产环境)
npm run deploy   # 构建并部署至Cloudflare

Existing Project Migration

现有项目迁移

To add the OpenNext adapter to an existing Next.js application:
为现有Next.js应用添加OpenNext适配器:

1. Install the adapter

1. 安装适配器

bash
bun add -d @opennextjs/cloudflare
bash
bun add -d @opennextjs/cloudflare
Secure Installation
安全安装
Adapter packages handle production traffic — pin exact versions and audit before upgrading. Follow supply chain security best practices:
  • Block post-install scripts
    npm config set ignore-scripts true
    (or Bun: disabled by default)
  • Cooldown period — Wait 7 days for new package versions to be vetted by the community
  • Audit before installing — Run
    socket package score npm <pkg>
    or use
    socket npm install <pkg>
    to check packages
Load the
dependency-upgrade
skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.
适配器包处理生产流量——固定精确版本并在升级前进行审计。遵循供应链安全最佳实践:
  • 阻止安装后脚本
    npm config set ignore-scripts true
    (Bun默认禁用)
  • 冷却期 — 等待7天,让社区审核新包版本
  • 安装前审计 — 运行
    socket package score npm <pkg>
    或使用
    socket npm install <pkg>
    检查包
加载
dependency-upgrade
技能以获取完整安全配置,包括Socket CLI集成、冷却期设置、锁文件验证和CI强制执行。

2. Create wrangler.jsonc

2. 创建wrangler.jsonc

jsonc
{
  "name": "my-next-app",
  "compatibility_date": "2025-05-05",
  "compatibility_flags": ["nodejs_compat"]
}
Critical configuration:
  • compatibility_date
    : Minimum
    2025-05-05
    (for FinalizationRegistry support)
  • compatibility_flags
    : Must include
    nodejs_compat
    (for Node.js runtime)
jsonc
{
  "name": "my-next-app",
  "compatibility_date": "2025-05-05",
  "compatibility_flags": ["nodejs_compat"]
}
关键配置
  • compatibility_date
    最低为
    2025-05-05
    (支持FinalizationRegistry)
  • compatibility_flags
    必须包含
    nodejs_compat
    (启用Node.js运行时)

3. Create open-next.config.ts

3. 创建open-next.config.ts

typescript
import { defineCloudflareConfig } from "@opennextjs/cloudflare";

export default defineCloudflareConfig({
  // Caching configuration (optional)
  // See: https://opennext.js.org/cloudflare/caching
});
typescript
import { defineCloudflareConfig } from "@opennextjs/cloudflare";

export default defineCloudflareConfig({
  // 缓存配置(可选)
  // 参考:https://opennext.js.org/cloudflare/caching
});

4. Update package.json scripts

4. 更新package.json脚本

json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
    "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
    "cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
  }
}
Script purposes:
  • dev
    : Next.js development server (fast iteration)
  • preview
    : Build + run in workerd runtime (test before deploy)
  • deploy
    : Build + deploy to Cloudflare
  • cf-typegen
    : Generate TypeScript types for Cloudflare bindings
json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
    "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
    "cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
  }
}
脚本用途
  • dev
    :Next.js开发服务器(快速迭代)
  • preview
    :构建并在workerd运行时运行(部署前测试)
  • deploy
    :构建并部署至Cloudflare
  • cf-typegen
    :为Cloudflare绑定生成TypeScript类型

5. Ensure Node.js runtime (not Edge)

5. 确保使用Node.js运行时(而非Edge)

Remove Edge runtime exports from your app:
typescript
// ❌ REMOVE THIS (Edge runtime not supported)
export const runtime = "edge";

// ✅ Use Node.js runtime (default)
// No export needed - Node.js is default
移除应用中的Edge运行时导出:
typescript
// ❌ 删除此代码(不支持Edge运行时)
export const runtime = "edge";

// ✅ 使用Node.js运行时(默认)
// 无需导出——Node.js是默认选项

Development Workflow

开发工作流

Dual Testing Required:
  • npm run dev
    - Fast iteration (Next.js dev server)
  • npm run preview
    - Production-like testing (workerd runtime, REQUIRED before deploy)
  • npm run deploy
    - Build and deploy
Critical: Always test
preview
before deploying to catch Workers-specific runtime issues
必须进行双重测试
  • npm run dev
    - 快速迭代(Next.js开发服务器)
  • npm run preview
    - 类生产环境测试(workerd运行时,部署前必须执行
  • npm run deploy
    - 构建并部署
关键提示:部署前务必测试
preview
,以排查Workers特有的运行时问题

Critical Configuration

关键配置

wrangler.jsonc minimum requirements:
jsonc
{
  "compatibility_date": "2025-05-05",  // Minimum for FinalizationRegistry
  "compatibility_flags": ["nodejs_compat"]  // Required for Node.js runtime
}
Cloudflare Bindings: Add D1, R2, KV, or AI bindings in
wrangler.jsonc
, access via
process.env
(see "Cloudflare Services Integration" section for complete patterns)
Package Exports (if needed): Create
.env
with
WRANGLER_BUILD_PLATFORM="node"
to prioritize Node.js exports
wrangler.jsonc最低要求:
jsonc
{
  "compatibility_date": "2025-05-05",  // 支持FinalizationRegistry的最低版本
  "compatibility_flags": ["nodejs_compat"]  // 启用Node.js运行时必需
}
Cloudflare绑定:在
wrangler.jsonc
中添加D1、R2、KV或AI绑定,通过
process.env
访问(完整模式请查看“Cloudflare服务集成”章节)
包导出(如有需要):创建
.env
文件并设置
WRANGLER_BUILD_PLATFORM="node"
,优先使用Node.js导出

Top 5 Critical Errors

五大关键错误

These are the most common deployment-blocking errors. For the complete catalog of 11+ errors, load
references/error-catalog-extended.md
.
这些是最常见的部署阻塞错误。如需获取11+个错误的完整目录,请加载
references/error-catalog-extended.md

1. Worker Size Limit Exceeded

1. Worker大小限制超出

Error:
"Your Worker exceeded the size limit of 3 MiB"
(Free) or
"10 MiB"
(Paid)
Quick Fix: Upgrade plan, analyze bundle with
bunx opennextjs-cloudflare build
→ check
.open-next/server-functions/default/handler.mjs.meta.json
, remove unused dependencies, or use dynamic imports.

错误信息
"Your Worker exceeded the size limit of 3 MiB"
(免费版)或
"10 MiB"
(付费版)
快速修复:升级套餐,使用
bunx opennextjs-cloudflare build
分析包大小→查看
.open-next/server-functions/default/handler.mjs.meta.json
,移除未使用的依赖,或使用动态导入。

2. Cannot Perform I/O on Behalf of Different Request

2. 无法代表其他请求执行I/O操作

Error:
"Cannot perform I/O on behalf of a different request"
Cause: Global database client reused across requests (Workers limitation)
Quick Fix: Create database clients INSIDE request handlers, never globally. Or use Cloudflare D1 which is designed for Workers.
typescript
// ❌ WRONG: Global client
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

// ✅ CORRECT: Request-scoped
export async function GET() {
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  // ... use pool
  await pool.end();
}

错误信息
"Cannot perform I/O on behalf of a different request"
原因:全局数据库客户端跨请求复用(Workers限制)
快速修复:在请求处理程序内部创建数据库客户端,切勿全局创建。或使用为Workers设计的Cloudflare D1。
typescript
// ❌ 错误:全局客户端
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

// ✅ 正确:请求作用域
export async function GET() {
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  // ... 使用pool
  await pool.end();
}

3. NPM Package Import Failures

3. NPM包导入失败

Error:
"Could not resolve '<package>'"
Quick Fix: Enable
nodejs_compat
flag in wrangler.jsonc, and/or create
.env
with
WRANGLER_BUILD_PLATFORM="node"
.

错误信息
"Could not resolve '<package>'"
快速修复:在wrangler.jsonc中启用
nodejs_compat
标志,和/或创建
.env
文件并设置
WRANGLER_BUILD_PLATFORM="node"

4. SSRF Vulnerability (CVE-2025-6087)

4. SSRF漏洞(CVE-2025-6087)

Vulnerability: Server-Side Request Forgery via
/_next/image
endpoint in versions < 1.3.0
Quick Fix: Upgrade immediately:
bun add -d @opennextjs/cloudflare@^1.3.0

漏洞描述:版本<1.3.0中通过
/_next/image
端点存在服务器端请求伪造(SSRF)
快速修复:立即升级:
bun add -d @opennextjs/cloudflare@^1.3.0

5. Failed to Load Chunk (Turbopack)

5. 加载Chunk失败(Turbopack)

Error:
"Failed to load chunk server/chunks/ssr/"
Quick Fix: Remove
--turbo
flag from build command. Use
next build
(standard), NOT
next build --turbo
.

More Errors: Load
references/error-catalog-extended.md
for 6 additional documented errors including FinalizationRegistry issues, Durable Objects warnings, Prisma conflicts, cross-fetch errors, and Windows development issues
错误信息
"Failed to load chunk server/chunks/ssr/"
快速修复:从构建命令中移除
--turbo
标志。使用
next build
(标准构建),而非
next build --turbo

更多错误:加载
references/error-catalog-extended.md
获取另外6个已记录错误,包括FinalizationRegistry问题、Durable Objects警告、Prisma冲突、cross-fetch错误和Windows开发问题

Feature Support Matrix

功能支持矩阵

FeatureStatusNotes
App Router✅ Fully SupportedLatest App Router features work
Pages Router✅ Fully SupportedLegacy Pages Router supported
Route Handlers✅ Fully SupportedAPI routes work as expected
React Server Components✅ Fully SupportedRSC fully functional
Server Actions✅ Fully SupportedServer Actions work
SSG✅ Fully SupportedStatic Site Generation
SSR✅ Fully SupportedServer-Side Rendering
ISR✅ Fully SupportedIncremental Static Regeneration
Middleware✅ SupportedExcept Node.js middleware (15.2+)
Image Optimization✅ SupportedVia Cloudflare Images
Partial Prerendering (PPR)✅ SupportedExperimental in Next.js
Composable Caching✅ Supported
'use cache'
directive
Response Streaming✅ SupportedStreaming responses work
next/after
API
✅ SupportedPost-response async work
Node.js Middleware (15.2+)❌ Not SupportedFuture support planned
Edge Runtime❌ Not SupportedUse Node.js runtime
功能状态说明
App Router✅ 完全支持最新App Router功能可用
Pages Router✅ 完全支持支持旧版Pages Router
Route Handlers✅ 完全支持API路由正常工作
React Server Components✅ 完全支持RSC功能完整
Server Actions✅ 完全支持Server Actions可用
SSG✅ 完全支持静态站点生成
SSR✅ 完全支持服务器端渲染
ISR✅ 完全支持增量静态再生
Middleware✅ 支持不支持Node.js中间件(15.2+)
Image Optimization✅ 支持通过Cloudflare Images实现
Partial Prerendering (PPR)✅ 支持Next.js中的实验性功能
Composable Caching✅ 支持
'use cache'
指令
Response Streaming✅ 支持流式响应可用
next/after
API
✅ 支持响应后异步操作
Node.js Middleware (15.2+)❌ 不支持计划未来支持
Edge Runtime❌ 不支持使用Node.js运行时

Cloudflare Services Integration

Cloudflare服务集成

Access Cloudflare bindings via
process.env
in Next.js route handlers:
typescript
import type { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const env = process.env as any;

  // D1 Database
  const users = await env.DB.prepare('SELECT * FROM users').all();

  // R2 Storage
  const file = await env.BUCKET.get('file.txt');

  // KV Storage
  const value = await env.KV.get('key');

  // Workers AI
  const ai = await env.AI.run('@cf/meta/llama-3-8b-instruct', { prompt: 'Hello' });

  return Response.json({ users, file, value, ai });
}
Wrangler Bindings Configuration:
jsonc
{
  "d1_databases": [{ "binding": "DB", "database_id": "..." }],
  "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "..." }],
  "kv_namespaces": [{ "binding": "KV", "id": "..." }],
  "ai": { "binding": "AI" }
}
Detailed Integration Patterns: Load
references/service-integration-patterns.md
for complete patterns including:
  • D1: Queries, inserts, transactions, batch operations
  • R2: Upload, download, list, delete with streaming
  • KV: Get, set with TTL, delete, list keys
  • Workers AI: Text generation, embeddings, image classification
  • Multi-service integration examples
  • TypeScript types for bindings (
    npm run cf-typegen
    )
Related Skills:
cloudflare-d1
,
cloudflare-r2
,
cloudflare-kv
,
cloudflare-workers-ai
for service-specific deep dives
在Next.js路由处理程序中通过
process.env
访问Cloudflare绑定:
typescript
import type { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const env = process.env as any;

  // D1数据库
  const users = await env.DB.prepare('SELECT * FROM users').all();

  // R2存储
  const file = await env.BUCKET.get('file.txt');

  // KV存储
  const value = await env.KV.get('key');

  // Workers AI
  const ai = await env.AI.run('@cf/meta/llama-3-8b-instruct', { prompt: 'Hello' });

  return Response.json({ users, file, value, ai });
}
Wrangler绑定配置
jsonc
{
  "d1_databases": [{ "binding": "DB", "database_id": "..." }],
  "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "..." }],
  "kv_namespaces": [{ "binding": "KV", "id": "..." }],
  "ai": { "binding": "AI" }
}
详细集成模式:加载
references/service-integration-patterns.md
获取完整模式,包括:
  • D1:查询、插入、事务、批量操作
  • R2:上传、下载、列表、删除及流式处理
  • KV:获取、设置TTL、删除、列出密钥
  • Workers AI:文本生成、嵌入、图像分类
  • 多服务集成示例
  • 绑定的TypeScript类型(
    npm run cf-typegen
相关技能
cloudflare-d1
cloudflare-r2
cloudflare-kv
cloudflare-workers-ai
用于服务深度集成

Image Optimization & Caching

图片优化与缓存

Images: Automatic optimization via Cloudflare Images (billed separately). Configure in
open-next.config.ts
with
imageOptimization: { loader: 'cloudflare' }
. Use standard Next.js
<Image />
component.
Caching: OpenNext provides sensible defaults. Override in
open-next.config.ts
if needed. See https://opennext.js.org/cloudflare/caching for advanced configuration
图片:通过Cloudflare Images自动优化(单独计费)。在
open-next.config.ts
中配置
imageOptimization: { loader: 'cloudflare' }
。使用标准Next.js
<Image />
组件。
缓存:OpenNext提供合理的默认值。如有需要可在
open-next.config.ts
中覆盖。高级配置请查看https://opennext.js.org/cloudflare/caching

Known Limitations

已知限制

Not Yet Supported

暂不支持

  1. Node.js Middleware (Next.js 15.2+)
    • Introduced in Next.js 15.2
    • Support planned for future releases
    • Use standard middleware for now
  2. Edge Runtime
    • Only Node.js runtime supported
    • Remove
      export const runtime = "edge"
      from your app
  3. Full Windows Support
    • Development on Windows not fully guaranteed
    • Use WSL, VM, or Linux-based CI/CD
  1. Node.js中间件(Next.js 15.2+)
    • 在Next.js 15.2中引入
    • 计划未来版本支持
    • 目前使用标准中间件
  2. Edge运行时
    • 仅支持Node.js运行时
    • 从应用中移除
      export const runtime = "edge"
  3. 完整Windows支持
    • Windows开发环境未完全兼容
    • 使用WSL、虚拟机或基于Linux的CI/CD

Worker Size Constraints

Worker大小限制

  • Free plan: 3 MiB limit (gzip-compressed)
  • Paid plan: 10 MiB limit (gzip-compressed)
  • Monitor bundle size during development
  • Use dynamic imports for code splitting
  • 免费套餐:3 MiB限制(gzip压缩后)
  • 付费套餐:10 MiB限制(gzip压缩后)
  • 开发过程中监控包大小
  • 使用动态导入进行代码拆分

Database Connections

数据库连接

  • External database clients (PostgreSQL, MySQL) must be request-scoped
  • Cannot reuse connections across requests (Workers limitation)
  • Prefer Cloudflare D1 for database needs (designed for Workers)
  • 外部数据库客户端(PostgreSQL、MySQL)必须是请求作用域
  • 无法跨请求复用连接(Workers限制)
  • 优先使用为Workers设计的Cloudflare D1

Deployment

部署

Local:
npm run deploy
(builds and deploys)
CI/CD: Use
npm run deploy
command in GitHub Actions, GitLab CI, or Cloudflare Workers Builds (auto-detected)
Custom Domains: Workers & Pages → Settings → Domains & Routes (domain must be on Cloudflare)
本地部署
npm run deploy
(构建并部署)
CI/CD:在GitHub Actions、GitLab CI或Cloudflare Workers Builds(自动检测)中使用
npm run deploy
命令
自定义域名:Workers & Pages → 设置 → 域名与路由(域名必须托管在Cloudflare)

TypeScript & Testing

TypeScript与测试

TypeScript Types: Run
npm run cf-typegen
to generate
cloudflare-env.d.ts
with typed bindings (D1Database, R2Bucket, KVNamespace, Ai)
Testing: Always test in
preview
mode before deployment to catch Workers-specific runtime issues and verify bindings work correctly
TypeScript类型:运行
npm run cf-typegen
生成
cloudflare-env.d.ts
,包含绑定的类型(D1Database、R2Bucket、KVNamespace、Ai)
测试:部署前务必在
preview
模式下测试,以排查Workers特有的运行时问题并验证绑定是否正常工作

Migration from Other Platforms

从其他平台迁移

From Vercel

从Vercel迁移

  1. Copy existing Next.js project
  2. Run existing project migration steps (above)
  3. Update environment variables in Cloudflare dashboard
  4. Replace Vercel-specific features:
    • Vercel Postgres → Cloudflare D1
    • Vercel Blob → Cloudflare R2
    • Vercel KV → Cloudflare KV
    • Vercel Edge Config → Cloudflare KV
  5. Test thoroughly with
    npm run preview
  6. Deploy with
    npm run deploy
  1. 复制现有Next.js项目
  2. 执行上述现有项目迁移步骤
  3. 在Cloudflare控制台更新环境变量
  4. 替换Vercel特有功能:
    • Vercel Postgres → Cloudflare D1
    • Vercel Blob → Cloudflare R2
    • Vercel KV → Cloudflare KV
    • Vercel Edge Config → Cloudflare KV
  5. 使用
    npm run preview
    全面测试
  6. 使用
    npm run deploy
    部署

From AWS / Other Platforms

从AWS / 其他平台迁移

Same process as Vercel migration - the adapter handles Next.js standard features automatically.
与Vercel迁移流程相同——适配器会自动处理Next.js标准功能。

Resources

资源

Official Documentation

官方文档

Troubleshooting

故障排除

Related Skills

相关技能

  • cloudflare-worker-base
    - Base Worker setup with Hono + Vite + React
  • cloudflare-d1
    - D1 database integration
  • cloudflare-r2
    - R2 object storage
  • cloudflare-kv
    - KV key-value storage
  • cloudflare-workers-ai
    - Workers AI integration
  • cloudflare-vectorize
    - Vector database for RAG
  • cloudflare-worker-base
    - 基于Hono + Vite + React的基础Worker搭建
  • cloudflare-d1
    - D1数据库集成
  • cloudflare-r2
    - R2对象存储
  • cloudflare-kv
    - KV键值存储
  • cloudflare-workers-ai
    - Workers AI集成
  • cloudflare-vectorize
    - 用于RAG的向量数据库

Quick Reference

快速参考

Essential Commands

核心命令

bash
undefined
bash
undefined

New project

新项目

npm create cloudflare@latest -- my-next-app --framework=next
npm create cloudflare@latest -- my-next-app --framework=next

Development

开发

npm run dev # Fast iteration (Next.js dev server) npm run preview # Test in workerd (production-like)
npm run dev # 快速迭代(Next.js开发服务器) npm run preview # 在workerd中测试(类生产环境)

Deployment

部署

npm run deploy # Build and deploy to Cloudflare
npm run deploy # 构建并部署至Cloudflare

TypeScript

TypeScript

npm run cf-typegen # Generate binding types
undefined
npm run cf-typegen # 生成绑定类型
undefined

Critical Configuration

关键配置

jsonc
// wrangler.jsonc
{
  "compatibility_date": "2025-05-05",  // Minimum!
  "compatibility_flags": ["nodejs_compat"]  // Required!
}
jsonc
// wrangler.jsonc
{
  "compatibility_date": "2025-05-05",  // 最低要求!
  "compatibility_flags": ["nodejs_compat"]  // 必需!
}

Common Pitfalls

常见陷阱

  1. ❌ Using Edge runtime → ✅ Use Node.js runtime
  2. ❌ Global DB clients → ✅ Request-scoped clients
  3. ❌ Old compatibility_date → ✅ Use 2025-05-05+
  4. ❌ Missing nodejs_compat → ✅ Add to compatibility_flags
  5. ❌ Only testing in
    dev
    → ✅ Always test
    preview
    before deploy
  6. ❌ Using Turbopack → ✅ Use standard Next.js build

Production Tested: Official Cloudflare support and active community Token Savings: ~59% vs manual setup Errors Prevented: 11+ documented issues Last Verified: 2025-12-04
  1. ❌ 使用Edge运行时 → ✅ 使用Node.js运行时
  2. ❌ 全局数据库客户端 → ✅ 请求作用域客户端
  3. ❌ 旧版compatibility_date → ✅ 使用2025-05-05+
  4. ❌ 缺少nodejs_compat → ✅ 添加至compatibility_flags
  5. ❌ 仅在
    dev
    中测试 → ✅ 部署前务必测试
    preview
  6. ❌ 使用Turbopack → ✅ 使用标准Next.js构建

生产验证:Cloudflare官方支持,社区活跃 节省成本:相比手动设置节省约59% 避免错误:11+个已记录问题 最后验证:2025-12-04