The Own Lab The Own Lab

Cloudflare Pages

前端部署平台的架構、設定、與 Vercel / Netlify 的差異比較

Overview##

Cloudflare Pages 是 Cloudflare 的前端部署平台。連結 Git repository 後,每次 push 自動 build + deploy,靜態資源透過全球 CDN 分發。

部署平台比較###

面向CF PagesVercelNetlifyDocker + 自建
定位靜態 + EdgeSSR 優先靜態 + Serverless完全自控
框架偏好Next.js 深度整合無限制
Edge RuntimeWorkersEdge FunctionsEdge Functions自建
Egress 費用免費超量收費超量收費看雲端商
免費額度500 次 build/月100GB 頻寬/月100GB 頻寬/月機器成本
生態整合R2, D1, Workers, KV無限制
維運負擔全部自己來

選擇原則:

  • Next.js 專案 → Vercel(原生支援最好)
  • 靜態 / Astro / 非 Next.js 框架 → CF Pages(免費 + 快 + 生態整合)
  • 需要完全控制 → Docker + 自建

Note

CF Pages 的核心優勢不只是免費——而是與 Cloudflare 生態的深度整合。一個帳號內可以無縫使用 R2(儲存)、D1(資料庫)、KV(鍵值快取)、Workers(邊緣運算)。

Architecture##

CF Pages 的部署流程:

graph LR
  A[Git Push] --> B[Build Trigger]
  B --> C[Build 環境]
  C --> D[靜態資源]
  D --> E[全球 CDN]
  C --> F[Functions]
  F --> G[Workers Runtime]

兩種部署方式###

方式說明適用場景
Git 連接連結 GitHub / GitLab,push 觸發主要工作流程
Direct Upload用 Wrangler CLI 上傳 build 產出CI/CD 自訂流程

Preview Deployments###

每個 branch / PR 自動部署到獨立的 preview URL:

main       → my-app.pages.dev
feat/login → abc123.my-app.pages.dev

Tip

Preview deployment 可以直接分享給團隊 review,不需要本地跑 build。每個 PR 都有自己的獨立環境。

Setup##

Git 連接部署###

  1. Cloudflare Dashboard → Pages → Create a project
  2. Connect to Git → 選擇 repository
  3. 設定 build 參數:
Framework preset:  Astro(自動偵測)
Build command:     npm run build
Build output:      dist
Root directory:    /              (monorepo 可指定子目錄)

Wrangler CLI 部署###

# 先在本地 build
pnpm run build

# 部署到 Pages
wrangler pages deploy ./dist --project-name my-app

# 部署到特定 branch(preview)
wrangler pages deploy ./dist --project-name my-app --branch feat/login

環境變數###

# Dashboard → Pages → Settings → Environment Variables

# 或用 wrangler.toml
# [vars]
# API_URL = "https://api.example.com"

# 敏感資料用 Secrets(Dashboard 設定,不進版控)
# DATABASE_URL = "postgres://..."
類型設定方式適用
Variableswrangler.toml 或 Dashboard非敏感設定
Secrets僅 DashboardAPI keys、密碼
Production / Preview各自獨立設定環境分離

Custom Domain##

把自訂域名綁定到 Pages 專案:

  1. Pages → Custom domains → Set up a domain
  2. 輸入域名(如 app.example.com
  3. Cloudflare 自動建立 CNAME 紀錄
# Cloudflare 自動建立的 DNS 紀錄
app.example.com.    IN  CNAME  my-app.pages.dev.    # Proxy: ON

Note

域名必須已在 Cloudflare DNS 管理中。SSL 憑證自動產生,不需要額外設定。

Functions##

Pages Functions 讓你在 Pages 專案中加入 server-side 邏輯,底層是 Cloudflare Workers:

project/
├── src/              ← 前端原始碼
├── functions/        ← Pages Functions(自動部署)
│   ├── api/
│   │   └── hello.ts  → GET /api/hello
│   └── webhook.ts    → POST /webhook
└── dist/             ← build 產出
// functions/api/hello.ts
export const onRequestGet: PagesFunction = async (context) => {
  return new Response(JSON.stringify({ message: 'Hello from Edge!' }), {
    headers: { 'Content-Type': 'application/json' },
  });
};

路由規則基於檔案結構:

檔案路徑路由
functions/api/hello.ts/api/hello
functions/api/users/[id].ts/api/users/:id
functions/api/[...path].ts/api/*(catch-all)

綁定 R2 / D1 / KV###

// functions/api/upload.ts
interface Env {
  ASSETS: R2Bucket;
  DB: D1Database;
  CACHE: KVNamespace;
}

export const onRequestPost: PagesFunction<Env> = async (context) => {
  // 存檔到 R2
  await context.env.ASSETS.put('file.txt', context.request.body);

  // 查詢 D1
  const result = await context.env.DB.prepare('SELECT * FROM users').all();

  return new Response('OK');
};

Warning

Pages Functions 運行在 Workers Runtime(V8 Isolate),不是 Node.js。部分 Node.js API 不可用(如 fspath)。使用前確認相容性。

Build Configuration##

Monorepo 設定###

在 monorepo 中部署特定子專案:

Root directory:    apps/my-app
Build command:     cd ../.. && pnpm nx build my-app
Build output:      apps/my-app/dist

Build 快取###

CF Pages 會自動快取 node_modules。如果需要清除:

Dashboard → Deployments → 選擇部署 → Retry deployment(勾選 clear cache)

常見 Build 設定###

框架Build CommandOutput Directory
Astronpm run builddist
Next.jsnpx @cloudflare/next-on-pages.vercel/output/static
Vite / Reactnpm run builddist
SvelteKitnpm run build.svelte-kit/cloudflare

Quiz##

Single Choice

CF Pages 相比 Vercel 的核心優勢是什麼?

Single Choice

Pages Functions 的底層是什麼?

Single Choice

在 Pages Functions 中,functions/api/users/[id].ts 對應哪個路由?

Single Choice

Preview Deployment 的主要用途是什麼?

Single Choice

在 Monorepo 中部署 Pages 專案,以下哪個設定是必要的?

Summary##

  • CF Pages 是前端部署平台,Git push 觸發自動 build + deploy + CDN 分發
  • 核心優勢:免費 egress + Cloudflare 生態整合(R2、D1、KV、Workers)
  • 每個 branch/PR 自動建立 Preview Deployment,方便團隊 review
  • Pages Functions 基於 Workers Runtime(V8 Isolate),不是 Node.js
  • 檔案系統路由:functions/api/users/[id].ts/api/users/:id
  • Monorepo 需設定 Root directory 指向子專案目錄

留言 (0)

登入後即可留言