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 之间的差异。
开始使用
新应用
要创建一个新的 Next.js 应用,预配置为使用 @opennextjs/cloudflare 在 Cloudflare 上运行,请运行:
npm create cloudflare@latest -- my-next-app --framework=next --experimental现有的 Next.js 应用
遵循 此处 的指南,在现有的 Next.js 应用中使用 @opennextjs/cloudflare (opens in a new tab)。
支持的 Next.js 运行时
Next.js 拥有 两种“运行时” (opens in a new tab) —— "Edge" 和 "Node.js"。当你使用 @opennextjs/cloudflare 时,你的应用可以使用 Node.js 运行时,它功能更齐全,并允许你使用 Cloudflare Workers 运行时提供的 Node.js APIs (opens in a new tab)。
这与 @cloudflare/next-on-pages 有一个重要区别,后者仅支持 "Edge" 运行时。Next.js 中的 Edge Runtime 代码 有意限制了可以使用哪些 Node.js APIs (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)(你应该使用 App Router 代替,它是在 Next.js 13 中引入的)
- 增量静态再生 (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 的格式。
你可以 此处 (opens in a new tab) 查看 @opennextjs/cloudflare 的代码,以了解其底层工作原理。