Cloudflare Pages:前后端一体化,免费部署全栈应用Cloudflare Pages: All-in-one for frontend and backend, free deployment of full-stack applications


AI free token/AI免费积分

本文来源:https://mp.weixin.qq.com/s/VLYYaKEpU8rHHkPzUa6xKA
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

图片

为什么独立开发者需要它?

上一篇我们讲了 Workers,它擅长处理后端逻辑。但一个完整的应用,还需要前端。传统做法是前端部署到 Vercel/Netlify,后端部署到另一处(使用全栈框架也可以部署到这两个系统),两边还要处理 CORS、域名、环境变量……

Pages 把这件事简化了。

Pages 是 Cloudflare 的全栈应用平台。你把代码推上去,它自动帮你构建、部署、分发到全球 CDN。前端是静态资源,后端是 Functions(本质就是 Workers),一体化管理。

对独立开发者来说,这意味着:

  • • 免费额度很大:静态资源请求无限免费,Functions 同 Workers 免费计划
  • • 一个平台搞定:前后端、域名、SSL、CDN 全在一个地方
  • • Git 集成:推代码自动部署,支持 Preview 分支

图片

Pages 是什么?

Pages 本质上是一个静态站点托管 + Serverless Functions 的组合。

静态资源:HTML、CSS、JS、图片等文件,直接托管到 Cloudflare 全球 CDN,请求不经过 Workers,完全免费且无限制。

Functions:放在 functions/ 目录下的代码,会被部署为 Workers,按 Workers 的计费规则收费。

两者的关系:

你的项目/├── public/          # 静态资源(免费无限)│   ├── index.html│   ├── styles.css│   └── app.js└── functions/       # Serverless Functions(按 Workers 计费)    └── api/        └── users.ts

用户访问 / → 返回静态资源(免费)用户访问 /api/users → 执行 Function(按 Workers 计费)

这种模式让大部分请求都是免费的静态资源请求,只有需要动态处理的请求才走 Functions。

Pages vs Workers:怎么选?

场景 推荐
纯静态站点(博客、文档) Pages
前后端一体的应用 Pages + Functions
纯 API 服务 Workers
需要更多控制(中间件、路由) Workers

简单说:有前端就用 Pages,纯后端就用 Workers。两者可以混用,Functions 本质就是 Workers。

免费额度 & 定价

Pages 的定价分两部分:

静态资源(完全免费)

项目 免费计划 付费计划
带宽 无限 无限
请求 无限 无限
构建次数 500/月 5000/月
Preview 部署 无限 无限

Functions(同 Workers)

项目 免费计划 付费计划($5/月)
请求数 10 万/天 1000 万/月
CPU 时间 10ms/请求 3000 万 CPU ms/月

关键点:静态资源请求完全免费,不计入 Functions 配额。一个典型的网站,90% 以上的请求都是静态资源,Functions 的消耗很少。

图片

5 分钟快速开始

方式一:使用 C3 命令行

npm create cloudflare@latest my-site

选择:

  • • What would you like to start with? → Hello World example
  • • Which template? → Hello World Worker
  • • Which language? → TypeScript
  • • Do you want to deploy? → Yes

方式二:Git 集成

  1. 1. 把代码推到 GitHub/GitLab
  2. 2. 在 Cloudflare Dashboard 创建 Pages 项目
  3. 3. 连接仓库,配置构建命令
  4. 4. 自动构建部署

方式三:Direct Upload

直接上传构建好的文件:

npx wrangler pages deploy ./dist

本地开发

cd my-sitenpx wrangler pages dev

图片

支持的框架

Pages 原生支持几乎所有主流框架:

图片

框架 构建命令 输出目录
Next.js npm run build .next
React (Vite) npm run build dist
Vue (Vite) npm run build dist
SvelteKit npm run build .svelte-kit
Astro npm run build dist
Nuxt npm run build .output
Remix npm run build build
Hugo hugo public
Hexo hexo generate public

以 Next.js 为例:

# 创建 Next.js 项目npx create-next-app@latest my-next-appcd my-next-app# 本地开发npx wrangler pages dev# 部署npx wrangler pages deploy .vercel/output/static

Pages Functions 实战

基础 API

在 functions/ 目录下创建文件,自动变成 API 端点:

// functions/api/hello.tsexport async function onRequest(context: EventContext): Promise {  return Response.json({    message: "Hello from Pages Functions!",    timestamp: Date.now(),  });}

访问 /api/hello 就能拿到 JSON 响应。

处理不同 HTTP 方法

