cloudflare-full-stack-scaffold

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Full-Stack Scaffold

Cloudflare 全栈脚手架

Complete, production-ready starter project for building full-stack applications on Cloudflare with React, Hono, AI SDK, and all Cloudflare services pre-configured.
这是一套完整的生产级启动项目,用于在 Cloudflare 上构建全栈应用,预配置了 React、Hono、AI SDK 以及所有 Cloudflare 服务。

When to Use This Skill

何时使用该工具

Use this skill when you need to:
  • Start a new full-stack Cloudflare project in minutes instead of hours
  • Build AI-powered applications with chat interfaces, RAG, or tool calling
  • Have core Cloudflare services ready (D1, KV, R2, Workers AI)
  • Opt-in to advanced features (Clerk Auth, AI Chat, Queues, Vectorize)
  • Use modern best practices (Tailwind v4, shadcn/ui, AI SDK, React 19)
  • Include planning docs and session handoff from the start
  • Choose your AI provider (Workers AI, OpenAI, Anthropic, Gemini)
  • Enable features only when needed with simple npm scripts
  • Avoid configuration errors and integration issues
当你有以下需求时可使用本工具:
  • 数分钟而非数小时启动新的全栈 Cloudflare 项目
  • 构建带聊天界面、RAG 或工具调用的 AI 驱动应用
  • 获得开箱即用的 Cloudflare 核心服务(D1、KV、R2、Workers AI)
  • 按需选用高级功能(Clerk Auth、AI Chat、Queues、Vectorize)
  • 采用现代开发最佳实践(Tailwind v4、shadcn/ui、AI SDK、React 19)
  • 从项目初始就包含规划文档和会话交接机制
  • 可自主选择 AI 提供商(Workers AI、OpenAI、Anthropic、Gemini)
  • 通过简单 npm 脚本按需启用功能
  • 避免配置错误和集成问题

What This Skill Provides

本工具提供的能力

Complete Scaffold Project

完整的脚手架项目

A fully working application you can copy, customize, and deploy immediately:
bash
undefined
你可以直接复制、自定义并立即部署的可用应用:
bash
undefined

Copy the scaffold

复制脚手架

cp -r scaffold/ my-new-app/ cd my-new-app/
cp -r scaffold/ my-new-app/ cd my-new-app/

Install dependencies

安装依赖

npm install
npm install

Initialize core services (D1, KV, R2)

初始化核心服务(D1、KV、R2)

./scripts/init-services.sh
./scripts/init-services.sh

Create database tables

创建数据库表

npm run d1:local
npm run d1:local

Start developing

启动开发环境

npm run dev

**Result**: Full-stack app running in ~5 minutes with:
- ✅ Frontend and backend connected
- ✅ Core Cloudflare services configured (D1, KV, R2, Workers AI)
- ✅ AI SDK ready with multiple providers
- ✅ Planning docs and session handoff protocol
- ✅ Dark mode, theming, UI components
- ✅ Optional features (1 script each to enable):
  - Clerk Auth (`npm run enable-auth`)
  - AI Chat UI (`npm run enable-ai-chat`)
  - Queues (`npm run enable-queues`)
  - Vectorize (`npm run enable-vectorize`)
npm run dev

**效果**:约5分钟即可运行全栈应用,包含:
- ✅ 前后端已连通
- ✅ Cloudflare 核心服务已配置(D1、KV、R2、Workers AI)
- ✅ AI SDK 已就绪,支持多提供商
- ✅ 规划文档与会话交接协议
- ✅ 暗色模式、主题系统、UI 组件
- ✅ 可选功能(每个功能只需1个脚本即可启用):
  - Clerk Auth(`npm run enable-auth`)
  - AI Chat UI(`npm run enable-ai-chat`)
  - Queues(`npm run enable-queues`)
  - Vectorize(`npm run enable-vectorize`)

Scaffold Structure

脚手架结构

