### Install dependencies and start the webpack development server Source: https://blog.cloudflare.com/cloudflare-workers-as-a-serverless-rust-platform Installs project dependencies and starts the webpack development server, making the web application accessible at http://localhost:8080. ```bash $ npm start > [email protected] start /Volumes/HD2/Code/cloudflare/bobross/bob-ross-lipsum-rust/bob-ross-lorem-ipsum-rust/www > webpack-dev-server ℹ 「wds」: Project is running at http://localhost:8080/ ``` -------------------------------- ### Quick Tunnel Output Example Source: https://developers.cloudflare.com/workers/llms-full.txt This is an example of the output you will see when starting a quick tunnel, including the assigned temporary URL. ```bash Starting quick tunnel to http://localhost:8080...Your tunnel URL: https://random-words-here.trycloudflare.com ``` -------------------------------- ### Basic Miniflare Setup Source: https://developers.cloudflare.com/workers/testing/miniflare This snippet shows a basic setup for Miniflare, initializing it with a Worker script and starting it. ```javascript import { Miniflare } from 'miniflare'; const mf = new Miniflare({ script: ` export default { async fetch(request, env, ctx) { return new Response('Hello from Miniflare!'); } } ` }); // Use mf.dispatchFetch(request) to simulate requests ``` -------------------------------- ### Basic WebSocket Connection Example Source: https://developers.cloudflare.com/agents/runtime/communication/websockets Demonstrates a simple WebSocket connection setup. Ensure you have a WebSocket server running to connect to. ```javascript const socket = new WebSocket("wss://your-websocket-server.com"); socket.addEventListener("open", () => { console.log("WebSocket connection opened"); socket.send("Hello from client!"); }); socket.addEventListener("message", (event) => { console.log("Message from server: ", event.data); }); socket.addEventListener("close", () => { console.log("WebSocket connection closed"); }); socket.addEventListener("error", (error) => { console.error("WebSocket error: ", error); }); ``` -------------------------------- ### Clone and Run LangChain Example Source: https://developers.cloudflare.com/workers/llms-full.txt Clone the example repository and run the LangChain example using `uv run`. ```bash git clone https://github.com/cloudflare/python-workers-examples cd 05-langchain uv run dev ``` -------------------------------- ### Basic Voice Agent Setup Source: https://developers.cloudflare.com/agents/examples/voice-agent This snippet shows the fundamental setup for a Voice Agent, including necessary imports and basic configuration. It's a starting point for most Voice Agent applications. ```javascript import { Voice } from "@cloudflare/workers-types/voice"; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Response { const voice = new Voice(request, env, ctx); // Your Voice Agent logic here return await voice.handle(); }, }; ``` -------------------------------- ### Install PlanetScale Database Driver (bun) Source: https://developers.cloudflare.com/workers/llms-full.txt Install the @planetscale/database package using bun. ```bash bun add @planetscale/database ``` -------------------------------- ### Start Log Tailing with npm Source: https://developers.cloudflare.com/workers/llms-full.txt Use this command to initiate a live log tailing session for your Worker using npm. Ensure you have `wrangler` installed. ```bash npx wrangler tail [WORKER] ``` -------------------------------- ### Basic Python Worker Source: https://developers.cloudflare.com/workers/languages/python/examples A simple Python Worker that handles incoming requests and returns a response. This is a foundational example for getting started with Python on Workers. ```python from js import Response def main(request): return Response.new("Hello from Python!") ``` -------------------------------- ### Start Development Server Source: https://developers.cloudflare.com/pages/get-started/c3 Run this command to start the local development server and preview your site. ```bash npm run dev ``` -------------------------------- ### Create a new Worker project with pnpm Source: https://developers.cloudflare.com/workers-ai/get-started/workers-wrangler Use pnpm to create a new Worker project named 'hello-ai'. This command will prompt you to install the `create-cloudflare` package and guide you through project setup. ```bash pnpm create cloudflare@latest hello-ai ``` -------------------------------- ### Navigate and Install Dependencies Source: https://developers.cloudflare.com/pages/get-started/c3 Change into your new project directory and install the necessary dependencies. ```bash cd my-astro-site npm install ``` -------------------------------- ### Install @opennextjs/cloudflare with bun Source: https://developers.cloudflare.com/workers/llms-full.txt Install the OpenNext Cloudflare adapter using bun as the first step for manual configuration. ```bash bun add @opennextjs/cloudflare@latest ``` -------------------------------- ### Create Text-to-Image Starter Template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Use npm, yarn, or pnpm to create a new project with the Text-to-Image starter template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/text-to-image-template ``` ```bash yarn create cloudflare --template=cloudflare/templates/text-to-image-template ``` ```bash pnpm create cloudflare@latest --template=cloudflare/templates/text-to-image-template ``` -------------------------------- ### Create a new Worker project with yarn Source: https://developers.cloudflare.com/workers-ai/get-started/workers-wrangler Use yarn to create a new Worker project named 'hello-ai'. This command will prompt you to install the `create-cloudflare` package and guide you through project setup. ```bash yarn create cloudflare hello-ai ``` -------------------------------- ### Example .env File Source: https://developers.cloudflare.com/workers/wrangler/system-environment-variables Demonstrates how to set environment variables in a .env file for persistent configuration. ```dotenv API_HOST="localhost:3000" ``` -------------------------------- ### Create a new Worker project with npm Source: https://developers.cloudflare.com/workers-ai/get-started/workers-wrangler Use npm to create a new Worker project named 'hello-ai'. This command will prompt you to install the `create-cloudflare` package and guide you through project setup. ```bash npm create cloudflare@latest -- hello-ai ``` -------------------------------- ### Rust Worker Router Setup with KV Access Source: https://developers.cloudflare.com/workers/tutorials/workers-kv-from-rust Set up a Rust Worker router to handle incoming requests. This example defines a struct for country data and initializes routes for POST and GET requests, with access to the 'cities' KV namespace. ```rust use serde::{Deserialize, Serialize}; use worker::* #[event(fetch)] async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { let router = Router::new(); #[derive(Serialize, Deserialize, Debug)] struct Country { city: String, } router // TODO: .post_async("/:country", |_, _| async move { Response::empty() }) // TODO: .get_async("/:country", |_, _| async move { Response::empty() }) .run(req, env) .await } ``` -------------------------------- ### Navigate to project directory Source: https://developers.cloudflare.com/d1/tutorials/build-a-comments-api Change into the newly created project directory. ```bash cd d1-comments-api ``` -------------------------------- ### Example: Using CLOUDFLARE_ENV Source: https://developers.cloudflare.com/workers/wrangler/system-environment-variables Shows a simple example of checking the CLOUDFLARE_ENV variable to determine the deployment environment. ```javascript addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { let message = "Hello World!" if (process.env.CLOUDFLARE_ENV === "production") { message = "Welcome to Production!" } return new Response(message) } ``` -------------------------------- ### Get Cloud Integration Setup Config Source: https://developers.cloudflare.com/api/resources/workers/subresources/routes/methods/list Retrieves the initial setup configuration for a cloud integration. ```APIDOC ## GET /api/resources/magic_cloud_networking/subresources/cloud_integrations/methods/initial_setup ### Description Gets the initial setup configuration for a cloud integration. ### Method GET ### Endpoint /api/resources/magic_cloud_networking/subresources/cloud_integrations/methods/initial_setup ``` -------------------------------- ### Create saas-admin-template with npm Source: https://developers.cloudflare.com/workers/llms-full.txt Use this command to initialize a new project with the saas-admin-template using npm. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/saas-admin-template ``` -------------------------------- ### Server-side Token Verification (Node.js Example) Source: https://developers.cloudflare.com/turnstile This Node.js example demonstrates how to verify the Turnstile token received from the client using the Cloudflare API. Ensure you have the 'axios' package installed (`npm install axios`). ```javascript const express = require('express'); const axios = require('axios'); const app = express(); app.use(express.json()); const CLOUDFLARE_SECRET_KEY = 'YOUR_SECRET_KEY'; // Get this from Cloudflare dashboard const CLOUDFLARE_API_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; app.post('/verify-turnstile', async (req, res) => { const { token } = req.body; if (!token) { return res.status(400).json({ success: false, message: 'Token is required.' }); } try { const response = await axios.post(CLOUDFLARE_API_URL, null, { params: { secret: CLOUDFLARE_SECRET_KEY, response: token } }); if (response.data.success) { // Token is valid res.json({ success: true, message: 'Verification successful.' }); } else { // Token is invalid res.status(400).json({ success: false, message: 'Invalid token.' }); } } catch (error) { console.error('Error verifying Turnstile token:', error.response ? error.response.data : error.message); res.status(500).json({ success: false, message: 'An error occurred during verification.' }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` -------------------------------- ### Install PlanetScale Database Driver (yarn) Source: https://developers.cloudflare.com/workers/llms-full.txt Install the @planetscale/database package using yarn. ```bash yarn add @planetscale/database ``` -------------------------------- ### Navigate to Project Directory Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/sveltekit Change into the newly created SvelteKit project directory. ```bash cd my-svelte-app ``` -------------------------------- ### Create SaaS Admin Starter Template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Use npm, yarn, or pnpm to create a new project with the SaaS Admin starter template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/saas-admin-template ``` ```bash yarn create cloudflare --template=cloudflare/templates/saas-admin-template ``` ```bash pnpm create cloudflare@latest --template=cloudflare/templates/saas-admin-template ``` -------------------------------- ### Python Worker Example Source: https://developers.cloudflare.com/workers/languages/python A basic example of a Python Worker that responds to requests. This requires Pyodide to be installed and configured. ```python from pyodide.http import pyfetch def handler(request): return new Response("Hello from Python!") ``` -------------------------------- ### Example Workers KV Get Source: https://developers.cloudflare.com/workers/databases/connecting-to-databases Retrieve data from Workers KV. This snippet demonstrates how to get a value by its key. ```javascript export async function onRequest(context) { const { request, env } = context; const url = new URL(request.url); const key = url.searchParams.get('key'); if (!key) { return new Response('Please provide a ?key query.', { status: 400 }); } const value = await env.YOUR_KV_NAMESPACE.get(key); if (value === null) { return new Response(`Key "${key}" not found.`, { status: 404 }); } return new Response(`Value for key "${key}": ${value}`); } ``` -------------------------------- ### Python Early Hints Example Source: https://developers.cloudflare.com/workers/llms-full.txt Serve raw HTML with Early Hints for a CSS file using Python. This example demonstrates returning Link headers to preload a stylesheet. ```python import refrom workers import Response, WorkerEntrypoint CSS = "body { color: red; }" HTML = """ Early Hints test

