Cloudflare Pages 部署 Next.js 应用教程

Cloudflare Pages 部署 Next.js 应用教程

本教程将指导你如何将现有的 Next.js 应用部署到 Cloudflare Pages。

准备工作

  1. 安装部署依赖

    首先,安装 @cloudflare/next-on-pages:

    bash 复制代码
    npm install --save-dev @cloudflare/next-on-pages
  2. 添加 wrangler.toml 配置文件

    在项目根目录创建 wrangler.toml 文件,内容如下:

    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"
    # 添加其他环境变量,记得给值加上双引号
  3. 更新 next.config.mjs

    修改 next.config.mjs 文件:

    javascript 复制代码
    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() 相关代码,也就是可以不添加这部分代码。

  4. 配置 Edge Runtime

    为所有服务端渲染的路由(包括 API 路由)添加以下配置:

    javascript 复制代码
    export const runtime = "edge";
  5. 更新 package.json

    scripts 中添加:

    json 复制代码
    "scripts": {
      "pages:build": "npx @cloudflare/next-on-pages",
      "preview": "npm run pages:build && wrangler pages dev",
      "deploy": "npm run pages:build && wrangler pages deploy"
    }

部署步骤

  1. 创建 Cloudflare Pages 项目

  2. 连接 GitHub 仓库

  3. 配置构建设置

    • 选择 Next.js 框架预设
  4. 设置环境变量(可选)

部署方式

  • 命令行部署: npm run deploy
  • Git 集成: 推送代码到生产分支自动触发部署

常见问题及解决方案

  1. 编译问题:确保本地 npm run build 能通过

  2. 启用 nodejs_compat 兼容性标志
    ![[Pasted image 20240913115015.png]]

  3. 环境变量问题:将配置放入 wrangler.toml
    否则 util.ts 的相关读取不到配置。

  4. 路由配置:所有非静态路由都需设置 Edge Runtime

  5. 第三方 API 兼容性:某些 API 可能不兼容 Edge Runtime,需要进行适配或替换

  6. 必须检查所有的是否缺少,否则都会最终失败。

    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 官方文档或寻求社区帮助。

相关推荐
初见无风5 小时前
3.0 Lua代码中的闭包
开发语言·lua·lua5.4
Eiceblue5 小时前
使用 Python 向 PDF 添加附件与附件注释
linux·开发语言·vscode·python·pdf
loong_XL6 小时前
AC自动机算法-字符串搜索算法:敏感词检测
开发语言·算法·c#
QmDeve6 小时前
Android 使用液态玻璃(LiquidGlass)效果,真实的折射和色散效果
android·github
xrkhy6 小时前
Java全栈面试题及答案汇总(2)
java·开发语言
@LetsTGBot搜索引擎机器人7 小时前
从零打造 Telegram 中文生态:界面汉化 + 中文Bot + @letstgbot 搜索引擎整合实战
开发语言·python·搜索引擎·github·全文检索
洲覆7 小时前
缓存异常:缓存穿透、缓存击穿、缓存雪崩
开发语言·数据库·mysql·缓存
AmazingKO7 小时前
推送报错403怎么办?vscode推送项目到github
chatgpt·github·visual studio code·竹相左边
油泼辣子多加7 小时前
2025年10月31日Github流行趋势
github
逻极7 小时前
变量与可变性:Rust中的数据绑定
开发语言·后端·rust