cloudflare-worker-base
Production-tested setup for Cloudflare Workers with Hono, Vite, and Static Assets. Use when: creating new Cloudflare Workers projects, setting up Hono routing with Workers, configuring Vite plugin for Workers, adding Static Assets to Workers, deploying with Wrangler, or encountering deployment errors, routing conflicts, or HMR crashes. Prevents 6 documented issues: export syntax errors, Static Assets routing conflicts, scheduled handler errors, HMR race conditions, upload race conditions, and Service Worker format confusion. Keywords: Cloudflare Workers, CF Workers, Hono, wrangler, Vite, Static Assets, @cloudflare/vite-plugin, wrangler.jsonc, ES Module, run_worker_first, SPA fallback, API routes, serverless, edge computing, "Cannot read properties of undefined", "Static Assets 404", "A hanging Promise was canceled", "Handler does not export", deployment fails, routing not working, HMR crashes
What this skill does
# Cloudflare Worker Base Stack **Production-tested**: cloudflare-worker-base-test (https://cloudflare-worker-base-test.webfonts.workers.dev) **Last Updated**: 2025-10-20 **Status**: Production Ready ✅ --- ## 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 ### 2. Install Dependencies ```bash cd my-worker npm install [email protected] npm install -D @cloudflare/[email protected] vite@latest ``` **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 { "$schema": "node_modules/wrangler/config-schema.json", "name": "my-worker", "main": "src/index.ts", "account_id": "YOUR_ACCOUNT_ID", "compatibility_date": "2025-10-11", "observability": { "enabled": true }, "assets": { "directory": "./public/", "binding": "ASSETS", "not_found_handling": "single-page-application", "run_worker_first": ["/api/*"] } } ``` **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 import { defineConfig } from 'vite' import { cloudflare } from '@cloudflare/vite-plugin' 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 } */ import { Hono } from 'hono' // Type-safe environment bindings type Bindings = { ASSETS: Fetcher } const app = new Hono<{ Bindings: Bindings }>() /** * 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; } ``` ### Step 3: Update Package Scripts 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**: ### Issue #1: Export Syntax Error **Error**: "Cannot read properties of undefined (reading 'map')" **Source**: [honojs/hono #3955](https://github.com/honojs/hono/issues/3955) **Prevention**: Use `export default app` (NOT `{ fetch: app.fetch }`) ### Issue #2: Static Assets Routing Conflicts **Error**: API routes return `index.html` instead of JSON **Source**: [workers-sdk #8879](https://github.com/cloudflare/workers-sdk/issues/8879) **Prevention**: Add `"run_worker_first": ["/api/*"]` to wrangler.jsonc ### Issue #3: Scheduled/Cron Not Exported **Error**: "Handler does not export a scheduled() function" **Source**: [honojs/vite-plugins #275](https://github.com/honojs/vite-plugins/issues/275) **Prevention**: Use Module Worker format when needed: ```typescript export default { fetch: app.fetch, scheduled: async (event, env, ctx) => { /* ... */ } } ``` ### Issue #4: HMR Race Condition **Error**: "A hanging Promise was canceled" during development **Source**: [workers-sdk #9518](https://github.com/cloudflare/workers-sdk/issues/9518) **Prevention**: Use `@cloudflare/[email protected]` or later ### Issue #5: Static Assets Upload Race **Error**: Non-deterministic deployment failures in CI/CD **Source**: [workers-sdk #7555](https://github.com/cloudflare/workers-sdk/issues/7555) **Prevention**: Use Wrangler 4.x+ with retry logic (fixed in recent versions) ### 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", "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 - Co
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.