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 13 和 14 的所有次要版本和补丁版本,以及 Next.js 15 发布后的版本(目前为候选发布版)。
为提升兼容性,我们鼓励您报告问题 (opens in a new tab)并贡献代码!
支持的 Next.js 功能
- 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)
尚未支持的 Next.js 功能
以下 Next.js 功能目前尚未支持 —— 但我们欢迎贡献和反馈!告诉我们您希望看到哪些功能,或者您想添加对哪些功能的支持:
- Pages Router (opens in a new tab) (您应该使用 Next.js 13 引入的 App Router 替代)
- 增量静态再生 (ISR) (opens in a new tab)
- 部分预渲染 (PPR) (opens in a new tab)
- 中间件 (opens in a new tab)
- 图片优化 (opens in a new tab) (您可以按照本指南 (opens in a new tab)将 Cloudflare Images 与 Next.js 集成)
- 实验性流式支持 (opens in a new tab)
@opennextjs/cloudflare 的工作原理
OpenNext Cloudflare 适配器通过获取 Next.js 构建输出并进行转换,使其能够在 Cloudflare Workers 中运行。
当您将 @opennextjs/cloudflare (opens in a new tab) 添加为 Next.js 应用的依赖项,并运行 npx cloudflare
时,适配器首先会通过执行 next build
构建您的应用,然后将构建输出转换为可以使用 Wrangler (opens in a new tab) 本地运行并部署到 Cloudflare 的格式。
您可以查看 @opennextjs/cloudflare 的源代码 (opens in a new tab)来了解其底层实现。