scaffold/
├── package.json              # All dependencies (React, Hono, AI SDK, Clerk)
├── tsconfig.json            # TypeScript config
├── vite.config.ts           # Cloudflare Vite plugin
├── wrangler.jsonc           # All Cloudflare services configured
├── .dev.vars.example        # Environment variables template
├── .gitignore               # Standard ignores
├── README.md                # Project-specific readme
├── CLAUDE.md                # Project instructions for Claude
├── SCRATCHPAD.md            # Session handoff protocol
├── CHANGELOG.md             # Version history
├── schema.sql               # D1 database schema
├── docs/                    # Complete planning docs
│   ├── ARCHITECTURE.md
│   ├── DATABASE_SCHEMA.md
│   ├── API_ENDPOINTS.md
│   ├── IMPLEMENTATION_PHASES.md
│   ├── UI_COMPONENTS.md
│   └── TESTING.md
├── migrations/              # D1 migrations
│   └── 0001_initial.sql
├── src/                     # Frontend (React + Vite + Tailwind v4)
│   ├── main.tsx
│   ├── App.tsx
│   ├── index.css           # Tailwind v4 theming
│   ├── components/
│   │   ├── ui/             # shadcn/ui components
│   │   ├── ThemeProvider.tsx
│   │   ├── ProtectedRoute.tsx     # Auth (COMMENTED)
│   │   └── ChatInterface.tsx      # AI chat (COMMENTED)
│   ├── lib/
│   │   ├── utils.ts        # cn() utility
│   │   └── api-client.ts   # Fetch wrapper
│   └── pages/
│       ├── Home.tsx
│       ├── Dashboard.tsx
│       └── Chat.tsx        # AI chat page (COMMENTED)
└── backend/                 # Backend (Hono + Cloudflare)
    ├── src/
    │   └── index.ts        # Main Worker entry
    ├── middleware/
    │   ├── cors.ts
    │   └── auth.ts         # JWT (COMMENTED)
    ├── routes/
    │   ├── api.ts          # Basic API routes
    │   ├── d1.ts           # D1 examples
    │   ├── kv.ts           # KV examples
    │   ├── r2.ts           # R2 examples
    │   ├── ai.ts           # Workers AI (direct binding)
    │   ├── ai-sdk.ts       # AI SDK examples (multiple providers)
    │   ├── vectorize.ts    # Vectorize examples
    │   └── queues.ts       # Queues examples
    └── db/
        └── queries.ts      # D1 typed query helpers
scaffold/
├── package.json              # 所有依赖(React、Hono、AI SDK、Clerk)
├── tsconfig.json            # TypeScript 配置
├── vite.config.ts           # Cloudflare Vite 插件
├── wrangler.jsonc           # 所有 Cloudflare 服务已配置
├── .dev.vars.example        # 环境变量模板
├── .gitignore               # 标准忽略规则
├── README.md                # 项目专属说明文档
├── CLAUDE.md                # 面向 Claude 的项目说明
├── SCRATCHPAD.md            # 会话交接协议
├── CHANGELOG.md             # 版本历史
├── schema.sql               # D1 数据库 schema
├── docs/                    # 完整规划文档
│   ├── ARCHITECTURE.md
│   ├── DATABASE_SCHEMA.md
│   ├── API_ENDPOINTS.md
│   ├── IMPLEMENTATION_PHASES.md
│   ├── UI_COMPONENTS.md
│   └── TESTING.md
├── migrations/              # D1 迁移文件
│   └── 0001_initial.sql
├── src/                     # 前端(React + Vite + Tailwind v4)
│   ├── main.tsx
│   ├── App.tsx
│   ├── index.css           # Tailwind v4 主题配置
│   ├── components/
│   │   ├── ui/             # shadcn/ui 组件
│   │   ├── ThemeProvider.tsx
│   │   ├── ProtectedRoute.tsx     # 鉴权(已注释)
│   │   └── ChatInterface.tsx      # AI 聊天(已注释)
│   ├── lib/
│   │   ├── utils.ts        # cn() 工具函数
│   │   └── api-client.ts   # Fetch 封装
│   └── pages/
│       ├── Home.tsx
│       ├── Dashboard.tsx
│       └── Chat.tsx        # AI 聊天页面(已注释)
└── backend/                 # 后端(Hono + Cloudflare)
    ├── src/
    │   └── index.ts        # Worker 主入口
    ├── middleware/
    │   ├── cors.ts
    │   └── auth.ts         # JWT(已注释)
    ├── routes/
    │   ├── api.ts          # 基础 API 路由
    │   ├── d1.ts           # D1 示例
    │   ├── kv.ts           # KV 示例
    │   ├── r2.ts           # R2 示例
    │   ├── ai.ts           # Workers AI(直接绑定)
    │   ├── ai-sdk.ts       # AI SDK 示例(多提供商)
    │   ├── vectorize.ts    # Vectorize 示例
    │   └── queues.ts       # Queues 示例
    └── db/
        └── queries.ts      # D1 类型化查询辅助函数

Helper Scripts

辅助脚本

scripts/setup-project.sh
:
  • Copies scaffold to new directory
  • Renames project in package.json
  • Initializes git repository
  • Runs npm install
  • Prompts to initialize services
scripts/init-services.sh
:
  • Creates D1 database via wrangler
  • Creates KV namespace
  • Creates R2 bucket
  • Updates wrangler.jsonc with IDs
  • (Queues and Vectorize created when enabled)
scripts/enable-auth.sh
:
  • Uncomments all Clerk auth patterns
  • Enables ProtectedRoute component
  • Enables auth middleware
  • Prompts for Clerk API keys
  • Updates .dev.vars
scripts/enable-ai-chat.sh
:
  • Uncomments ChatInterface component
  • Uncomments Chat page
  • Enables AI SDK UI patterns
  • Adds chat route to App.tsx
  • Prompts for AI provider API keys
scripts/enable-queues.sh
:
  • Uncomments Queues routes and bindings
  • Enables async message processing
  • Provides queue creation instructions
  • Updates backend and config files
scripts/enable-vectorize.sh
:
  • Uncomments Vectorize routes and bindings
  • Enables vector search and RAG
  • Provides index creation instructions
  • Configures embedding dimensions