Early Hints test page

""" class Default(WorkerEntrypoint): async def fetch(self, request): if re.search("test.css", request.url): headers = {"content-type": "text/css"} return Response(CSS, headers=headers) else: headers = {"content-type": "text/html","link": "; rel=preload; as=style"} return Response(HTML, headers=headers) ``` -------------------------------- ### Create Remix Starter Template with npm Source: https://developers.cloudflare.com/workers/llms-full.txt Use this command to scaffold a new project using the Remix Starter template with npm. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/remix-starter-template ``` -------------------------------- ### Install Prisma CLI (bun) Source: https://developers.cloudflare.com/workers/llms-full.txt Installs the Prisma CLI as a development dependency using bun. ```bash bun add -d prisma ``` -------------------------------- ### Install Cloudflare Pulumi Package (Go) Source: https://developers.cloudflare.com/pulumi/tutorial/hello-world Installs the Cloudflare Pulumi package for Go projects using the go get command. ```bash go get github.com/pulumi/pulumi-cloudflare/sdk/v3/go/cloudflare go: downloading github.com/pulumi/pulumi-cloudflare ... ``` -------------------------------- ### Example of Gradual Deployment Configuration Source: https://developers.cloudflare.com/workers/configuration/versions-and-deployments/gradual-deployments This example shows how to configure a gradual deployment using the Cloudflare API. It sets the percentage of traffic that should be directed to the new version. ```bash curl -X PUT "https://api.cloudflare.com/client/v4/zones/:zone_identifier/workers/deployments/:service_identifier" \ --header "Authorization: Bearer " \ --header "Content-Type: application/json" \ --data '{ "percentage": 50 }' ``` -------------------------------- ### Implement read operations (GET) Source: https://developers.cloudflare.com/workers/tutorials/deploy-an-express-app Implement GET routes to fetch data from the D1 database. This example shows fetching all items. ```typescript app.get("/items", async (req, res) => { const { results } = await env.DB.prepare("SELECT * FROM items").all(); res.json(results); }); app.get("/items/:id", async (req, res) => { const id = req.params.id; const { results } = await env.DB.prepare("SELECT * FROM items WHERE id = ?").bind(id).all(); res.json(results[0]); }); ``` -------------------------------- ### Output of Turso CLI Version Check Source: https://developers.cloudflare.com/workers/tutorials/connect-to-turso-using-workers This is an example output showing the installed Turso CLI version. Your installed version may differ. ```text turso version v0.51.0 ``` -------------------------------- ### Running Migrations with Miniflare Source: https://developers.cloudflare.com/workers/testing/miniflare/migrations This example demonstrates how to configure Miniflare to run database migrations. It shows the necessary Miniflare options to specify the migration directory and the database client. ```bash npx miniflare --wrangler-config wrangler.toml --modules --port 8787 --kv-persist=./kv-data --d1-migrations=./migrations --d1-local=./d1-data ``` -------------------------------- ### KV GET Operation (TypeScript SDK) Source: https://developers.cloudflare.com/kv Example of using the Cloudflare TypeScript SDK to get a value for a given key from a KV namespace. ```typescript const value = await client.kv.namespaces.values.get('', 'KEY', { account_id: '', }); ``` -------------------------------- ### JavaScript Early Hints Example Source: https://developers.cloudflare.com/workers/llms-full.txt Serve raw HTML with Early Hints for a CSS file. This example demonstrates how to return Link headers to preload a stylesheet. ```javascript const CSS = "body { color: red; }";const HTML = " Early Hints test

Early Hints test page

"; export default { async fetch(req) { // If request is for test.css, serve the raw CSS if (/test\.css$/.test(req.url)) { return new Response(CSS, { headers: { "content-type": "text/css", }, }); } else { // Serve raw HTML using Early Hints for the CSS file return new Response(HTML, { headers: { "content-type": "text/html", link: "; rel=preload; as=style", }, }); } }, }; ``` -------------------------------- ### Install PlanetScale Database Driver (pnpm) Source: https://developers.cloudflare.com/workers/llms-full.txt Install the @planetscale/database package using pnpm. ```bash pnpm add @planetscale/database ``` -------------------------------- ### Basic React Router Setup Source: https://developers.cloudflare.com/workers/framework-guides/web-apps/react-router Demonstrates a minimal setup for React Router within a React application. ```jsx import { BrowserRouter, Routes, Route } from 'react-router-dom'; function App() { return ( } /> } /> ); } function Home() { return

Home

; } function About() { return

About

; } export default App; ``` -------------------------------- ### Get All Members Response Source: https://developers.cloudflare.com/workers/llms-full.txt Example JSON response when retrieving all members. ```json { "success": true, "members": [ { "id": 1, "name": "Alice Johnson", "email": "alice@example.com", "joined_date": "2024-01-15" }, { "id": 2, "name": "Bob Smith", "email": "bob@example.com", "joined_date": "2024-02-20" }, { "id": 3, "name": "Carol Williams", "email": "carol@example.com", "joined_date": "2024-03-10" } ] } ``` -------------------------------- ### Client SDK Integration Example Source: https://developers.cloudflare.com/agents/examples/chat-agent Illustrates how to integrate the Cloudflare Agents client SDK into a frontend application to enable chat functionality. This example focuses on the client-side setup. ```javascript import { ChatAgent } from "@cloudflare/agents/chat"; // Initialize the chat agent const agent = new ChatAgent("/autonomous-chat"); // Function to send a message and display the response async function sendMessage() { const userInput = document.getElementById("userInput") as HTMLInputElement; const message = userInput.value; if (!message) return; // Display user message displayMessage("User", message); userInput.value = ""; // Send message to the agent and display response const response = await agent.sendMessage(message); displayMessage("Agent", response.content); } function displayMessage(sender: string, content: string) { const chatBox = document.getElementById("chatBox") as HTMLElement; const messageElement = document.createElement("p"); messageElement.textContent = `${sender}: ${content}`; chatBox.appendChild(messageElement); } // Add event listener for sending messages (e.g., on button click or Enter key) // document.getElementById("sendButton").addEventListener("click", sendMessage); ``` -------------------------------- ### Create and Run Cloudflare Agents Starter Source: https://developers.cloudflare.com/agents Use these commands to quickly set up and run a Cloudflare agent starter project. No API keys are required as it defaults to Workers AI. ```bash npx create-cloudflare@latest --template cloudflare/agents-starter cd agents-starter && npm install npm run dev ``` -------------------------------- ### Install Workers Vitest Integration Source: https://developers.cloudflare.com/workers/llms-full.txt Uninstall the old Miniflare environment and install the new Vitest pool for Workers. This setup runs tests within the workerd runtime. ```bash npm uninstall vitest-environment-miniflarenpm install --save-dev vitest@^4.1.0npm install --save-dev @cloudflare/vitest-pool-workers ``` -------------------------------- ### Environment-Specific Configuration Source: https://developers.cloudflare.com/workers/configuration/versions-and-deployments This example shows how to configure different settings for different environments (e.g., production, staging). ```toml [env.production] route = "https://api.example.com/*" ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://developers.cloudflare.com/pulumi/tutorial/hello-world Initialize a new directory for your Pulumi project and navigate into it. ```bash mkdir serverless-cloudflare cd serverless-cloudflare ``` -------------------------------- ### Example: Get a remote secret Source: https://developers.cloudflare.com/workers/llms-full.txt This example demonstrates how to retrieve a remote secret using its store ID and secret ID. The output shows the retrieved secret details. ```bash npx wrangler secrets-store secret get 8f7a1cdced6342c18d223ece462fd88d --secret-id 13bc7498c6374a4e9d13be091c3c65f1 --remote ``` ```text 🔐 Getting secret... (ID: 13bc7498c6374a4e9d13be091c3c65f1)✓ Select an account: › My account| Name | ID | StoreID | Comment | Scopes | Status | Created | Modified ||-----------------------------|-------------------------------------|-------------------------------------|---------|---------|---------|------------------------|------------------------|| ServiceA_key-1 | 13bc7498c6374a4e9d13be091c3c65f1 | 8f7a1cdced6342c18d223ece462fd88d | | workers | active | 4/9/2025, 10:06:01 PM | 4/15/2025, 09:13:05 AM | ``` -------------------------------- ### Proxy GET requests to example.com in Python Source: https://developers.cloudflare.com/workers/llms-full.txt Implement a Python Worker that forwards GET requests to example.com. This example uses the `workers` library and defines a `MethodNotAllowed` helper function. ```python from workers import WorkerEntrypoint, Response, fetch class Default(WorkerEntrypoint): def fetch(self, request): def method_not_allowed(request): msg = f'Method {request.method} not allowed.' headers = {"Allow": "GET"} return Response(msg, headers=headers, status=405) # Only GET requests work with this proxy. if request.method != "GET": return method_not_allowed(request) return fetch("https://example.com") ``` -------------------------------- ### Create Remix Starter Template Source: https://developers.cloudflare.com/workers/get-started/quickstarts Use npm, yarn, or pnpm to create a new project with the Remix starter template. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/remix-starter-template ``` ```bash yarn create cloudflare --template=cloudflare/templates/remix-starter-template ``` ```bash pnpm create cloudflare@latest --template=cloudflare/templates/remix-starter-template ``` -------------------------------- ### Install Miniflare v3 with bun Source: https://developers.cloudflare.com/workers/llms-full.txt Install the latest version of Miniflare v3 as a development dependency using bun. ```bash bun add -d miniflare@latest ``` -------------------------------- ### Basic OpenTelemetry Exporter Setup Source: https://developers.cloudflare.com/workers/observability/exporting-opentelemetry-data This snippet shows a basic setup for exporting OpenTelemetry data using a generic exporter. Ensure you have the necessary OpenTelemetry SDK and exporter packages installed. ```javascript import { trace, metrics, context, propagation } from '@opentelemetry/api'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { OTLPMetricExporter } from '@opentelemetry/exporter-metric-otlp-http'; import { Resource } from '@opentelemetry/resources'; import { SDK, Span, TraceState } from '@opentelemetry/sdk-trace-base'; import { MeterProvider } from '@opentelemetry/sdk-metrics'; import { SimpleSpanProcessor, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; // Configure trace exporter const traceExporter = new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces', }); // Configure metric exporter const metricExporter = new OTLPMetricExporter({ url: 'http://localhost:4318/v1/metrics', }); // Configure resource const resource = new Resource({ attributes: { service: { name: 'my-worker', }, }, }); // Initialize trace provider const traceProvider = new SDK({ resource: resource, spanProcessor: new BatchSpanProcessor(traceExporter), }); traceProvider.register({ contextManager: new context.NoopContextManager(), propagator: propagation.NoopPropagator.getInstance(), }); // Initialize meter provider const meterProvider = new MeterProvider({ resource: resource, }); meterProvider.addMetricReader(metricExporter); // Get tracers and meters const tracer = trace.getTracer('my-worker-tracer'); const meter = meterProvider.getMeter('my-worker-meter'); // Example usage async function handler(request) { const span = tracer.startSpan('my-worker-request'); span.setAttribute('http.method', request.method); // ... your worker logic ... span.end(); return new Response('Hello from Worker!'); } export default { fetch: handler, }; ``` -------------------------------- ### Start Development Server Source: https://developers.cloudflare.com/agents/examples/slack-agent Run this command in your terminal to start the development server for your agent. ```bash npm run dev ``` -------------------------------- ### Initialize Git Repository Source: https://developers.cloudflare.com/pages/tutorials/forms These commands set up a new local directory, initialize it as a Git repository, and link it to a remote GitHub repository. This is a standard starting point for new projects. ```bash # create new directory mkdir new-project # enter new directory cd new-project # initialize git git init # attach remotegit remote add origin git@github.com:/.git # change default branch name git branch -M main ``` -------------------------------- ### Get Information About a Specific AI Model Source: https://developers.cloudflare.com/workers-ai/configuration/bindings This example demonstrates how to get detailed information about a specific AI model, such as its capabilities and input/output schema. Replace `MODEL_ID` with the actual ID of the model you are interested in. ```bash wrangler ai inspect "@cf/meta/llama-2-7b-chat-fp16" ```