Cloudflare 适配器
@opennextjs/cloudflare
(opens in a new tab) 适配器允许您使用 Next.js 的 Node.js "运行时" (opens in a new tab) 将 Next.js 应用部署到 Cloudflare Workers (opens in a new tab) 平台。
@opennextjs/cloudflare
(opens in a new tab) 目前处于 1.0 之前的版本阶段,仍在积极开发中。我们鼓励您试用该适配器,报告错误 (opens in a new tab),分享反馈 (opens in a new tab),并通过贡献代码来帮助改善在 Cloudflare 上运行 Next.js 应用的体验。目前我们暂不建议将其用于关键业务的生产环境应用。
您也可以使用 @cloudflare/next-on-pages
(opens in a new tab) 将 Next.js 应用部署到 Cloudflare Pages。您可以通过下方支持的 Next.js 功能对比表以及查阅 @cloudflare/next-on-pages
的文档 (opens in a new tab) 来了解两者的区别,并通过此链接 (opens in a new tab) 了解 Workers 和 Pages 之间的差异。
快速开始
新建应用
要创建一个预配置为使用 @opennextjs/cloudflare
在 Cloudflare 上运行的新 Next.js 应用,请运行:
npm create cloudflare@latest -- my-next-app --framework=next --experimental
现有 Next.js 应用
按照此指南 将 @opennextjs/cloudflare (opens in a new tab) 适配器应用到现有的 Next.js 应用中。
支持的 Next.js 运行时
Next.js 提供两种"运行时" (opens in a new tab) —— "Edge" 和 "Node.js"。当使用 @opennextjs/cloudflare
时,您的应用应使用 Node.js 运行时,该运行时功能更全面,并允许您使用 Cloudflare Workers 运行时提供的 Node.js API (opens in a new tab)。
这与 @cloudflare/next-on-pages
有重要区别,后者仅支持 "Edge" 运行时。Next.js 中的 Edge Runtime 代码有意限制了可使用的 Node.js API (opens in a new tab),且 "Edge" 运行时不支持所有 Next.js 功能。
支持的 Next.js 版本
@opennextjs/cloudflare
目前处于 1.0 之前的开发阶段,仍在积极开发中。我们计划支持 Next.js 15 的所有次要版本和补丁版本,以及 Next.js 14 的最新次要版本。
为帮助提高兼容性,我们鼓励您报告问题 (opens in a new tab)并贡献代码!
支持的 Next.js 功能
部分 Next.js 功能尚未完全支持或未经过完整测试。我们将在发布 1.0 版本的过程中持续更新此列表。
- App Router (opens in a new tab)
- 路由处理器 (opens in a new tab)
- 动态路由 (opens in a new tab)
- 静态站点生成 (SSG) (opens in a new tab)
- 服务端渲染 (SSR) (opens in a new tab)
- 中间件 (opens in a new tab)
- 图片优化 (opens in a new tab)(可通过本指南 (opens in a new tab)集成 Cloudflare Images)
- 部分预渲染 (PPR) (opens in a new tab)
- Pages Router (opens in a new tab)
- 增量静态再生 (ISR) (opens in a new tab) 1
- 支持 after (opens in a new tab)
- 可组合缓存 (opens in a new tab) (
'use cache'
) 是 Next.js 15 的功能,目前尚未支持
1 目前仅支持 direct
模式,不适用于生产环境。
我们欢迎贡献和反馈!
Windows 支持
OpenNext 可以在 Windows 系统上使用,但我们不保证对 Windows 的完全支持,原因如下:
- Next.js 工具链本身存在 Windows 支持问题,而 OpenNext 正是基于这些工具构建的
- OpenNext 团队资源有限,考虑到上述因素,完全支持 Windows 被确定为较低优先级,因此在 Windows 上的开发和测试投入有限
基于以上情况,您可以在 Windows 上自行承担风险进行应用开发。如果没有其他选择,我们建议您:
- 使用 Windows Subsystem for Linux (WSL) (opens in a new tab) 运行 OpenNext
- 在 Linux 虚拟机中运行
- 使用标准 Next.js 工具链开发应用,然后在 CI/CD 系统(如运行在 Linux/MacOS 环境下的 GitHub Actions (opens in a new tab))中使用 OpenNext 进行部署
Windows Subsystem for Linux (WSL) 允许您在 Windows 机器上运行 Linux 环境,而无需单独的虚拟机或双系统启动。Visual Studio Code 提供了一个扩展 (opens in a new tab),可以非常方便地在 WSL 中进行开发。
@opennextjs/cloudflare
工作原理
OpenNext Cloudflare 适配器的工作原理是通过转换 Next.js 的构建输出,使其能够在 Cloudflare Workers 中运行。
当你在 Next.js 应用中添加 @opennextjs/cloudflare (opens in a new tab) 作为依赖,并运行 npx opennextjs-cloudflare
时,适配器首先会执行 package.json
中的 build
脚本来构建你的应用,然后将构建输出转换为可以通过 Wrangler (opens in a new tab) 在本地运行并部署到 Cloudflare 的格式。
你可以查看 @opennextjs/cloudflare
的源代码 (opens in a new tab)来了解其底层实现。