scripts/setup-project.sh
  • 复制脚手架到新目录
  • 在 package.json 中重命名项目
  • 初始化 git 仓库
  • 执行 npm install
  • 提示初始化服务
scripts/init-services.sh
  • 通过 wrangler 创建 D1 数据库
  • 创建 KV 命名空间
  • 创建 R2 存储桶
  • 用 ID 更新 wrangler.jsonc
  • (Queues 和 Vectorize 在启用时创建)
scripts/enable-auth.sh
  • 取消所有 Clerk 鉴权代码的注释
  • 启用 ProtectedRoute 组件
  • 启用鉴权中间件
  • 提示输入 Clerk API 密钥
  • 更新 .dev.vars
scripts/enable-ai-chat.sh
  • 取消 ChatInterface 组件的注释
  • 取消 Chat 页面的注释
  • 启用 AI SDK UI 模式
  • 向 App.tsx 添加聊天路由
  • 提示输入 AI 提供商 API 密钥
scripts/enable-queues.sh
  • 取消 Queues 路由和绑定的注释
  • 启用异步消息处理
  • 提供队列创建说明
  • 更新后端和配置文件
scripts/enable-vectorize.sh
  • 取消 Vectorize 路由和绑定的注释
  • 启用向量搜索和 RAG
  • 提供索引创建说明
  • 配置嵌入维度

Reference Documentation

参考文档

references/quick-start-guide.md
:
  • 5-minute setup walkthrough
  • First deployment guide
  • Common customizations
references/service-configuration.md
:
  • Details on each Cloudflare service
  • When to use each one
  • Configuration options
references/ai-sdk-guide.md
:
  • AI SDK Core vs UI
  • Provider switching patterns
  • Streaming and tool calling
  • RAG implementation
references/customization-guide.md
:
  • Removing unused services
  • Adding new routes/pages
  • Customizing theme
  • Project structure best practices
references/enabling-auth.md
:
  • Clerk setup walkthrough
  • JWT template configuration
  • Testing auth flow
references/quick-start-guide.md
  • 5分钟配置流程
  • 首次部署指南
  • 常见自定义操作
references/service-configuration.md
  • 每个 Cloudflare 服务的详情
  • 各服务适用场景
  • 配置选项
references/ai-sdk-guide.md
  • AI SDK Core 与 UI 的区别
  • 提供商切换模式
  • 流式传输和工具调用
  • RAG 实现
references/customization-guide.md
  • 移除未使用的服务
  • 添加新路由/页面
  • 自定义主题
  • 项目结构最佳实践
references/enabling-auth.md
  • Clerk 配置流程
  • JWT 模板配置
  • 鉴权流程测试

Key Integrations

核心集成

1. AI SDK Integration (Three Approaches)

1. AI SDK 集成(三种方式)

Direct Workers AI Binding (fastest):
typescript
// Already works, no API key needed
const result = await c.env.AI.run('@cf/meta/llama-3-8b-instruct', {
  messages: [{ role: 'user', content: 'Hello' }]
})
AI SDK with Workers AI (portable code, same infrastructure):
typescript
import { streamText } from 'ai'
import { createWorkersAI } from 'workers-ai-provider'

const workersai = createWorkersAI({ binding: c.env.AI })
const result = await streamText({
  model: workersai('@cf/meta/llama-3-8b-instruct'),
  messages: [{ role: 'user', content: 'Hello' }]
})
AI SDK with External Providers (OpenAI, Anthropic, Gemini):
typescript
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'

// Switch providers in 1 line
const result = await streamText({
  model: openai('gpt-4o'),  // or anthropic('claude-sonnet-4-5')
  messages: [{ role: 'user', content: 'Hello' }]
})
AI SDK v5 UI - Chat Interface (COMMENTED, enable with script):
tsx
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
import { useState } from 'react'

function ChatInterface() {
  const [input, setInput] = useState('')
  const { messages, sendMessage, status } = useChat({
    transport: new DefaultChatTransport({
      api: '/api/ai-sdk/chat',
    }),
  })

  // Send message on Enter key
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && status === 'ready' && input.trim()) {
      sendMessage({ text: input })
      setInput('')
    }
  }

  // Render messages (v5 uses message.parts[])
  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.parts.map(part => {
            if (part.type === 'text') return <div>{part.text}</div>
          })}
        </div>
      ))}
      <input
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={handleKeyDown}
        disabled={status !== 'ready'}
      />
    </div>
  )
}
直接 Workers AI 绑定(速度最快):
typescript
// 开箱即用,无需 API 密钥
const result = await c.env.AI.run('@cf/meta/llama-3-8b-instruct', {
  messages: [{ role: 'user', content: 'Hello' }]
})
搭配 Workers AI 使用 AI SDK(代码可移植,相同基础设施):
typescript
import { streamText } from 'ai'
import { createWorkersAI } from 'workers-ai-provider'

const workersai = createWorkersAI({ binding: c.env.AI })
const result = await streamText({
  model: workersai('@cf/meta/llama-3-8b-instruct'),
  messages: [{ role: 'user', content: 'Hello' }]
})
搭配外部提供商使用 AI SDK(OpenAI、Anthropic、Gemini):
typescript
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'

