关于 cloudflare-pages
面向前端和全栈项目的 Cloudflare Pages 部署技能,介绍通过 Wrangler 或 Git 集成发布网站。涵盖预览部署、Pages Functions、绑定及域名配置。
主要功能
- 01Wrangler 命令行部署
- 02Git 集成与预览部署
- 03Pages Functions 与中间件
- 04KV、D1 和 R2 绑定
- 05自定义域名、响应头与重定向
- 06CI/CD 配置示例
适用场景
- 01发布静态前端网站
- 02为拉取请求生成预览版本
- 03为网站添加边缘 API 路由
- 04配置域名、响应头和重定向
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill cloudflare-pages安装后在 Claude Code 中输入/cloudflare-pages确认已加载。
详细介绍
Cloudflare Pages
在 Cloudflare 的网络上部署前端项目,提供预览构建、边缘函数和全球 CDN 分发。
适用场景
- 部署静态网站(React、Vue、Astro、Hugo、Next.js 静态导出)。
- 使用 Pages Functions 实现服务端逻辑的全栈应用。
- 需要为每个拉取请求自动部署预览版本的项目。
- 希望使用零配置 CDN、自定义域名和 TLS 的团队。
- 从 Vercel、Netlify 或 GitHub Pages 迁移到 Cloudflare 生态系统。
前置条件
- 本地已安装 Node.js 18+ 和 npm。
- 拥有 Cloudflare 账户(大多数项目使用免费套餐即可)。
- 已安装 Wrangler CLI:
npm install -g wrangler。 - 已通过
wrangler login或CLOUDFLARE_API_TOKEN环境变量完成身份验证。 - 源代码位于 Git 仓库中(通过 GitHub 或 GitLab 集成控制面板)。
使用 Wrangler 设置项目
创建新项目
# Create a new Pages project
npx wrangler pages project create my-site
# List existing projects
npx wrangler pages project list
# Delete a project (removes all deployments)
npx wrangler pages project delete my-site
从本地构建输出部署
# Build your framework first
npm run build
# Deploy the output directory
npx wrangler pages deploy dist --project-name=my-site
# Deploy with a custom branch name (triggers preview URL)
npx wrangler pages deploy dist --project-name=my-site --branch=feature-auth
# Deploy and get the deployment URL in JSON
npx wrangler pages deploy dist --project-name=my-site --branch=main 2>&1 | tail -1
列出和管理部署
# List recent deployments
npx wrangler pages deployment list --project-name=my-site
# Tail live logs from a deployment
npx wrangler pages deployment tail --project-name=my-site --environment=production
控制面板 Git 集成
- 前往 Workers & Pages > Create application > Pages。
- 连接你的 GitHub 或 GitLab 账户。
- 选择仓库并配置:
- 生产分支:
main - 构建命令:
npm run build - 构建输出目录:
dist(或根据框架选择build、.next、public)
- 生产分支:
- 按环境设置环境变量(Production 与 Preview)。
框架预设
Cloudflare 会自动检测框架。如有需要,可覆盖预设:
| 框架 | 构建命令 | 输出目录 |
|---|---|---|
| React CRA | npm run build | build |
| Vite | npm run build | dist |
| Next.js | npx @cloudflare/next-on-pages | .vercel/output/static |
| Astro | npm run build | dist |
| Hugo | hugo | public |
| SvelteKit | npm run build | .svelte-kit/cloudflare |
预览部署
每个非生产分支都会自动获得一个唯一的预览 URL。
# URL format for preview deployments
https://<commit-hash>.<project-name>.pages.dev
https://<branch-name>.<project-name>.pages.dev
基于分支的访问控制
# Set preview branch patterns in wrangler.toml (Pages-specific)
# Or configure via dashboard: Settings > Builds & deployments
# Include branches: feature/*, staging
# Exclude branches: dependabot/*
在拉取请求中发布预览评论
启用 Cloudflare Pages GitHub App,以便在 PR 评论中发布部署 URL。在 Settings > Builds & deployments > Preview comment 下进行配置。
Pages Functions
Pages Functions 可提供与静态网站一同部署的服务端逻辑。在项目根目录下的 functions/ 目录中放置文件。
基本 API 路由
// functions/api/hello.ts
export const onRequestGet: PagesFunction = async (context) => {
return new Response(JSON.stringify({ message: "Hello from the edge" }), {
headers: { "Content-Type": "application/json" },
});
};
// functions/api/users/[id].ts — dynamic route parameter
export const onRequestGet: PagesFunction = async (context) => {
const userId = context.params.id;
return new Response(JSON.stringify({ userId }), {
headers: { "Content-Type": "application/json" },
});
};
中间件
// functions/_middleware.ts — runs before all routes
export const onRequest: PagesFunction = async (context) => {
const authHeader = context.request.headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return new Response("Unauthorized", { status: 401 });
}
return context.next();
};
使用绑定的 Functions
// functions/api/data.ts — using KV and D1 bindings
interface Env {
MY_KV: KVNamespace;
MY_DB: D1Database;
MY_BUCKET: R2Bucket;
}
export const onRequestGet: PagesFunction<Env> = async (context) => {
// Read from KV
const cached = await context.env.MY_KV.get("key");
if (cached) return new Response(cached);
// Query D1
const result = await context.env.MY_DB.prepare(
"SELECT * FROM items LIMIT 10"
).all();
// Cache in KV
await context.env.MY_KV.put("key", JSON.stringify(result.results), {
expirationTtl: 300,
});
return Response.json(result.results);
};
Wrangler 配置
# wrangler.toml — Pages project configuration
name = "my-site"
compatibility_date = "2024-09-01"
pages_build_output_dir = "dist"
# KV namespace binding
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123def456"
# D1 database binding
[[d1_databases]]
binding = "MY_DB"
database_name = "my-app-db"
database_id = "xxxx-yyyy-zzzz"
# R2 bucket binding
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "app-assets"
# Environment variables
[vars]
API_BASE_URL = "https://api.example.com"
标头和重定向
自定义标头
# public/_headers
/assets/*
Cache-Control: public, max-age=31536000, immutable
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'
/api/*
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
重定向
# public/_redirects
/old-page /new-page 301
/blog/:slug /posts/:slug 301
/docs/* https://docs.example.com/:splat 302
/home / 302
自定义域名
# Add a custom domain via Cloudflare dashboard:
# Pages project > Custom domains > Set up a custom domain
# Or via API
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/pages/projects/my-site/domains" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"www.example.com"}'
CI/CD 集成
GitHub Actions
# .github/workflows/deploy.yml
name: Deploy to Cloudflare Pages
on:
push:
branches: [main]
pull_request:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy dist --project-name=my-site
故障排除
| 症状 | 原因 | 解决方法 |
|---|---|---|
| 构建因内存不足而失败 | 构建超出 1 GB RAM 限制 | 减少依赖项;使用 NODE_OPTIONS=--max_old_space_size=768 |
| Functions 返回 404 | functions/ 目录不在项目根目录 | 将 functions/ 移到仓库根目录,而不是放在 src/ 中 |
| 预览 URL 显示旧内容 | 浏览器缓存或部署版本过期 | 强制刷新;在部署列表中检查最新提交哈希 |
| 自定义域名显示 SSL 错误 | DNS 未通过 Cloudflare 代理 | 在 CNAME 记录上启用橙色云朵(代理) |
_headers 文件被忽略 | 文件不在构建输出目录中 | 将其放在 public/ 中,以便构建时复制到 dist/ |
| Functions 中的绑定未定义 | 缺少 wrangler.toml 或控制面板配置 | 在 wrangler.toml 中添加绑定并重新部署 |
| 超出 1 MB 函数大小限制 | 打包的依赖项过多 | 使用 Tree-shaking;将大型依赖项移至 KV 或 R2 |
相关技能
- cloudflare-workers - 边缘后端逻辑和 API 路由
- cloudflare-r2 - 用于存储资源和上传文件的对象存储
- cloudflare-zero-trust - 使用 Access 策略保护预览部署
- cdn-setup - 通用 CDN 配置模式
评论
支持 Markdown