Cloudflare Pages 部署 Next.js 应用教程
本教程将指导你如何将现有的 Next.js 应用部署到 Cloudflare Pages。
准备工作
-
安装部署依赖
首先,安装 @cloudflare/next-on-pages:
npm install --save-dev @cloudflare/next-on-pages -
添加
wrangler.toml配置文件在项目根目录创建
wrangler.toml文件,内容如下:name = "my-app" compatibility_date = "2024-07-29" compatibility_flags = ["nodejs_compat"] pages_build_output_dir = ".vercel/output/static" [env.production.vars] NEXTAUTH_URL = "https://your-domain.com" NEXTAUTH_SECRET = "your-secret-key" # 添加其他环境变量,记得给值加上双引号 -
更新
next.config.mjs修改
next.config.mjs文件:import { setupDevPlatform } from '@cloudflare/next-on-pages/next-dev'; /** @type {import('next').NextConfig} */ const nextConfig = {}; if (process.env.NODE_ENV === 'development') { await setupDevPlatform(); } export default nextConfig;注意:通过 Git 部署时,需要注释掉
setupDevPlatform()相关代码,也就是可以不添加这部分代码。 -
配置 Edge Runtime
为所有服务端渲染的路由(包括 API 路由)添加以下配置:
export const runtime = "edge"; -
更新
package.json在
scripts中添加:"scripts": { "pages:build": "npx @cloudflare/next-on-pages", "preview": "npm run pages:build && wrangler pages dev", "deploy": "npm run pages:build && wrangler pages deploy" }
部署步骤
-
创建 Cloudflare Pages 项目
![![[Pasted image 20240913113425.png]]](https://i-blog.csdnimg.cn/direct/1de3775ab3f54b3f9d64901033277b54.png)
-
连接 GitHub 仓库
![![[Pasted image 20240913113452.png]]](https://i-blog.csdnimg.cn/direct/672f2af61f484991bde5a74a05ac5c9d.png)
-
配置构建设置
![![[Pasted image 20240913190732.png]]](https://i-blog.csdnimg.cn/direct/9bb796b5a755481bb278901c9bfb681f.png)
- 选择 Next.js 框架预设
-
设置环境变量(可选)
部署方式
- 命令行部署:
npm run deploy - Git 集成: 推送代码到生产分支自动触发部署
常见问题及解决方案
- 编译问题:确保本地
npm run build能通过 - 启用
nodejs_compat兼容性标志
![[Pasted image 20240913115015.png]] - 环境变量问题:将配置放入
wrangler.toml
否则 util.ts 的相关读取不到配置。 - 路由配置:所有非静态路由都需设置 Edge Runtime
- 第三方 API 兼容性:某些 API 可能不兼容 Edge Runtime,需要进行适配或替换
- 必须检查所有的是否缺少,否则都会最终失败。
Please make sure that all your non-static routes export the following edge runtime route segment config:
export const runtime = 'edge';
通过以上步骤和注意事项,你应该能够成功将 Next.js 应用部署到 Cloudflare Pages。如遇到其他问题,请查阅 Cloudflare 官方文档或寻求社区帮助。



