// 只需1行即可切换提供商
const result = await streamText({
  model: openai('gpt-4o'),  // 或 anthropic('claude-sonnet-4-5')
  messages: [{ role: 'user', content: 'Hello' }]
})
AI SDK v5 UI - 聊天界面(已注释,可通过脚本启用):
tsx
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
import { useState } from 'react'

function ChatInterface() {
  const [input, setInput] = useState('')
  const { messages, sendMessage, status } = useChat({
    transport: new DefaultChatTransport({
      api: '/api/ai-sdk/chat',
    }),
  })

  // 按 Enter 键发送消息
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && status === 'ready' && input.trim()) {
      sendMessage({ text: input })
      setInput('')
    }
  }

  // 渲染消息(v5 使用 message.parts[])
  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.parts.map(part => {
            if (part.type === 'text') return <div>{part.text}</div>
          })}
        </div>
      ))}
      <input
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={handleKeyDown}
        disabled={status !== 'ready'}
      />
    </div>
  )
}

2. Forms & Data Fetching (React Hook Form + Zod + TanStack Query)

2. 表单与数据获取(React Hook Form + Zod + TanStack Query)

Industry-Standard Libraries for Production Apps:
React Hook Form - Performant form state management:
tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'

const form = useForm({
  resolver: zodResolver(userSchema), // Zod validation
})

<input {...register('name')} />
{errors.name && <span>{errors.name.message}</span>}
Zod v4 - TypeScript-first schema validation:
typescript
// Define schema once
const userSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
})

// Infer TypeScript type
type User = z.infer<typeof userSchema>

// Use in frontend (React Hook Form)
resolver: zodResolver(userSchema)

// Use in backend (same schema!)
const validated = userSchema.parse(requestBody)
TanStack Query v5 - Smart data fetching & caching:
typescript
// Fetch data with automatic caching
const { data, isLoading } = useQuery({
  queryKey: ['users'],
  queryFn: () => apiClient.get('/api/users'),
})

// Update data with mutations
const mutation = useMutation({
  mutationFn: (newUser) => apiClient.post('/api/users', newUser),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['users'] })
  },
})
Full-Stack Validation Pattern:
  • ✅ Define schema in
    shared/schemas/
    (single source of truth)
  • ✅ Frontend validates instantly (React Hook Form + Zod)
  • ✅ Backend validates securely (same Zod schema)
  • ✅ TypeScript types inferred automatically
  • ✅ Update validation once, applies everywhere
Complete Working Examples:
  • Profile page with form:
    /profile
    route
  • Dashboard with queries:
    /dashboard
    route
  • Form component:
    src/components/UserProfileForm.tsx
  • Backend validation:
    backend/routes/forms.ts
  • Shared schemas:
    shared/schemas/userSchema.ts
See
references/supporting-libraries-guide.md
for comprehensive guide.
生产级应用的行业标准库
React Hook Form - 高性能表单状态管理:
tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'

const form = useForm({
  resolver: zodResolver(userSchema), // Zod 校验
})

<input {...register('name')} />
{errors.name && <span>{errors.name.message}</span>}
Zod v4 - TypeScript 优先的 schema 校验:
typescript
// 仅定义一次 schema
const userSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
})

// 自动推导 TypeScript 类型
type User = z.infer<typeof userSchema>

// 前端使用(React Hook Form)
resolver: zodResolver(userSchema)

// 后端使用(相同 schema!)
const validated = userSchema.parse(requestBody)
TanStack Query v5 - 智能数据获取与缓存:
typescript
// 自动缓存的方式获取数据
const { data, isLoading } = useQuery({
  queryKey: ['users'],
  queryFn: () => apiClient.get('/api/users'),
})

// 通过 mutation 更新数据
const mutation = useMutation({
  mutationFn: (newUser) => apiClient.post('/api/users', newUser),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['users'] })
  },
})
全栈校验模式
  • ✅ 在
    shared/schemas/
    中定义 schema(唯一数据源)
  • ✅ 前端实时校验(React Hook Form + Zod)
  • ✅ 后端安全校验(相同 Zod schema)
  • ✅ 自动推导 TypeScript 类型
  • ✅ 只需更新一次校验规则,全栈生效
完整可用示例
  • 带表单的个人资料页面:
    /profile
    路由
  • 带查询的仪表盘:
    /dashboard
    路由
  • 表单组件:
    src/components/UserProfileForm.tsx
  • 后端校验:
    backend/routes/forms.ts
  • 共享 schema:
    shared/schemas/userSchema.ts
查看
references/supporting-libraries-guide.md
获取完整指南。

3. All Cloudflare Services Pre-Configured

3. 所有 Cloudflare 服务预配置

Database (D1):
  • Schema file with example tables
  • Migrations directory
  • Typed query helpers
  • Example CRUD routes
Key-Value Storage (KV):
  • Get/put/delete examples
  • TTL patterns
  • Bulk operations
Object Storage (R2):
  • Upload/download examples
  • Presigned URLs
  • Streaming large files
AI Inference (Workers AI):
  • Text generation
  • Embeddings
  • Image generation (Stable Diffusion)