// functions/api/users.tsexport async function onRequestGet(context: EventContext): Promise {  // GET /api/users  const users = await getUsers();  return Response.json(users);}export async function onRequestPost(context: EventContext): Promise {  // POST /api/users  const body = await context.request.json();  const user = await createUser(body);  return Response.json(user, { status: 201 });}

文件名决定路由,方法名决定 HTTP 方法。onRequestGet 处理 GET,onRequestPost 处理 POST。

图片

使用 Bindings

Functions 同样支持 Workers 的所有 Bindings:

// functions/api/data.tsinterface Env {  DB: D1Database;  KV: KVNamespace;}export async function onRequest(context: EventContext): Promise {  const { env } = context;  // 使用 D1  const { results } = await env.DB.prepare("SELECT * FROM items LIMIT 10").all();  // 使用 KV  const config = await env.KV.get("config", { type: "json" });  return Response.json({ items: results, config });}

在 Cloudflare Dashboard 中配置 Bindings,不需要改代码。

中间件

中间件可以在请求到达处理函数前执行逻辑:

// functions/_middleware.tsexport async function onRequest(context: EventContext): Promise {  const { request, next } = context;  // CORS 处理  if (request.method === "OPTIONS") {    return new Response(null, {      headers: {        "Access-Control-Allow-Origin": "*",        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",        "Access-Control-Allow-Headers": "Content-Type",      },    });  }  // 继续执行下一个中间件或处理函数  const response = await next();  // 添加响应头  response.headers.set("X-Processed-By", "Pages Functions");  return response;}

认证示例

// functions/_middleware.tsexport async function onRequest(context: EventContext): Promise {  const { request, next, env } = context;  // 跳过公开路由  const url = new URL(request.url);  if (url.pathname.startsWith("/api/public")) {    return next();  }  // 验证 token  const token = request.headers.get("Authorization")?.replace("Bearer ", "");  if (!token) {    return Response.json({ error: "Unauthorized" }, { status: 401 });  }  const user = await verifyToken(token, env.JWT_SECRET);  if (!user) {    return Response.json({ error: "Invalid token" }, { status: 401 });  }  // 把用户信息传递给后续处理  context.data = { user };  return next();}

实战场景

场景 1:博客 + 评论系统

静态博客(Hugo/Astro)+ 动态评论:

my-blog/├── content/           # Markdown 文章├── layouts/           # 模板├── static/            # 静态资源└── functions/    └── api/        ├── comments.ts    # 评论 API        └── _middleware.ts  # 反垃圾中间件

场景 2:SaaS 仪表盘

React/Vue 前端 + API 后端:

my-saas/├── src/               # 前端代码│   ├── App.tsx│   └── pages/├── public/            # 静态资源└── functions/    └── api/        ├── auth/        # 认证 API        ├── users/       # 用户 API        └── billing/     # 计费 API

场景 3:电商产品页

Next.js + 动态库存/订单:

my-shop/├── app/               # Next.js App Router│   ├── page.tsx       # 首页│   └── products/├── public/            # 产品图片└── functions/    └── api/        ├── products.ts  # 产品 API        ├── cart.ts      # 购物车 API        └── checkout.ts  # 结账 API

自定义域名

添加自定义域名

  1. 1. 在 Cloudflare Dashboard 进入 Pages 项目
  2. 2. 点击 "Custom domains"
  3. 3. 输入你的域名
  4. 4. 按提示配置 DNS 记录

SSL 证书

Pages 自动为所有域名提供 SSL 证书,包括自定义域名。不需要手动配置。

子域名

支持任意子域名:

  • • www.example.com
  • • blog.example.com
  • • app.example.com

环境变量 & Secrets

环境变量

在 Dashboard 中配置,分两种:

  • • Production:生产环境变量
  • • Preview:预览部署变量

代码中访问:

