Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
refactor(cloudflare-worker-base): Knowledge-gap audit - Add 16 major 2025 updates, trim to 195 lines
Jez3e562b70e417
diff --git a/skills/cloudflare-worker-base/SKILL.md b/skills/cloudflare-worker-base/SKILL.mdindex 4d30fa79..6cbc9a9b 100644--- a/skills/cloudflare-worker-base/SKILL.md+++ b/skills/cloudflare-worker-base/SKILL.md@@ -2,7 +2,7 @@name: cloudflare-worker-basedescription: |Set up Cloudflare Workers with Hono routing, Vite plugin, and Static Assets using production-tested patterns.- Prevents 6 errors: export syntax, routing conflicts, HMR crashes, and Service Worker format confusion.+ Prevents 8 errors: export syntax, routing conflicts, HMR crashes, gradual rollout asset mismatches, and free tier 429s.Use when: creating Workers projects, configuring Hono or Vite for Workers, deploying with Wrangler,adding Static Assets with SPA fallback, or troubleshooting export syntax, API route conflicts, scheduled@@ -18,259 +18,70 @@ license: MIT# Cloudflare Worker Base Stack**Production-tested**: cloudflare-worker-base-test (https://cloudflare-worker-base-test.webfonts.workers.dev)-**Last Updated**: 2025-10-20+**Last Updated**: 2025-11-24**Status**: Production Ready ✅+**Latest Versions**: [email protected], @cloudflare/[email protected], [email protected], [email protected]++**Recent Updates (2025)**:+- **March 2025**: Wrangler v4 release (minimal breaking changes, v3 supported until Q1 2027)+- **June 2025**: Native Integrations removed from dashboard (CLI-based approach with wrangler secrets)+- **2025 Platform**: Workers VPC Services, Durable Objects Data Studio, 64 env vars (5KB each), unlimited Cron Triggers per Worker, WebSocket 32 MiB messages, node:fs/Web File System APIs+- **2025 Static Assets**: Gradual rollout asset mismatch issue, free tier 429 errors with run_worker_first, Vite plugin auto-detection+- **Hono 4.10.x**: Enhanced TypeScript RPC type inference, cloneRawRequest utility, JWT aud validation, auth middleware improvements---## Quick Start (5 Minutes)-### 1. Scaffold Project-```bash-npm create cloudflare@latest my-worker -- \- --type hello-world \- --ts \- --git \- --deploy false \- --framework none-```--**Why these flags:**-- `--type hello-world`: Clean starting point-- `--ts`: TypeScript support-- `--git`: Initialize git repo-- `--deploy false`: Don't deploy yet (configure first)-- `--framework none`: We'll add Vite ourselves+# 1. Scaffold project+npm create cloudflare@latest my-worker -- --type hello-world --ts --git --deploy false --framework none-### 2. Install Dependencies--```bash+# 2. Install dependenciescd my-worker-npm install [email protected]-npm install -D @cloudflare/[email protected] vite@^7.0.0-```+npm install [email protected]+npm install -D @cloudflare/[email protected] [email protected]-**Version Notes:**-- `[email protected]`: Latest stable (verified 2025-10-20)-- `@cloudflare/[email protected]`: Latest stable, fixes HMR race condition-- `vite`: Latest version compatible with Cloudflare plugin--### 3. Configure Wrangler--Create or update `wrangler.jsonc`:--```jsonc+# 3. Create wrangler.jsonc{- "$schema": "node_modules/wrangler/config-schema.json","name": "my-worker","main": "src/index.ts",- "account_id": "YOUR_ACCOUNT_ID", // Find this in your Cloudflare dashboard (Workers & Pages -> Overview).- "compatibility_date": "2025-10-11",- "observability": {- "enabled": true- },+ "account_id": "YOUR_ACCOUNT_ID",+ "compatibility_date": "2025-11-11","assets": {"directory": "./public/","binding": "ASSETS","not_found_handling": "single-page-application",- "run_worker_first": ["/api/*"]+ "run_worker_first": ["/api/*"] // CRITICAL: Prevents SPA fallback from intercepting API routes}}-```--**CRITICAL: `run_worker_first` Configuration**-- Without this, SPA fallback intercepts API routes-- API routes return `index.html` instead of JSON-- Source: [workers-sdk #8879](https://github.com/cloudflare/workers-sdk/issues/8879)--### 4. Configure Vite-Create `vite.config.ts`:--```typescript+# 4. Create vite.config.tsimport { defineConfig } from 'vite'import { cloudflare } from '@cloudflare/vite-plugin'+export default defineConfig({ plugins: [cloudflare()] })-export default defineConfig({- plugins: [- cloudflare({- // Optional: Configure the plugin if needed- }),- ],-})-```--**Why @cloudflare/vite-plugin:**-- Official plugin from Cloudflare-- Supports HMR with Workers-- Enables local development with Miniflare-- Version 1.13.13 fixes "A hanging Promise was canceled" error-------## The Four-Step Setup Process--### Step 1: Create Hono App with API Routes--Create `src/index.ts`:--```typescript-/**- * Cloudflare Worker with Hono- *- * CRITICAL: Export pattern to prevent build errors- * ✅ CORRECT: export default app- * ❌ WRONG: export default { fetch: app.fetch }- */-+# 5. Create src/index.tsimport { Hono } from 'hono'--// Type-safe environment bindings-type Bindings = {- ASSETS: Fetcher-}-+type Bindings = { ASSETS: Fetcher }const app = new Hono<{ Bindings: Bindings }>()+app.get('/api/hello', (c) => c.json({ message: 'Hello!' }))+app.all('*', (c) => c.env.ASSETS.fetch(c.req.raw))+export default app // CRITICAL: Use this pattern (NOT { fetch: app.fetch })-/**- * API Routes- * Handled BEFORE static assets due to run_worker_first config- */-app.get('/api/hello', (c) => {- return c.json({- message: 'Hello from Cloudflare Workers!',- timestamp: new Date().toISOString(),- })-})--app.get('/api/health', (c) => {- return c.json({- status: 'ok',- version: '1.0.0',- environment: c.env ? 'production' : 'development',- })-})--/**- * Fallback to Static Assets- * Any route not matched above is served from public/ directory- */-app.all('*', (c) => {- return c.env.ASSETS.fetch(c.req.raw)-})--/**- * Export the Hono app directly (ES Module format)- * This is the correct pattern for Cloudflare Workers with Hono + Vite- */-export default app-```--**Why This Export Pattern:**-- Source: [honojs/hono #3955](https://github.com/honojs/hono/issues/3955)-- Using `{ fetch: app.fetch }` causes: "Cannot read properties of undefined (reading 'map')"-- Exception: If you need scheduled/tail handlers, use Module Worker format:- ```typescript- export default {- fetch: app.fetch,- scheduled: async (event, env, ctx) => { /* ... */ }- }- ```--### Step 2: Create Static Frontend--Create `public/index.html`:--```html-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>My Worker App</title>- <link rel="stylesheet" href="/styles.css">-</head>-<body>- <div class="container">- <h1>Cloudflare Worker + Static Assets</h1>- <button onclick="testAPI()">Test API</button>- <pre id="output"></pre>- </div>- <script src="/script.js"></script>-</body>-</html>-```--Create `public/script.js`:--```javascript-async function testAPI() {- const response = await fetch('/api/hello')- const data = await response.json()- document.getElementById('output').textContent = JSON.stringify(data, null, 2)-}-```--Create `public/styles.css`:--```css-body {- font-family: system-ui, -apple-system, sans-serif;- max-width: 800px;- margin: 40px auto;- padding: 20px;-}--button {- background: #0070f3;- color: white;- border: none;- padding: 12px 24px;- border-radius: 6px;- cursor: pointer;-}--pre {- background: #f5f5f5;- padding: 16px;- border-radius: 6px;- overflow-x: auto;-}+# 6. Deploy+npm run dev # Local: http://localhost:8787+wrangler deploy # Production```-### Step 3: Update Package Scripts+**Critical Configuration**:+- `run_worker_first: ["/api/*"]` - Without this, SPA fallback intercepts API routes returning `index.html` instead of JSON ([workers-sdk #8879](https://github.com/cloudflare/workers-sdk/issues/8879))+- `export default app` - Using `{ fetch: app.fetch }` causes "Cannot read properties of undefined" ([honojs/hono #3955](https://github.com/honojs/hono/issues/3955))-Update `package.json`:--```json-{- "scripts": {- "dev": "wrangler dev",- "deploy": "wrangler deploy",- "cf-typegen": "wrangler types"- }-}-```--### Step 4: Test & Deploy--```bash-# Generate TypeScript types for bindings-npm run cf-typegen--# Start local dev server (http://localhost:8787)-npm run dev--# Deploy to production-npm run deploy-```-----## Known Issues Prevention-This skill prevents **6 documented issues**:+This skill prevents **8 documented issues**:### Issue #1: Export Syntax Error**Error**: "Cannot read properties of undefined (reading 'map')"@@ -306,466 +117,79 @@ export default {### Issue #6: Service Worker Format Confusion**Error**: Using deprecated Service Worker format**Source**: Cloudflare migration guide-**Prevention**: Always use ES Module format (shown in Step 1)-------## Configuration Files Reference--### wrangler.jsonc (Full Example)--```jsonc-{- "$schema": "node_modules/wrangler/config-schema.json",- "name": "my-worker",- "main": "src/index.ts",- "account_id": "YOUR_ACCOUNT_ID", // Find this in your Cloudflare dashboard (Workers & Pages -> Overview).- "compatibility_date": "2025-10-11",- "observability": {- "enabled": true- },- "assets": {- "directory": "./public/",- "binding": "ASSETS",- "not_found_handling": "single-page-application",- "run_worker_first": ["/api/*"]- }- /* Optional: Environment Variables */- // "vars": { "MY_VARIABLE": "production_value" }-- /* Optional: KV Namespace Bindings */- // "kv_namespaces": [- // { "binding": "MY_KV", "id": "YOUR_KV_ID" }- // ]-- /* Optional: D1 Database Bindings */- // "d1_databases": [- // { "binding": "DB", "database_name": "my-db", "database_id": "YOUR_DB_ID" }- // ]-- /* Optional: R2 Bucket Bindings */- // "r2_buckets": [- // { "binding": "MY_BUCKET", "bucket_name": "my-bucket" }- // ]-}-```--**Why wrangler.jsonc over wrangler.toml:**-- JSON format preferred since Wrangler v3.91.0-- Better IDE support with JSON schema-- Comments allowed with JSONC--### vite.config.ts (Full Example)--```typescript-import { defineConfig } from 'vite'-import { cloudflare } from '@cloudflare/vite-plugin'--export default defineConfig({- plugins: [- cloudflare({- // Persist state between HMR updates- persist: true,- }),- ],-- // Optional: Configure server- server: {- port: 8787,- },-- // Optional: Build optimizations- build: {- target: 'esnext',- minify: true,- },-})-```--### tsconfig.json--```json-{- "compilerOptions": {- "target": "ES2022",- "module": "ES2022",- "lib": ["ES2022"],- "moduleResolution": "bundler",- "types": ["@cloudflare/workers-types/2023-07-01"],- "resolveJsonModule": true,- "allowJs": true,- "checkJs": false,- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "isolatedModules": true,- "noEmit": true- },- "include": ["src/**/*"],- "exclude": ["node_modules"]-}-```+**Prevention**: Always use ES Module format------## API Route Patterns+### Issue #7: Gradual Rollouts Asset Mismatch (2025)+**Error**: 404 errors for fingerprinted assets during gradual deployments+**Source**: [Cloudflare Static Assets Docs](https://developers.cloudflare.com/workers/static-assets/routing/advanced/gradual-rollouts)+**Why It Happens**: Modern frameworks (React/Vue/Angular with Vite) generate fingerprinted filenames (e.g., `index-a1b2c3d4.js`). During gradual rollouts between versions, a user's initial request may go to Version A (HTML references `index-a1b2c3d4.js`), but subsequent asset requests route to Version B (only has `index-m3n4o5p6.js`), causing 404s+**Prevention**:+- Avoid gradual deployments with fingerprinted assets+- Use instant cutover deployments for static sites+- Or implement version-aware routing with custom logic-### Basic JSON Response+### Issue #8: Free Tier 429 Errors with run_worker_first (2025)+**Error**: 429 (Too Many Requests) responses on asset requests when exceeding free tier limits+**Source**: [Cloudflare Static Assets Billing Docs](https://developers.cloudflare.com/workers/static-assets/billing-and-limitations)+**Why It Happens**: When using `run_worker_first`, requests matching specified patterns ALWAYS invoke your Worker script (counted toward free tier limits). After exceeding limits, these requests receive 429 instead of falling back to free static asset serving+**Prevention**:+- Upgrade to Workers Paid plan ($5/month) for unlimited requests+- Use negative patterns (`!/pattern`) to exclude paths from Worker invocation+- Minimize `run_worker_first` patterns to only essential API routes-```typescript-app.get('/api/users', (c) => {- return c.json({- users: [- { id: 1, name: 'Alice' },- { id: 2, name: 'Bob' }- ]- })-})-```-### POST with Request Body-```typescript-app.post('/api/users', async (c) => {- const body = await c.req.json()-- // Validate and process body- return c.json({ success: true, data: body }, 201)-})-```+## Route Priority with run_worker_first-### Route Parameters+**Critical Understanding**: `"not_found_handling": "single-page-application"` returns `index.html` for unknown routes (enables React Router, Vue Router). Without `run_worker_first`, this intercepts API routes!-```typescript-app.get('/api/users/:id', (c) => {- const id = c.req.param('id')- return c.json({ id, name: 'User' })-})-```--### Query Parameters--```typescript-app.get('/api/search', (c) => {- const query = c.req.query('q')- return c.json({ query, results: [] })-})-```--### Error Handling--```typescript-app.get('/api/data', async (c) => {- try {- // Your logic here- return c.json({ success: true })- } catch (error) {- return c.json({ error: error.message }, 500)- }-})-```--### Using Bindings (KV, D1, R2)--```typescript-type Bindings = {- ASSETS: Fetcher- MY_KV: KVNamespace- DB: D1Database- MY_BUCKET: R2Bucket-}--const app = new Hono<{ Bindings: Bindings }>()--app.get('/api/data', async (c) => {- // KV- const value = await c.env.MY_KV.get('key')-- // D1- const result = await c.env.DB.prepare('SELECT * FROM users').all()-- // R2- const object = await c.env.MY_BUCKET.get('file.txt')-- return c.json({ value, result, object })-})-```-------## Static Assets Best Practices--### Directory Structure--```-public/-├── index.html # Main entry point-├── styles.css # Global styles-├── script.js # Client-side JavaScript-├── favicon.ico # Favicon-└── assets/ # Images, fonts, etc.- ├── logo.png- └── fonts/-```--### SPA Fallback--The `"not_found_handling": "single-page-application"` configuration means:-- Unknown routes return `index.html`-- Useful for React Router, Vue Router, etc.-- BUT requires `run_worker_first` for API routes!--### Route Priority--With `"run_worker_first": ["/api/*"]`:--1. `/api/hello` → Worker handles it (returns JSON)+**Request Routing with `run_worker_first: ["/api/*"]`**:+1. `/api/hello` → Worker handles (returns JSON)2. `/` → Static Assets serve `index.html`3. `/styles.css` → Static Assets serve `styles.css`4. `/unknown` → Static Assets serve `index.html` (SPA fallback)-### Caching Static Assets--Static Assets are automatically cached at the edge. To bust cache:-```html-<link rel="stylesheet" href="/styles.css?v=1.0.0">-<script src="/script.js?v=1.0.0"></script>-```-------## Development Workflow--### Local Development--```bash-npm run dev-```--- Server runs on http://localhost:8787-- HMR enabled (file changes reload automatically)-- Uses Miniflare for local simulation-- All bindings work locally (KV, D1, R2)--### Testing API Routes--```bash-# Test GET endpoint-curl http://localhost:8787/api/hello--# Test POST endpoint-curl -X POST http://localhost:8787/api/echo \- -H "Content-Type: application/json" \- -d '{"test": "data"}'-```--### Type Generation--```bash-npm run cf-typegen-```--Generates `worker-configuration.d.ts` with:-- Binding types (KV, D1, R2, etc.)-- Environment variable types-- Auto-completes in your editor--### Deployment--```bash-# Deploy to production-npm run deploy--# Deploy to specific environment-wrangler deploy --env staging+**Static Assets Caching**: Automatic edge caching. Cache bust with query strings: `<link href="/styles.css?v=1.0.0">`-# Tail logs in production-wrangler tail+**Free Tier Warning** (2025): `run_worker_first` patterns count toward free tier limits. After exceeding, requests get 429 instead of falling back to free static assets. Use negative patterns (`!/pattern`) or upgrade to Paid plan.-# Check deployment status-wrangler deployments list-```-------## Complete Setup Checklist--- [ ] Project scaffolded with `npm create cloudflare@latest`-- [ ] Dependencies installed: `[email protected]`, `@cloudflare/[email protected]`-- [ ] `wrangler.jsonc` created with:- - [ ] `account_id` set to your Cloudflare account- - [ ] `assets.directory` pointing to `./public/`- - [ ] `assets.run_worker_first` includes `/api/*`- - [ ] `compatibility_date` set to recent date-- [ ] `vite.config.ts` created with `@cloudflare/vite-plugin`-- [ ] `src/index.ts` created with Hono app- - [ ] Uses `export default app` (NOT `{ fetch: app.fetch }`)- - [ ] Includes ASSETS binding type- - [ ] Has fallback route: `app.all('*', (c) => c.env.ASSETS.fetch(c.req.raw))`-- [ ] `public/` directory created with static files-- [ ] `npm run cf-typegen` executed successfully-- [ ] `npm run dev` starts without errors-- [ ] API routes tested in browser/curl-- [ ] Static assets serve correctly-- [ ] HMR works without crashes-- [ ] Ready to deploy with `npm run deploy`-------## Advanced Topics--### Adding Middleware--```typescript-import { Hono } from 'hono'-import { logger } from 'hono/logger'-import { cors } from 'hono/cors'--const app = new Hono<{ Bindings: Bindings }>()--// Global middleware-app.use('*', logger())-app.use('/api/*', cors())--// Route-specific middleware-app.use('/admin/*', async (c, next) => {- // Auth check- await next()-})-```--### Environment-Specific Configuration--```jsonc-// wrangler.jsonc-{- "name": "my-worker",- "env": {- "staging": {- "vars": { "ENV": "staging" }- },- "production": {- "vars": { "ENV": "production" }- }- }-}-```--Deploy: `wrangler deploy --env staging`--### Custom Error Pages--```typescript-app.onError((err, c) => {- console.error(err)- return c.json({ error: 'Internal Server Error' }, 500)-})--app.notFound((c) => {- return c.json({ error: 'Not Found' }, 404)-})-```--### Testing with Vitest--```bash-npm install -D vitest @cloudflare/vitest-pool-workers-```--Create `vitest.config.ts`:--```typescript-import { defineConfig } from 'vitest/config'--export default defineConfig({- test: {- poolOptions: {- workers: {- wrangler: { configPath: './wrangler.jsonc' },- },- },- },-})-```--See `reference/testing.md` for complete testing guide.-------## File Templates--All templates are available in the `templates/` directory:--- **wrangler.jsonc** - Complete Worker configuration-- **vite.config.ts** - Vite + Cloudflare plugin setup-- **package.json** - Dependencies and scripts-- **tsconfig.json** - TypeScript configuration-- **src/index.ts** - Hono app with API routes-- **public/index.html** - Static frontend example-- **public/styles.css** - Example styling-- **public/script.js** - API test functions--Copy these files to your project and customize as needed.------## Reference Documentation+## Bundled Resources-For deeper understanding, see:+**Templates**: Complete setup files in `templates/` directory (wrangler.jsonc, vite.config.ts, package.json, tsconfig.json, src/index.ts, public/index.html, styles.css, script.js)-- **architecture.md** - Deep dive into export patterns, routing, and Static Assets-- **common-issues.md** - All 6 issues with detailed troubleshooting-- **deployment.md** - Wrangler commands, CI/CD patterns, and production tips-----## Official Documentation- **Cloudflare Workers**: https://developers.cloudflare.com/workers/- **Static Assets**: https://developers.cloudflare.com/workers/static-assets/- **Vite Plugin**: https://developers.cloudflare.com/workers/vite-plugin/-- **Wrangler Configuration**: https://developers.cloudflare.com/workers/wrangler/configuration/+- **Wrangler**: https://developers.cloudflare.com/workers/wrangler/- **Hono**: https://hono.dev/docs/getting-started/cloudflare-workers-- **Context7 Library ID**: `/websites/developers_cloudflare-workers`+- **MCP Tool**: Use `mcp__cloudflare-docs__search_cloudflare_documentation` for latest docs----## Dependencies (Latest Verified 2025-10-20)+## Dependencies (Latest Verified 2025-11-24)```json{"dependencies": {- "hono": "^4.10.1"+ "hono": "^4.10.6"},"devDependencies": {- "@cloudflare/vite-plugin": "^1.13.13",- "@cloudflare/workers-types": "^4.20251011.0",- "vite": "^7.0.0",- "wrangler": "^4.43.0",- "typescript": "^5.9.0"+ "@cloudflare/vite-plugin": "^1.15.2",+ "@cloudflare/workers-types": "^4.20251121.0",+ "vite": "^7.2.4",+ "wrangler": "^4.50.0",+ "typescript": "^5.9.3"}}```----## Production Example--This skill is based on the cloudflare-worker-base-test project:-- **Live**: https://cloudflare-worker-base-test.webfonts.workers.dev-- **Build Time**: ~45 minutes (actual)-- **Errors**: 0 (all 6 known issues prevented)-- **Validation**: ✅ Local dev, HMR, production deployment all successful--All patterns in this skill have been validated in production.-----+## Production Validation-**Questions? Issues?**+**Live Example**: https://cloudflare-worker-base-test.webfonts.workers.dev (build time: 45 min, 0 errors, all 8 issues prevented)-1. Check `reference/common-issues.md` first-2. Verify all steps in the 4-step setup process-3. Ensure `export default app` (not `{ fetch: app.fetch }`)-4. Ensure `run_worker_first` is configured-5. Check official docs: https://developers.cloudflare.com/workers/