Vector Database (Vectorize):
  • Insert/query embeddings
  • RAG patterns
  • Similarity search
Message Queues:
  • Producer examples
  • Consumer patterns
  • Batch processing
数据库(D1)
  • 带示例表的 schema 文件
  • 迁移文件目录
  • 类型化查询辅助函数
  • 示例 CRUD 路由
键值存储(KV)
  • Get/put/delete 示例
  • TTL 模式
  • 批量操作
对象存储(R2)
  • 上传/下载示例
  • 预签名 URL
  • 大文件流式传输
AI 推理(Workers AI)
  • 文本生成
  • 嵌入向量
  • 图像生成(Stable Diffusion)
向量数据库(Vectorize)
  • 插入/查询嵌入向量
  • RAG 模式
  • 相似度搜索
消息队列
  • 生产者示例
  • 消费者模式
  • 批量处理

3. Optional Clerk Authentication

3. 可选 Clerk 鉴权

All auth patterns included but COMMENTED - uncomment to enable:
bash
./scripts/enable-auth.sh
所有鉴权模式已包含但已注释 - 取消注释即可启用:
bash
./scripts/enable-auth.sh

Prompts for Clerk keys, uncomments all patterns

提示输入 Clerk 密钥,取消所有代码注释


**What gets enabled**:
- Frontend: ProtectedRoute component, auth in api-client
- Backend: JWT verification middleware
- Protected API routes
- Auth loading states
- Session management

**启用的内容**:
- 前端:ProtectedRoute 组件、api-client 中的鉴权逻辑
- 后端:JWT 验证中间件
- 受保护的 API 路由
- 鉴权加载状态
- 会话管理

4. Planning Docs + Session Handoff Protocol

4. 规划文档 + 会话交接协议

docs/ directory - Complete planning structure:
  • ARCHITECTURE.md: System design
  • DATABASE_SCHEMA.md: D1 schema docs
  • API_ENDPOINTS.md: All routes documented
  • IMPLEMENTATION_PHASES.md: Phased build approach
  • UI_COMPONENTS.md: Component hierarchy
  • TESTING.md: Test strategy
SCRATCHPAD.md - Session handoff protocol:
  • Current phase tracking
  • Progress checkpoints
  • Next actions
  • References to planning docs
docs/ 目录 - 完整的规划结构:
  • ARCHITECTURE.md:系统设计
  • DATABASE_SCHEMA.md:D1 schema 文档
  • API_ENDPOINTS.md:所有路由的文档
  • IMPLEMENTATION_PHASES.md:分阶段构建方案
  • UI_COMPONENTS.md:组件层级
  • TESTING.md:测试策略
SCRATCHPAD.md - 会话交接协议:
  • 当前阶段跟踪
  • 进度检查点
  • 下一步动作
  • 规划文档引用

Usage Guide

使用指南

Quick Start (5 Minutes)

快速开始(5分钟)

bash
undefined
bash
undefined

1. Copy scaffold

1. 复制脚手架

cd /path/to/skills/cloudflare-full-stack-scaffold cp -r scaffold/ ~/projects/my-new-app/ cd ~/projects/my-new-app/
cd /path/to/skills/cloudflare-full-stack-scaffold cp -r scaffold/ ~/projects/my-new-app/ cd ~/projects/my-new-app/

2. Run setup

2. 执行安装

npm install
npm install

3. Initialize Cloudflare services

3. 初始化 Cloudflare 服务

npx wrangler d1 create my-app-db npx wrangler kv:namespace create my-app-kv npx wrangler r2 bucket create my-app-bucket npx wrangler vectorize create my-app-index --dimensions=1536 npx wrangler queues create my-app-queue
npx wrangler d1 create my-app-db npx wrangler kv:namespace create my-app-kv npx wrangler r2 bucket create my-app-bucket npx wrangler vectorize create my-app-index --dimensions=1536 npx wrangler queues create my-app-queue

4. Update wrangler.jsonc with IDs from step 3

4. 用步骤3返回的ID更新 wrangler.jsonc

5. Create D1 tables

5. 创建 D1 表

npx wrangler d1 execute my-app-db --local --file=schema.sql
npx wrangler d1 execute my-app-db --local --file=schema.sql

6. Start dev server

6. 启动开发服务器

npm run dev

**Visit**: http://localhost:5173
npm run dev

**访问地址**:http://localhost:5173

Enable Authentication (Optional)

启用鉴权(可选)

bash
./scripts/enable-auth.sh
bash
./scripts/enable-auth.sh

Prompts for Clerk publishable and secret keys

提示输入 Clerk 可发布密钥和密钥

Uncomments all auth patterns

取消所有鉴权代码的注释

Updates .dev.vars

更新 .dev.vars

npm run dev
undefined
npm run dev
undefined

Enable AI Chat Interface (Optional)

启用 AI 聊天界面(可选)

bash
./scripts/enable-ai-chat.sh
bash
./scripts/enable-ai-chat.sh

Uncomments ChatInterface component

取消 ChatInterface 组件的注释

Uncomments Chat page

