### Clone and Run Local Development Source: https://github.com/cloudflare/templates/blob/main/workers-for-platforms-template/README.md Clone the repository, install dependencies, and run the setup and development server for local testing. The setup script configures credentials, creates necessary resources, and generates environment variables. ```bash git clone https://github.com/cloudflare/templates.git cd templates/workers-for-platforms-template npm install npm run setup npm run dev npm test ``` -------------------------------- ### Copy Example Environment File Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/README.md Use this command to copy the example environment file to start configuring your local development environment. ```bash cp .dev.vars.example .dev.vars ``` -------------------------------- ### Install Dependencies Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/README.md Run this command in the project root to install all necessary Node.js dependencies. ```bash npm install ``` -------------------------------- ### Copy Environment Variables Example Source: https://github.com/cloudflare/templates/blob/main/saas-admin-template/README.md Copies the example environment variables file to be used for local development. Remember to fill in your API token. ```bash # Create a .dev.vars file for local development cp .dev.vars.example .dev.vars ``` -------------------------------- ### Create Astro Blog Project with C3 Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/README.md Use the create-cloudflare CLI to start a new project with the Astro blog template. Ensure you have Node.js installed. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/astro-blog-starter-template ``` -------------------------------- ### Run Development Server Source: https://github.com/cloudflare/templates/blob/main/containers-template/README.md Start the development server to preview your application locally. Access it at http://localhost:8787. ```bash npm run dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/cloudflare/templates/blob/main/containers-template/README.md Install project dependencies using npm, yarn, pnpm, or bun. ```bash npm install ``` ```bash yarn install ``` ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### Create New Cloudflare Project with Template Source: https://github.com/cloudflare/templates/blob/main/mysql-hyperdrive-template/README.md Use the create-cloudflare CLI to start a new project from the mysql-hyperdrive-template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/mysql-hyperdrive-template ``` -------------------------------- ### Start Development Server Source: https://github.com/cloudflare/templates/blob/main/CONTRIBUTING.md Run this command to start your local development server before using Playwright codegen. ```bash pnpm dev ``` -------------------------------- ### Create Text To Image App Project Source: https://github.com/cloudflare/templates/blob/main/text-to-image-template/README.md Use the create-cloudflare CLI to start a new project with the text-to-image template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/text-to-image-template ``` -------------------------------- ### Create Cloudflare Project with OpenAuth Template Source: https://github.com/cloudflare/templates/blob/main/openauth-template/README.md Use the create-cloudflare CLI to start a new project with the OpenAuth template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/openauth-template ``` -------------------------------- ### Example Custom Asset Prefixes Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md An example demonstrating how to specify custom asset prefixes in wrangler.jsonc. This configuration adds '/cf-assets/' and '/my-custom-folder/' to the list of rewritten URLs. ```json { "vars": { "ASSET_PREFIXES": "[\"/cf-assets/\", \"/my-custom-folder/\"]", } } ``` -------------------------------- ### Create Cloudflare Project with Vite React Template Source: https://github.com/cloudflare/templates/blob/main/vite-react-template/README.md Use this command to start a new project using the specified Cloudflare template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/vite-react-template ``` -------------------------------- ### D1 Database Integration Example Source: https://context7.com/cloudflare/templates/llms.txt Demonstrates how to interact with Cloudflare D1, a serverless SQLite database. Includes examples for querying all records, parameterized queries, and inserting data with return values. ```typescript // src/index.ts - D1 database example export default { async fetch(request: Request, env: Env): Promise { // Query all records const stmt = env.DB.prepare("SELECT * FROM comments LIMIT 3"); const { results } = await stmt.all(); return Response.json(results); }, } satisfies ExportedHandler; ``` ```typescript // Parameterized queries with bindings async function getCommentsByAuthor(env: Env, author: string) { const stmt = env.DB.prepare("SELECT * FROM comments WHERE author = ?1").bind(author); const { results } = await stmt.all(); return results; } ``` ```typescript // Insert with returning async function createComment(env: Env, author: string, content: string) { const stmt = env.DB.prepare( "INSERT INTO comments (author, content) VALUES (?1, ?2) RETURNING *" ).bind(author, content); const { results } = await stmt.all(); return results[0]; } ``` -------------------------------- ### D1 Database Setup Commands Source: https://context7.com/cloudflare/templates/llms.txt Commands for setting up and managing your D1 database, including creation, local migration application, and remote production migration application. ```bash # Setup D1 database npx wrangler d1 create my-database npx wrangler d1 migrations apply DB --local # Local development npx wrangler d1 migrations apply DB --remote # Production ``` -------------------------------- ### Cloudflare Workflows Example Source: https://context7.com/cloudflare/templates/llms.txt Define and manage multi-step workflows using Cloudflare Workers. This example demonstrates steps for processing data, sleeping, waiting for external events, and finalization. ```typescript // worker/workflow.ts - Workflows example import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers"; import type { WorkflowEvent } from "cloudflare:workers"; export class MyWorkflow extends WorkflowEntrypoint> { async run(event: WorkflowEvent>, step: WorkflowStep) { // Step 1: Execute a task with automatic retries const result = await step.do("process data", async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return { processed: true, timestamp: Date.now() }; }); // Step 2: Sleep for a specified duration await step.sleep("wait 2 seconds", "2 seconds"); // Step 3: Wait for external event (human approval, webhook, etc.) const approval = await step.waitForEvent("wait for approval", { type: "user-approval", timeout: "60 minutes", }); // Step 4: Final processing await step.do("finalize", async () => { console.log("Results:", { result, approval: approval.payload }); }); } } // Worker to manage workflows export default { async fetch(request: Request, env: Env): Promise { const url = new URL(request.url); // Start a new workflow if (url.pathname === "/api/workflow/start" && request.method === "POST") { const instance = await env.MY_WORKFLOW.create({ params: { timestamp: Date.now() }, }); return Response.json({ instanceId: instance.id }); } // Get workflow status if (url.pathname.startsWith("/api/workflow/status/")) { const instanceId = url.pathname.split("/").pop()!; const instance = await env.MY_WORKFLOW.get(instanceId); const status = await instance.status(); return Response.json(status); } // Send event to workflow if (url.pathname.startsWith("/api/workflow/event/") && request.method === "POST") { const instanceId = url.pathname.split("/").pop()!; const body = await request.json() as { approved: boolean }; const instance = await env.MY_WORKFLOW.get(instanceId); await instance.sendEvent({ type: "user-approval", payload: body, }); return Response.json({ success: true }); } return Response.json({ error: "Not Found" }, { status: 404 }); }, } satisfies ExportedHandler; ``` -------------------------------- ### Worker Secrets Example (.env.example) Source: https://github.com/cloudflare/templates/blob/main/CONTRIBUTING.md Example of how to define worker secrets in a .env.example file using dotenv format. This file should contain placeholder values for secrets that users will replace during deployment. ```ini COOKIE_SIGNING_KEY=my-secret # example comment: should be a real random string in production ``` -------------------------------- ### Static Path Matching Example Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Use static paths for exact prefix matching. These routes will match the specified path and any subpaths. ```json {"binding": "APP1", "path": "/docs"} // Matches /docs, /docs/, /docs/anything ``` ```json {"binding": "APP2", "path": "/dashboard"} // Matches /dashboard, /dashboard/, /dashboard/user ``` -------------------------------- ### Create Cloudflare Project with React Router Template Source: https://github.com/cloudflare/templates/blob/main/react-router-starter-template/README.md Use C3 to initialize a new project with the React Router starter template for Cloudflare Workers. Ensure you have Node.js installed. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/react-router-starter-template ``` -------------------------------- ### Proxy Public Route Example Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/README.md Demonstrates how a public route is proxied directly to the origin server without any authentication or payment checks. ```bash curl https://your-worker.dev/any-path # → Proxied directly to origin server ``` -------------------------------- ### Basic wrangler.jsonc Setup Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md This wrangler.jsonc configuration sets up basic services and defines routes using a JSON string for the ROUTES variable. It maps service bindings to specific paths. ```jsonc { "services": [ { "binding": "DOCS", "service": "docs-worker" }, { "binding": "DASH", "service": "dashboard-worker" }, ], "vars": { "ROUTES": "[{\"binding\": \"DOCS\", \"path\": \"/docs\"}, {\"binding\": \"DASH\", \"path\": \"/dashboard\"}]", }, } ``` -------------------------------- ### Development Commands Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md These bash commands are used for managing the development lifecycle of the project, including starting the local server, type checking, and deploying to Cloudflare. ```bash # Start local development server npm run dev # Type check npm run types # Deploy to Cloudflare npm run deploy ``` -------------------------------- ### Run Wrangler Source: https://github.com/cloudflare/templates/blob/main/remix-starter-template/README.md Commands to build and start the application using Wrangler, a tool for Cloudflare Workers. ```sh npm run build npm start ``` -------------------------------- ### Dynamic Parameter Matching Example Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Utilize dynamic parameters with ':name' to capture path segments. These segments can be accessed within your application. ```json {"binding": "APP1", "path": "/:tenant"} // Matches /acme, /acme/dashboard ``` ```json {"binding": "APP2", "path": "/:tenant/dashboard"} // Matches /acme/dashboard, /acme/dashboard/settings ``` -------------------------------- ### Run Docker Compose for Local Development Source: https://github.com/cloudflare/templates/blob/main/react-router-postgres-ssr-template/README.md Start the Docker container for local Hyperdrive development. This command creates a PostgreSQL container and seeds it with data from init.sql. ```bash docker-compose up -d ``` -------------------------------- ### R2 Explorer Setup Source: https://context7.com/cloudflare/templates/llms.txt Configure an R2 Explorer to provide a web-based file explorer for R2 object storage buckets. Can be set to read-only mode. ```typescript // src/index.ts - R2 Explorer import { R2Explorer } from "r2-explorer"; export default R2Explorer({ // Set to false to allow users to upload files readonly: true, // Optional: Secure with Cloudflare Access // cfAccessTeamName: "my-team-name", }); ``` -------------------------------- ### CSS URL Rewriting Example Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Demonstrates how CSS url() references to asset paths are automatically rewritten to include the mount prefix. ```css /* Before: */ background-image: url("/assets/bg.png"); /* After (when served from /docs mount): */ background-image: url("/docs/assets/bg.png"); ``` -------------------------------- ### Wrangler Configuration for Queues Source: https://github.com/cloudflare/templates/blob/main/workers-builds-notifications-template/README.md Example configuration in wrangler.jsonc specifying a queue consumer. The 'queue' name must match the actual queue created. ```jsonc { "queues": { "consumers": [ { "queue": "builds-event-subscriptions", // ← Must match your queue name ... } ] } } ``` -------------------------------- ### Local Development Setup and Testing Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/AGENTS.md Use this script to set up your local environment variables, including a JWT secret, and to run your worker locally. Test endpoints using curl. ```bash cp .dev.vars.example .dev.vars node -e "console.log('JWT_SECRET=' + require('crypto').randomBytes(32).toString('hex'))" >> .dev.vars npm run dev ``` ```bash curl http://localhost:8787/__x402/health # Should return 200 ``` ```bash curl http://localhost:8787/__x402/protected # Should return 402 ``` -------------------------------- ### Basic Vitest Setup for Worker Templates Source: https://github.com/cloudflare/templates/blob/main/AGENTS.md Sets up Vitest for testing Cloudflare Worker templates, including configuration for the Workers pool and a basic test file. ```typescript // vitest.config.ts import { defineWorkersProject } from "@cloudflare/vitest-pool-workers/config"; export default defineWorkersProject({ test: { poolOptions: { workers: { singleWorker: true, wrangler: { configPath: "./wrangler.json", }, }, }, }, }); ``` ```typescript // test/index.test.ts import { SELF } from "cloudflare:test"; import { describe, it, expect } from "vitest"; describe("Template Name", () => { it("returns 200 on homepage", async () => { const response = await SELF.fetch("https://example.com/"); expect(response.status).toBe(200); }); it("returns HTML content", async () => { const response = await SELF.fetch("https://example.com/"); const html = await response.text(); expect(html).toContain(""); }); // Add at least 3 more meaningful tests... }); ``` -------------------------------- ### HTML Favicon Rewriting Example Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Shows how favicon links are rewritten to include the mount prefix, ensuring correct asset serving even if they don't match standard asset prefixes. ```html ``` -------------------------------- ### Create Cloudflare Project with D1 Template Source: https://github.com/cloudflare/templates/blob/main/d1-template/README.md Use the 'create-cloudflare' CLI to scaffold a new project using the Worker + D1 template. Ensure you select 'no' for deployment when prompted by C3 if you intend to follow manual setup steps. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/d1-template ``` -------------------------------- ### Multi-Tenant wrangler.jsonc Setup Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md This wrangler.jsonc configuration is for a multi-tenant application. It defines a single service binding and a ROUTES variable that uses a dynamic path parameter for tenant identification. ```jsonc { "services": [{ "binding": "TENANT_APP", "service": "tenant-worker" }], "vars": { "ROUTES": "[{\"binding\": \"TENANT_APP\", \"path\": \"/:tenant/app\"}]", }, } ``` -------------------------------- ### HTML Asset URL Rewriting Example Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Demonstrates how the router rewrites HTML asset URLs to maintain correct paths when served from a specific mount prefix. This ensures assets load correctly across different microfrontends. ```html ``` -------------------------------- ### Create Cloudflare Worker Project with OpenAPI Template Source: https://github.com/cloudflare/templates/blob/main/chanfana-openapi-template/README.md Use the create-cloudflare CLI to scaffold a new project using the OpenAPI template. Select 'no' for deployment when prompted by C3 and follow the project's setup steps before deploying. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/openapi-template ``` -------------------------------- ### Example Preset for Bot Exception IDs Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/AGENTS.md A JSON configuration snippet showing an array of bot detection IDs that should be allowed free access. This is useful for excluding known bots from payment requirements. ```json "except_detection_ids": [ 120623194, // Googlebot 117479730, // BingBot 132995013, // ChatGPT-User 33564303 // Claude-User ] ``` -------------------------------- ### Static Mount Route Configuration with Preload Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md This JSON configuration defines routes for a microfrontend setup. Routes with `preload: true` will be automatically prefetched by the router in non-Chromium browsers. Dynamic parameters prevent preloading. ```json { "routes": [ { "binding": "APP1", "path": "/app1", "preload": true }, { "binding": "APP2", "path": "/app2", "preload": true }, { "binding": "APP3", "path": "/:tenant/dashboard" } // Cannot preload (dynamic parameter) ] } ``` -------------------------------- ### Create NLWeb Starter Project Source: https://github.com/cloudflare/templates/blob/main/nlweb-template/README.md Use this command with C3 to initialize a new project using the NLWeb starter template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/nlweb-template ``` -------------------------------- ### Clone LLM Chat App Template Repository Source: https://github.com/cloudflare/templates/blob/main/llm-chat-app-template/README.md Clone the repository to get started with the LLM chat application template. ```bash git clone https://github.com/cloudflare/templates.git cd templates/llm-chat-app ``` -------------------------------- ### Create Cloudflare Project with Containers Template Source: https://github.com/cloudflare/templates/blob/main/containers-template/README.md Use the C3 CLI to initialize a new project with the containers template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/containers-template ``` -------------------------------- ### Create Cloudflare Project with R2-Explorer Template Source: https://github.com/cloudflare/templates/blob/main/r2-explorer-template/README.md Use this command to initialize a new project with the R2-Explorer template using the create-cloudflare CLI. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/r2-explorer-template ``` -------------------------------- ### Install Dependencies and Configure JWT Secret Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/README.md Installs project dependencies and generates a JWT secret for local development. Ensure to update the `NETWORK` in `wrangler.jsonc` for production deployment. ```bash npm install cp .dev.vars.example .dev.vars node -e "console.log('JWT_SECRET=' + require('crypto').randomBytes(32).toString('hex'))" >> .dev.vars npm run dev ``` -------------------------------- ### Create Cloudflare Project with Template Source: https://github.com/cloudflare/templates/blob/main/to-do-list-kv-template/README.md Use the create-cloudflare CLI to scaffold a new project from the to-do list KV template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/to-do-list-kv-template ``` -------------------------------- ### Initialize PostgreSQL Database Source: https://github.com/cloudflare/templates/blob/main/react-router-postgres-ssr-template/README.md This SQL script contains the database schema and sample data. You can execute it using your database provider's SQL editor or a command-line tool like `psql`. ```sql -- This file contains all database schema and sample data ``` -------------------------------- ### Upload Template Help Source: https://github.com/cloudflare/templates/blob/main/cli/README.md Displays help information for the 'upload' command, including usage and arguments for uploading template directories to the Cloudflare Templates API. ```bash $ npx tsx src/index.ts help upload Usage: cli upload [options] [path-to-templates] upload templates to the templates API Arguments: path-to-templates path to directory containing templates (default: ".") ``` -------------------------------- ### Wrangler Development Commands Source: https://context7.com/cloudflare/templates/llms.txt Common Wrangler commands for local development, including starting the dev server and connecting to remote resources. ```bash # Development npm run dev # Start local development server npx wrangler dev # Alternative: direct wrangler command npx wrangler dev --remote # Connect to remote resources (Hyperdrive, etc.) ``` -------------------------------- ### Create Cloudflare Project with Template Source: https://github.com/cloudflare/templates/blob/main/postgres-hyperdrive-template/README.md Use the C3 CLI to create a new project from the Worker + PostgreSQL Hyperdrive template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/postgres-hyperdrive-template ``` -------------------------------- ### Docker Compose for Local Development Source: https://github.com/cloudflare/templates/blob/main/react-postgres-fullstack-template/README.md Sets up a Docker container with PostgreSQL and seeds it with initial data. Use this to run the application locally. ```yaml services: db: image: postgres:14 ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql environment: POSTGRES_DB: "books" POSTGRES_USER: "user" POSTGRES_PASSWORD: "password" volumes: postgres_data: ``` -------------------------------- ### Wildcard Route Matching Examples Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Employ wildcard characters '*' for zero or more segments and '+' for one or more segments to define flexible routes. ```json {"binding": "APP1", "path": "/api/:path*"} // Matches /api, /api/users, /api/users/123 ``` ```json {"binding": "APP2", "path": "/app/:path+"} // Matches /app/users, /app/users/123 (but NOT /app) ``` -------------------------------- ### Build and Deploy Next.js Site Source: https://github.com/cloudflare/templates/blob/main/next-starter-template/README.md Commands for building the production site, previewing it locally, and deploying to Cloudflare. Also includes a command for viewing Worker logs. ```bash npm run build ``` ```bash npm run preview ``` ```bash npm run build && npm run deploy ``` ```bash npm wrangler tail ``` -------------------------------- ### Deploy Templates Source: https://github.com/cloudflare/templates/blob/main/CLAUDE.md Commands for deploying templates, live demos, and uploading to the Cloudflare Templates API. ```bash pnpm run deploy ``` ```bash pnpm run deploy-live-demos ``` ```bash pnpm run upload ``` -------------------------------- ### Markdown Ordered List Syntax Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/src/content/blog/markdown-style-guide.md Create ordered lists by starting each line with a number followed by a period. This is useful for sequential steps or items. ```markdown 1. First item 2. Second item 3. Third item ``` -------------------------------- ### Protected Route - No Auth Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/README.md Example of requesting a protected route without any payment or authentication cookie. Expects a 402 Payment Required response. ```bash curl https://your-worker.dev/premium # → 402 Payment Required ``` -------------------------------- ### Create Cloudflare Project with Template Source: https://context7.com/cloudflare/templates/llms.txt Use the create-cloudflare CLI to scaffold a new project from a specific template. Choose from various templates like D1, LLM chat, or React Router. ```bash # Create a new project with any template npm create cloudflare@latest -- --template=cloudflare/templates/ # Examples: npm create cloudflare@latest -- --template=cloudflare/templates/d1-template npm create cloudflare@latest -- --template=cloudflare/templates/llm-chat-app-template npm create cloudflare@latest -- --template=cloudflare/templates/react-router-starter-template # Or use the interactive CLI npm create cloudflare@latest # or pnpm create cloudflare@latest # or yarn create cloudflare@latest ``` -------------------------------- ### Parameter Constraint Examples Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md Add constraints to dynamic parameters using parentheses to restrict matched values. This ensures only specific formats are accepted. ```json {"binding": "APP1", "path": "/:tenant(a|b|c)"} // Only matches /a, /b, or /c ``` ```json {"binding": "APP2", "path": "/:id(\d+)"} // Only matches numeric IDs ``` -------------------------------- ### Preview Production Build Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/README.md Locally previews the production build of your site before deploying. This ensures the deployed version matches your expectations. ```bash npm run preview ``` -------------------------------- ### Add Dashboard Content Markers in README.md Source: https://github.com/cloudflare/templates/blob/main/AGENTS.md Ensures template details display correctly in the Cloudflare Dashboard by wrapping content with start and end markers. ```markdown [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](...) ## Overview This template demonstrates... ## Getting Started ... ``` -------------------------------- ### Create Cloudflare Project with Durable Chat Template Source: https://github.com/cloudflare/templates/blob/main/durable-chat-template/README.md Use the `create-cloudflare` CLI to scaffold a new project using the durable chat template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/durable-chat-template ``` -------------------------------- ### Create Cloudflare Project with Multiplayer Globe Template Source: https://github.com/cloudflare/templates/blob/main/multiplayer-globe-template/README.md Use the create-cloudflare CLI to quickly scaffold a new project using the multiplayer globe template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/multiplayer-globe-template ``` -------------------------------- ### Upload a Preview Version to Cloudflare Source: https://github.com/cloudflare/templates/blob/main/react-router-starter-template/README.md Upload a new version of your application for preview deployment. This is useful for testing specific builds before promoting them to production. ```bash npx wrangler versions upload ``` -------------------------------- ### Run All E2E Tests Locally Source: https://github.com/cloudflare/templates/blob/main/README.md Execute all end-to-end tests for the Cloudflare Workers templates in local development mode. This mode starts development servers for each template. ```bash pnpm run test:e2e ``` -------------------------------- ### Run Development Checks Source: https://github.com/cloudflare/templates/blob/main/CLAUDE.md Execute these commands to check template quality and run tests. ```bash pnpm run check ``` ```bash pnpm run fix ``` ```bash pnpm run test ``` ```bash pnpm run test:e2e ``` ```bash pnpm run test:cli ``` -------------------------------- ### Configure Bot Exception IDs in JSONC Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/AGENTS.md Example of how to configure bot detection IDs for exceptions in x402-proxy. This allows specific bots to bypass payment requirements. ```jsonc "except_detection_ids": [ 120623194, // Googlebot 117479730 // BingBot ] ``` -------------------------------- ### Create Cloudflare Worker Project with Template Source: https://github.com/cloudflare/templates/blob/main/workers-builds-notifications-template/README.md Use the create-cloudflare CLI to scaffold a new project from this template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/workers-builds-notifications-template ``` -------------------------------- ### Build Production Site Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/README.md Compiles your Astro project into static assets for deployment. The output is placed in the ./dist/ directory. ```bash npm run build ``` -------------------------------- ### Wrangler Configuration Best Practices Source: https://github.com/cloudflare/templates/blob/main/CLAUDE.md Recommended settings for wrangler.json or wrangler.jsonc files to ensure compatibility and performance. ```json Must use `wrangler.json` or `wrangler.jsonc` format (not `.toml`) Latest compatibility date Observability and Smart Placement enabled by default Source maps enabled for development ``` -------------------------------- ### Create R2 Bucket using Wrangler Source: https://github.com/cloudflare/templates/blob/main/r2-explorer-template/README.md This command creates a new R2 bucket named 'r2-explorer-bucket' using the Wrangler CLI. Ensure you have Wrangler installed and configured. ```bash npx wrangler r2 bucket create r2-explorer-bucket ``` -------------------------------- ### Apply D1 Database Migrations Source: https://github.com/cloudflare/templates/blob/main/openauth-template/README.md Run database migrations to initialize the D1 database. This command applies migrations from the 'migrations' directory. ```bash npx wrangler d1 migrations apply --remote openauth-template-auth-db ``` -------------------------------- ### Create D1 Database for OpenAuth Source: https://github.com/cloudflare/templates/blob/main/openauth-template/README.md Create a D1 database instance named 'openauth-template-auth-db'. Remember to update the 'database_id' in wrangler.json with the ID of the created database. ```bash npx wrangler d1 create openauth-template-auth-db ``` -------------------------------- ### Basic Template Test Structure Source: https://github.com/cloudflare/templates/blob/main/README.md A fundamental example of a Playwright test for a Cloudflare Workers template. It uses the `templateUrl` fixture to navigate to the template's URL and asserts the visibility of a heading. ```typescript import { test, expect } from "./fixtures"; test.describe("My Template", () => { test("should render correctly", async ({ page, templateUrl }) => { await page.goto(templateUrl); await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible(); }); }); ``` -------------------------------- ### Bot Management Filtering Configuration Source: https://github.com/cloudflare/templates/blob/main/x402-proxy-template/README.md Configure bot management to differentiate between human and automated traffic for protected routes. This example sets a score threshold and whitelists specific bot detection IDs. ```jsonc "PROTECTED_PATTERNS": [ { "pattern": "/api/premium/*", "price": "$0.10", "description": "Premium API access", "bot_score_threshold": 30, // Lower score = more likely automated "except_detection_ids": [ 120623194, // Googlebot 132995013 // ChatGPT-User ] } ] ``` -------------------------------- ### Durable Objects: RPC and Storage Source: https://context7.com/cloudflare/templates/llms.txt Implement strongly consistent, low-latency storage with single-threaded execution for real-time collaboration and coordination. This example shows RPC method calls and basic data storage. ```typescript // src/index.ts - Durable Objects example import { DurableObject } from "cloudflare:workers"; export class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); } // RPC method callable from Workers async sayHello(): Promise { let result = this.ctx.storage.sql .exec("SELECT 'Hello, World!' as greeting") .one() as { greeting: string }; return result.greeting; } // Store and retrieve data async increment(): Promise { let count = (await this.ctx.storage.get("count")) || 0; count++; await this.ctx.storage.put("count", count); return count; } } export default { async fetch(request: Request, env: Env): Promise { // Get or create a Durable Object instance by name const id: DurableObjectId = env.MY_DURABLE_OBJECT.idFromName( new URL(request.url).pathname ); const stub = env.MY_DURABLE_OBJECT.get(id); // Call RPC method on the Durable Object const greeting = await stub.sayHello(); return new Response(greeting); }, } satisfies ExportedHandler; ``` -------------------------------- ### Create Cloudflare Next.js Project Source: https://github.com/cloudflare/templates/blob/main/next-starter-template/README.md Use the create-cloudflare CLI to quickly scaffold a new Next.js project with the specified template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/next-starter-template ``` -------------------------------- ### Playwright E2E Tests for Templates Source: https://context7.com/cloudflare/templates/llms.txt Write end-to-end tests for templates using Playwright. Requires setup with fixtures for automatic URL resolution. Use `templateUrl` to target local or live deployments. ```typescript // playwright-tests/my-template.spec.ts import { test, expect } from "./fixtures"; test.describe("My Template", () => { test("should render homepage correctly", async ({ page, templateUrl }) => { await page.goto(templateUrl); await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible(); }); test("should handle form submission", async ({ page, templateUrl }) => { await page.goto(templateUrl); await page.fill('input[name="email"]', 'test@example.com'); await page.click('button[type="submit"]'); await expect(page.getByText("Success")).toBeVisible(); }); }); ``` -------------------------------- ### Apply D1 Database Migrations Source: https://github.com/cloudflare/templates/blob/main/chanfana-openapi-template/README.md Initialize the D1 database by applying migrations. This command assumes you have a 'DB' binding configured and migrations located in the 'migrations' directory. ```bash npx wrangler d1 migrations apply DB --remote ``` -------------------------------- ### Workers AI: LLM Chat with Streaming Source: https://context7.com/cloudflare/templates/llms.txt Build AI-powered applications using Cloudflare Workers AI with support for LLMs. This example demonstrates streaming responses via Server-Sent Events for a chat interface. ```typescript // src/index.ts - LLM Chat with streaming interface ChatMessage { role: "system" | "user" | "assistant"; content: string; } const MODEL_ID = "@cf/meta/llama-3.1-8b-instruct-fp8"; const SYSTEM_PROMPT = "You are a helpful, friendly assistant."; export default { async fetch(request: Request, env: Env): Promise { if (request.method !== "POST") { return new Response("Method not allowed", { status: 405 }); } const { messages = [] } = await request.json() as { messages: ChatMessage[] }; // Add system prompt if not present if (!messages.some((msg) => msg.role === "system")) { messages.unshift({ role: "system", content: SYSTEM_PROMPT }); } // Stream response using Server-Sent Events const stream = await env.AI.run(MODEL_ID, { messages, max_tokens: 1024, stream: true, }); return new Response(stream, { headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive", }, }); }, } satisfies ExportedHandler; ``` -------------------------------- ### Basic Playwright Test Structure Source: https://github.com/cloudflare/templates/blob/main/CONTRIBUTING.md A fundamental Playwright test example in TypeScript. This snippet demonstrates how to navigate to a page and assert the visibility of an H1 element, serving as a basic smoke test for application functionality. ```typescript import { test, expect } from "@playwright/test"; test("homepage loads correctly", async ({ page }) => { await page.goto("/"); await expect(page.locator("h1")).toBeVisible(); }); ``` -------------------------------- ### Access Hyperdrive Binding in JavaScript Source: https://github.com/cloudflare/templates/blob/main/react-router-postgres-ssr-template/README.md Access the Hyperdrive binding in your Worker code to establish a database connection. This example shows how to check for the binding's existence and create a SQL client using the connection string. ```javascript if (c.env.HYPERDRIVE) { const sql = postgres(c.env.HYPERDRIVE.connectionString); // Use SQL client } ``` -------------------------------- ### Advanced wrangler.jsonc Setup with Preloading and Transitions Source: https://github.com/cloudflare/templates/blob/main/microfrontend-template/README.md This advanced wrangler.jsonc configuration sets up multiple services, including a root worker. The ROUTES variable is a JSON object enabling `smoothTransitions` and defining routes with preloading enabled for specific paths. ```jsonc { "services": [ { "binding": "APP1", "service": "app1-worker" }, { "binding": "APP2", "service": "app2-worker" }, { "binding": "ROOT", "service": "root-worker" }, ], "vars": { "ROUTES": "{\"smoothTransitions\":true, \"routes\":[{\"binding\": \"ROOT\", \"path\": \"/\"}, {\"binding\": \"APP1\", \"path\": \"/app1\", \"preload\":true}, {\"binding\": \"APP2\", \"path\": \"/app2\", \"preload\":true}]}", } } ``` -------------------------------- ### Build and Deploy to Cloudflare Source: https://github.com/cloudflare/templates/blob/main/astro-blog-starter-template/README.md Builds the production site and then deploys it to Cloudflare Workers. This command combines the build and deploy steps. ```bash npm run build && npm run deploy ```