export async function onRequest(context: EventContext): Promise {  const apiKey = context.env.API_KEY;  // 使用 apiKey}

Secrets

敏感信息用 Secrets 存储:

npx wrangler pages secret put API_KEY

Secrets 加密存储,代码中和普通环境变量一样访问。

Preview 部署

每次推送到非生产分支(或 PR),Pages 会自动创建 Preview 部署:

  • • 独立的 URL:<分支名>.<项目名>.pages.dev
  • • 独立的环境变量(Preview 变量)
  • • 不影响生产环境

这对独立开发者很有用:

  • • 测试新功能,不影响线上
  • • 给客户看预览链接
  • • PR 自动部署,Review 更方便

回滚

如果新部署有问题,可以一键回滚到之前的版本:

  1. 1. 在 Dashboard 进入 Pages 项目
  2. 2. 点击 "Deployments"
  3. 3. 找到想要回滚的版本
  4. 4. 点击 "Rollback to this deployment"

回滚立即生效,不需要重新构建。

图片

部署限制

项目 免费计划 付费计划
构建次数 500/月 5000/月
构建时间 20 分钟 20 分钟
文件数量 20,000 20,000
单文件大小 25MB 25MB
项目数量 无限 无限

成本计算器

案例 1:个人博客

  • • 每天 1 万 PV
  • • 95% 静态资源请求
  • • 5% Functions 请求(评论、搜索)

成本:$0/月(全部在免费额度内)

案例 2:小型 SaaS

  • • 每天 5 万 PV
  • • 80% 静态资源请求
  • • 20% Functions 请求

成本:$0-5/月(取决于 Functions 使用量)

案例 3:电商站点

  • • 每天 20 万 PV
  • • 70% 静态资源请求
  • • 30% Functions 请求

成本:$5-15/月

对比传统方案:Vercel Pro $20/月,Netlify Pro $19/月。Pages 的按量计费对独立开发者更友好。

最佳实践 & 避坑指南

1. 静态资源优先

能用静态资源解决的,不要走 Functions。比如:

  • • 配置数据放 JSON 文件,不要每次请求都查数据库
  • • 博客文章预构建为 HTML,不要动态渲染
  • • 图片/视频直接传 R2,不要经过 Functions

2. 合理拆分 Functions

  • • 每个文件一个端点,保持简单
  • • 公共逻辑放 _middleware.ts
  • • 复杂业务用 Advanced Mode(完整的 Worker)

3. 构建优化

{  "scripts": {    "build": "vite build",    "preview": "vite preview"  }}
  • • 使用 Vite/Next.js 的增量构建
  • • 启用构建缓存
  • • 减少不必要的依赖

4. 环境变量管理

  • • 开发环境用 .dev.vars
  • • 生产环境用 Dashboard 或 wrangler pages secret
  • • 不要提交敏感信息到 Git

5. 调试技巧

  • • 本地开发用 wrangler pages dev
  • • 用 console.log() 输出日志
  • • 在 Dashboard 查看 Functions 日志

Pages vs 其他平台

特性 Pages Vercel Netlify
静态资源免费 无限 100GB/月 100GB/月
Functions 免费额度 10 万请求/天 100GB-Hrs 125K 请求/月
自定义域名 SSL 免费自动 免费自动 免费自动
Preview 部署 无限 无限 无限
D1/KV/R2 集成 原生支持 不支持 不支持
价格 $5/月起 $20/月 $19/月

Pages 的优势在于:免费额度更大,和 Cloudflare 生态集成更好。

相关资源

https://developers.cloudflare.com/pages

 

Source of this article: https://mp.weixin.qq.com/s/VLYYaKEpU8rHHkPzUa6xKA If there are copyright issues, please email us at 13951431913#139.com or submit a comment on the right.

图片

Why do indie developers need it?

In the previous article, we covered Workers, which excel at handling backend logic. But a complete application also needs a frontend. The traditional approach is to deploy the frontend to Vercel/Netlify and the backend elsewhere (full-stack frameworks can also be deployed to these two systems), while handling CORS, domains, environment variables, and so on on both sides.

Pages simplifies this.

Pages is Cloudflare's full-stack application platform. You push your code, and it automatically builds, deploys, and distributes it to the global CDN. The frontend is static assets, the backend is Functions (essentially Workers), all managed together.

For indie developers, this means:

• Generous free tier: unlimited free static asset requests; Functions follows the Workers free plan

• One platform handles everything: frontend, backend, domain, SSL, CDN all in one place

• Git integration: push code for automatic deployment, with Preview branch support

图片

What is Pages?

Pages is essentially a combination of static site hosting + Serverless Functions.

Static assets: files such as HTML, CSS, JS, and images are hosted directly on Cloudflare's global CDN. Requests do not go through Workers, and they are completely free and unlimited.

Functions: code in the functions/ directory is deployed as Workers and billed according to Workers' pricing rules.

The relationship between the two:

User visits / → returns static assets (free) User visits /api/users → executes a Function (billed as Workers)

This model makes most requests free static asset requests; only requests that need dynamic processing go through Functions.

Pages vs Workers: how to choose?

Simply put: use Pages if you have a frontend, use Workers for pure backend. They can be mixed; Functions are essentially Workers.

Free tier & pricing

Pages' pricing has two parts:

Static assets (completely free)

Functions (same as Workers)

Key point: static asset requests are completely free and do not count against the Functions quota. On a typical website, more than 90% of requests are static assets, so Functions usage is minimal.

图片

5-minute quick start

Option 1: Use the C3 CLI

Choose:

• What would you like to start with? → Hello World example

• Which template? → Hello World Worker

• Which language? → TypeScript

• Do you want to deploy? → Yes

Option 2: Git integration

1. Push your code to GitHub/GitLab

2. Create a Pages project in the Cloudflare Dashboard

3. Connect the repository and configure the build command

4. It automatically builds and deploys

Option 3: Direct Upload

Directly upload the built files:

Local development

图片

Supported frameworks

Pages natively supports almost all major frameworks:

图片

Taking Next.js as an example:

Pages Functions in practice

Basic API

Create a file in the functions/ directory and it automatically becomes an API endpoint:

Visiting /api/hello returns a JSON response.

Handling different HTTP methods

The file name determines the route, and the method name determines the HTTP method. onRequestGet handles GET, onRequestPost handles POST.

图片

Using Bindings

Functions also support all of Workers' Bindings:

Configure Bindings in the Cloudflare Dashboard without changing code.

Middleware

Middleware can execute logic before the request reaches the handler:

Authentication example

Real-world scenarios

Scenario 1: Blog + comment system

Static blog (Hugo/Astro) + dynamic comments:

Scenario 2: SaaS dashboard

React/Vue frontend + API backend:

Scenario 3: E-commerce product pages

Next.js + dynamic inventory/orders:

Custom domains

Adding a custom domain

1. Go to the Pages project in the Cloudflare Dashboard

2. Click "Custom domains"

3. Enter your domain

4. Configure DNS records as prompted

SSL certificates

Pages automatically provides SSL certificates for all domains, including custom domains. No manual configuration is needed.

Subdomains

Supports any subdomain:

• www.example.com

• blog.example.com

• app.example.com

Environment variables & Secrets

Environment variables

Configure them in the Dashboard; there are two types:

• Production: production environment variables

• Preview: preview deployment variables

Access them in code:

Secrets

Store sensitive information in Secrets:

Secrets are encrypted at rest and accessed in code just like regular environment variables.

Preview deployments

Every time you push to a non-production branch (or PR), Pages automatically creates a Preview deployment:

• A unique URL: ..pages.dev

• Separate environment variables (Preview variables)

• Does not affect the production environment

This is very useful for indie developers:

• Test new features without affecting production

• Show preview links to clients

• PRs are automatically deployed, making reviews easier

Rollback

If a new deployment has issues, you can roll back to a previous version with one click:

1. Go to the Pages project in the Dashboard

2. Click "Deployments"

3. Find the version you want to roll back to

4. Click "Rollback to this deployment"

The rollback takes effect immediately; no rebuild is needed.

图片

Deployment limits

Cost calculator

Case 1: Personal blog

• 10,000 page views per day

• 95% static asset requests

• 5% Functions requests (comments, search)

Cost: $0/month (all within the free tier)

Case 2: Small SaaS

• 50,000 page views per day

• 80% static asset requests

• 20% Functions requests

Cost: $0-5/month (depends on Functions usage)

Case 3: E-commerce site

• 200,000 page views per day

• 70% static asset requests

• 30% Functions requests

Cost: $5-15/month

Compared with traditional options: Vercel Pro $20/month, Netlify Pro $19/month. Pages' usage-based billing is friendlier for indie developers.

Best practices & pitfalls to avoid

1. Prioritize static assets

If it can be solved with static assets, don't use Functions. For example:

• Put configuration data in JSON files; don't query the database on every request

• Pre-build blog posts as HTML; don't render dynamically

• Upload images/videos directly to R2; don't route them through Functions

2. Split Functions sensibly

• One endpoint per file; keep it simple

• Put shared logic in _middleware.ts

• For complex business logic, use Advanced Mode (a full Worker)

3. Build optimization

• Use incremental builds from Vite/Next.js

• Enable build caching

• Reduce unnecessary dependencies

4. Environment variable management

• Use .dev.vars for development environments

• Use Dashboard or wrangler pages secret for production

• Don't commit sensitive information to Git

5. Debugging tips

• Use wrangler pages dev for local development

• Use console.log() to output logs

• View Functions logs in the Dashboard

Pages vs other platforms

Pages' advantages are a larger free tier and better integration with the Cloudflare ecosystem.

Related resources

https://developers.cloudflare.com/pages

暂无评论,快来发表第一条评论吧!No comments yet. Be the first!

📮 需求咨询📮 Inquiry