取消 Chat 页面的注释

Prompts for OpenAI/Anthropic API keys (optional)

提示输入 OpenAI/Anthropic API 密钥(可选)

npm run dev

**Visit**: http://localhost:5173/chat
npm run dev

**访问地址**:http://localhost:5173/chat

Deploy to Production

部署到生产环境

bash
undefined
bash
undefined

Build

构建

npm run build
npm run build

Deploy

部署

npx wrangler deploy
npx wrangler deploy

Migrate production database

迁移生产数据库

npx wrangler d1 execute my-app-db --remote --file=schema.sql
npx wrangler d1 execute my-app-db --remote --file=schema.sql

Set production secrets

设置生产环境密钥

npx wrangler secret put CLERK_SECRET_KEY npx wrangler secret put OPENAI_API_KEY
undefined
npx wrangler secret put CLERK_SECRET_KEY npx wrangler secret put OPENAI_API_KEY
undefined

Customization Patterns

自定义模式

Remove Unused Services

移除未使用的服务

Don't need Vectorize?
  1. Delete
    backend/routes/vectorize.ts
  2. Remove vectorize binding from
    wrangler.jsonc
  3. Remove from
    vite.config.ts
    cloudflare plugin
  4. Remove route registration in
    backend/src/index.ts
不需要 Vectorize?
  1. 删除
    backend/routes/vectorize.ts
  2. wrangler.jsonc
    中移除 vectorize 绑定
  3. vite.config.ts
    的 cloudflare 插件中移除相关配置
  4. backend/src/index.ts
    中移除路由注册

Add New API Routes

添加新 API 路由

typescript
// backend/routes/my-feature.ts
import { Hono } from 'hono'

export const myFeatureRoutes = new Hono()

myFeatureRoutes.get('/hello', (c) => {
  return c.json({ message: 'Hello from my feature!' })
})

// backend/src/index.ts
import { myFeatureRoutes } from './routes/my-feature'
app.route('/api/my-feature', myFeatureRoutes)
typescript
// backend/routes/my-feature.ts
import { Hono } from 'hono'

export const myFeatureRoutes = new Hono()

myFeatureRoutes.get('/hello', (c) => {
  return c.json({ message: 'Hello from my feature!' })
})

// backend/src/index.ts
import { myFeatureRoutes } from './routes/my-feature'
app.route('/api/my-feature', myFeatureRoutes)

Switch AI Providers

切换 AI 提供商

typescript
// Change this line:
model: openai('gpt-4o'),

// To this:
model: anthropic('claude-sonnet-4-5'),

// Or this:
model: google('gemini-2.5-flash'),

// Or use Workers AI:
const workersai = createWorkersAI({ binding: c.env.AI })
model: workersai('@cf/meta/llama-3-8b-instruct'),
typescript
// 修改这一行:
model: openai('gpt-4o'),

// 改为:
model: anthropic('claude-sonnet-4-5'),

// 或者:
model: google('gemini-2.5-flash'),

// 或者使用 Workers AI:
const workersai = createWorkersAI({ binding: c.env.AI })
model: workersai('@cf/meta/llama-3-8b-instruct'),

Customize Theme

自定义主题

All theming in
src/index.css
:
css
:root {
  --background: hsl(0 0% 100%);  /* Change colors here */
  --foreground: hsl(0 0% 3.9%);
  --primary: hsl(220 90% 56%);
  /* etc */
}
所有主题配置在
src/index.css
中:
css
:root {
  --background: hsl(0 0% 100%);  /* 在此修改颜色 */
  --foreground: hsl(0 0% 3.9%);
  --primary: hsl(220 90% 56%);
  /* 其他配置 */
}

Architecture Highlights

架构亮点

Frontend-Backend Connection

前后端连接

Key Insight: The Vite plugin runs your Worker on the SAME port as Vite.
typescript
// ✅ CORRECT: Use relative URLs
fetch('/api/data')

// ❌ WRONG: Don't use absolute URLs
fetch('http://localhost:8787/api/data')
No proxy configuration needed!
核心要点:Vite 插件在和 Vite 相同端口上运行 Worker。
typescript
// ✅ 正确:使用相对路径
fetch('/api/data')

// ❌ 错误:不要使用绝对路径
fetch('http://localhost:8787/api/data')
无需代理配置!

Environment Variables

环境变量

Frontend (.env):
bash
VITE_CLERK_PUBLISHABLE_KEY=pk_test_xxx
Backend (.dev.vars):
bash
CLERK_SECRET_KEY=sk_test_xxx
OPENAI_API_KEY=sk-xxx
前端 (.env):
bash
VITE_CLERK_PUBLISHABLE_KEY=pk_test_xxx
后端 (.dev.vars):
bash
CLERK_SECRET_KEY=sk_test_xxx
OPENAI_API_KEY=sk-xxx

CORS Configuration

CORS 配置

Critical: CORS middleware must be applied BEFORE routes:
typescript
// ✅ CORRECT ORDER
app.use('/api/*', corsMiddleware)
app.post('/api/data', handler)

// ❌ WRONG - Will cause CORS errors
app.post('/api/data', handler)
app.use('/api/*', corsMiddleware)
关键:CORS 中间件必须在路由之前应用:
typescript
// ✅ 正确顺序
app.use('/api/*', corsMiddleware)
app.post('/api/data', handler)

// ❌ 错误 - 会导致 CORS 错误
app.post('/api/data', handler)
app.use('/api/*', corsMiddleware)

Auth Pattern (When Enabled)

鉴权模式(启用后)

Frontend: Check
isLoaded
before making API calls:
typescript
const { isLoaded, isSignedIn } = useSession()

useEffect(() => {
  if (!isLoaded) return  // Wait for auth
  fetch('/api/protected').then(/* ... */)
}, [isLoaded])
Backend: JWT verification middleware:
typescript
import { jwtAuthMiddleware } from './middleware/auth'

app.use('/api/protected/*', jwtAuthMiddleware)
前端:发起 API 调用前检查
isLoaded
typescript
const { isLoaded, isSignedIn } = useSession()

useEffect(() => {
  if (!isLoaded) return  // 等待鉴权加载完成
  fetch('/api/protected').then(/* ... */)
}, [isLoaded])
后端:JWT 验证中间件:
typescript
import { jwtAuthMiddleware } from './middleware/auth'

app.use('/api/protected/*', jwtAuthMiddleware)

Dependencies Included

包含的依赖

json
{
  "dependencies": {
    "react": "^19.2.0",
    "react-dom": "^19.2.0",
    "hono": "^4.10.2",
    "@cloudflare/vite-plugin": "^1.13.14",

    "ai": "^5.0.76",
    "@ai-sdk/openai": "^1.0.0",
    "@ai-sdk/anthropic": "^1.0.0",
    "@ai-sdk/google": "^1.0.0",
    "workers-ai-provider": "^2.0.0",
    "@ai-sdk/react": "^1.0.0",

    "@clerk/clerk-react": "^5.53.3",
    "@clerk/backend": "^2.19.0",

    "tailwindcss": "^4.1.14",
    "@tailwindcss/vite": "^4.1.14",
    "class-variance-authority": "^0.7.0",
    "clsx": "^2.1.1",
    "tailwind-merge": "^2.5.4",

    "zod": "^3.24.1",
    "react-hook-form": "^7.54.2",
    "@hookform/resolvers": "^3.9.1",

    "@tanstack/react-query": "^5.62.11",

    "@radix-ui/react-slot": "^1.1.1",
    "@radix-ui/react-dropdown-menu": "^2.1.4"
  },
  "devDependencies": {
    "@types/react": "^19.0.0",
    "@types/react-dom": "^19.0.0",
    "typescript": "^5.7.2",
    "vite": "^7.1.11",
    "wrangler": "^4.0.0"
  }
}
json
{
  "dependencies": {
    "react": "^19.2.0",
    "react-dom": "^19.2.0",
    "hono": "^4.10.2",
    "@cloudflare/vite-plugin": "^1.13.14",

    "ai": "^5.0.76",
    "@ai-sdk/openai": "^1.0.0",
    "@ai-sdk/anthropic": "^1.0.0",
    "@ai-sdk/google": "^1.0.0",
    "workers-ai-provider": "^2.0.0",
    "@ai-sdk/react": "^1.0.0",

    "@clerk/clerk-react": "^5.53.3",
    "@clerk/backend": "^2.19.0",

    "tailwindcss": "^4.1.14",
    "@tailwindcss/vite": "^4.1.14",
    "class-variance-authority": "^0.7.0",
    "clsx": "^2.1.1",
    "tailwind-merge": "^2.5.4",

    "zod": "^3.24.1",
    "react-hook-form": "^7.54.2",
    "@hookform/resolvers": "^3.9.1",

    "@tanstack/react-query": "^5.62.11",

    "@radix-ui/react-slot": "^1.1.1",
    "@radix-ui/react-dropdown-menu": "^2.1.4"
  },
  "devDependencies": {
    "@types/react": "^19.0.0",
    "@types/react-dom": "^19.0.0",
    "typescript": "^5.7.2",
    "vite": "^7.1.11",
    "wrangler": "^4.0.0"
  }
}

Token Efficiency

效率提升

ScenarioWithout ScaffoldWith ScaffoldSavings
Initial setup~18-22k tokens~3-5k tokens~80%
Service configuration~8-10k tokens0 tokens (done)100%
Frontend-backend connection~5-7k tokens0 tokens (done)100%
AI SDK setup~4-6k tokens0 tokens (done)100%
Auth integration~6-8k tokens~500 tokens~90%
Planning docs~3-5k tokens0 tokens (included)100%
Total~44-58k tokens~3-6k tokens~90%
Time Savings: 3-4 hours → 5-10 minutes (~95% faster)
场景不使用脚手架使用脚手架节省比例
初始配置~18-22k tokens~3-5k tokens~80%
服务配置~8-10k tokens0 tokens(已完成)100%
前后端连接~5-7k tokens0 tokens(已完成)100%
AI SDK 配置~4-6k tokens0 tokens(已完成)100%
鉴权集成~6-8k tokens~500 tokens~90%
规划文档~3-5k tokens0 tokens(已包含)100%
总计~44-58k tokens~3-6k tokens~90%
时间节省:3-4小时 → 5-10分钟(提速约95%)

Common Issues Prevented

避免的常见问题

IssueHow Scaffold Prevents It
Service binding errorsAll bindings pre-configured and tested
CORS errorsMiddleware in correct order
Auth race conditionsProper loading state patterns
Frontend-backend connectionVite plugin correctly configured
AI SDK setup confusionMultiple working examples
Missing planning docsComplete docs/ structure included
Environment variable mix-upsClear .dev.vars.example with comments
Missing migrationsmigrations/ directory with examples
Inconsistent file structureStandard, tested structure
Database type errorsTyped query helpers included
Theme configurationTailwind v4 theming pre-configured
Build errorsWorking build config (vite + wrangler)
Total Errors Prevented: 12+ common setup and integration errors
问题脚手架的规避方式
服务绑定错误所有绑定已预配置并测试
CORS 错误中间件顺序正确
鉴权竞态条件规范的加载状态模式
前后端连接问题Vite 插件已正确配置
AI SDK 配置困惑提供多套可用示例
缺失规划文档包含完整的 docs/ 结构
环境变量混淆带注释的清晰 .dev.vars.example 模板
缺失迁移文件带示例的 migrations/ 目录
文件结构不一致标准的、经过测试的结构
数据库类型错误包含类型化查询辅助函数
主题配置问题Tailwind v4 主题已预配置
构建错误可用的构建配置(vite + wrangler)
总共避免的错误:12+ 常见的配置和集成错误

When NOT to Use This Scaffold

不适用场景

  • ❌ Building a static site (no backend needed)
  • ❌ Using Next.js, Remix, or other meta-framework
  • ❌ Need SSR (use framework-specific Cloudflare adapter)
  • ❌ Building backend-only API (no frontend needed)
  • ❌ Extremely simple single-page app
For these cases: Use minimal templates or official framework starters.
  • ❌ 构建静态站点(无需后端)
  • ❌ 使用 Next.js、Remix 或其他元框架
  • ❌ 需要 SSR(使用框架专属的 Cloudflare 适配器)
  • ❌ 构建仅后端的 API(无需前端)
  • ❌ 极简单页面应用
对于以上场景:使用极简模板或官方框架启动项目。

Production Evidence

生产验证

Based on:
  • Cloudflare's official agents-starter template (AI SDK patterns)
  • cloudflare-full-stack-integration skill (tested frontend-backend patterns)
  • session-handoff-protocol skill (planning docs + SCRATCHPAD.md)
  • tailwind-v4-shadcn skill (UI component patterns)
  • Multiple production Jezweb projects
Package versions verified: 2025-10-23
Works with:
  • Cloudflare Workers (production environment)
  • Wrangler 4.0+
  • Node.js 18+
  • npm/pnpm/yarn
基于以下项目构建
  • Cloudflare 官方 agents-starter 模板(AI SDK 模式)
  • cloudflare-full-stack-integration 工具(经过测试的前后端模式)
  • session-handoff-protocol 工具(规划文档 + SCRATCHPAD.md)
  • tailwind-v4-shadcn 工具(UI 组件模式)
  • 多个 Jezweb 生产项目
包版本验证时间:2025-10-23
兼容环境
  • Cloudflare Workers(生产环境)
  • Wrangler 4.0+
  • Node.js 18+
  • npm/pnpm/yarn

Quick Reference

快速参考

Setup new project:
bash
cp -r scaffold/ my-app/
cd my-app/
npm install
创建新项目
bash
cp -r scaffold/ my-app/
cd my-app/
npm install

Follow quick-start-guide.md

按照 quick-start-guide.md 操作


**Enable auth**:
```bash
./scripts/enable-auth.sh
Enable AI chat:
bash
./scripts/enable-ai-chat.sh
Deploy:
bash
npm run build
npx wrangler deploy
Key Files:
  • wrangler.jsonc
    - Service configuration
  • vite.config.ts
    - Build configuration
  • .dev.vars.example
    - Environment variables template
  • docs/ARCHITECTURE.md
    - System design
  • SCRATCHPAD.md
    - Session handoff protocol

Remember: This scaffold is a starting point, not a constraint. Customize everything to match your needs. The value is in having a working foundation with all the integration patterns already figured out, saving hours of setup and debugging time.

**启用鉴权**:
```bash
./scripts/enable-auth.sh
启用 AI 聊天
bash
./scripts/enable-ai-chat.sh
部署
bash
npm run build
npx wrangler deploy
核心文件
  • wrangler.jsonc
    - 服务配置
  • vite.config.ts
    - 构建配置
  • .dev.vars.example
    - 环境变量模板
  • docs/ARCHITECTURE.md
    - 系统设计
  • SCRATCHPAD.md
    - 会话交接协议

注意:本脚手架是起点而非约束。你可以根据需求自定义所有内容。它的价值在于提供了一个可用的基础,所有集成模式都已验证,可节省数小时的配置和调试时间。