### Install Miniflare using npm Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This command installs Miniflare as a development dependency for your project using npm. It ensures Miniflare is available for testing and local development environments. ```bash npm install miniflare --save-dev ``` -------------------------------- ### Update Miniflare Options Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This example illustrates how to dynamically update the configuration of an existing Miniflare instance using the `setOptions` method. It allows for changing settings like scripts, KV namespaces, and bindings without recreating the instance, followed by a reload. ```javascript const mf = new Miniflare({ script: "...", kvNamespaces: ["TEST_NAMESPACE"], bindings: { KEY: "value1" }, }); await mf.setOptions({ script: "...", kvNamespaces: ["TEST_NAMESPACE"], bindings: { KEY: "value2" }, }); ``` -------------------------------- ### Starting an HTTP Server with Miniflare Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This code snippet shows how to start a basic HTTP server using Miniflare. It configures Miniflare with a simple fetch handler and specifies a port. The `await mf.ready` line ensures the server is listening before proceeding. The primary dependency is the 'miniflare' package. ```javascript import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: "\n export default { async fetch(request, env, ctx) { return new Response(\"Hello Miniflare!\"); }) } ", port: 5000, }); await mf.ready; console.log("Listening on :5000"); ``` -------------------------------- ### Manage Queue Producers and D1 Databases Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Demonstrates how to obtain instances for Queue producers and D1 databases, which are essential for interacting with these Cloudflare services locally. ```javascript const producer = await mf.getQueueProducer("QUEUE_BINDING"); const db = await mf.getD1Database("D1_BINDING") ``` -------------------------------- ### Install Dependencies (Shell) Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-scratch.mdx Installs all project dependencies listed in `package.json`. This command is essential after cloning the repository to ensure all necessary libraries are available for the project to run. ```shell npm install ``` -------------------------------- ### Apply Options and Dispatch Events Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Demonstrates applying new options to an existing Miniflare instance, dispatching fetch and scheduled events, and accessing worker instances. ```javascript await mf.setOptions({ kvNamespaces: ["TEST_NAMESPACE2"] }); const bindings = await mf.getBindings(); const res = await mf.dispatchFetch("http://localhost:8787/", { headers: { Authorization: "Bearer ..." }, }); const text = await res.text(); const worker = await mf.getWorker(); const scheduledResult = await worker.scheduled({ cron: "30 * * * *" }); ``` -------------------------------- ### Install kv-asset-handler Package Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-worker.mdx This command installs the `@cloudflare/kv-asset-handler` package as a development dependency. This package is essential for serving static assets from your Worker. ```sh npm i -D @cloudflare/kv-asset-handler ``` -------------------------------- ### Initialize Miniflare with Basic Configuration Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Initializes Miniflare with a script, enabling modules, and setting basic compatibility options. This is a fundamental step for running a Cloudflare Worker locally. ```javascript import { Miniflare, Log, LogLevel } from "miniflare"; const mf = new Miniflare({ log: new Log(LogLevel.INFO), script: ` export default { async fetch(request, env, ctx) { return new Response("Hello Miniflare!"); } } `, scriptPath: "./index.js", modules: true, modulesRules: [ { type: "ESModule", include: ["**/*.js"], fallthrough: true }, { type: "Text", include: ["**/*.text"] }, ], compatibilityDate: "2021-11-23", compatibilityFlags: ["formdata_parser_supports_files"], upstream: "https://miniflare.dev", }); ``` -------------------------------- ### Configure Server and Site Options Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Configures the local HTTP server host and port, enables HTTPS with certificate paths, and sets up Workers Sites for serving static files from a specified directory. ```javascript host: "127.0.0.1", port: 8787, https: true, httpsKeyPath: "./key.pem", httpsCertPath: "./cert.pem", sitePath: "./site", siteInclude: ["**/*.html", "**/*.css", "**/*.js"], siteExclude: ["node_modules"], ``` -------------------------------- ### Enabling Debug Logging in Miniflare Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This example shows how to enable detailed logging in Miniflare by setting the `log` property to an instance of the `Log` class with a specified log level. `LogLevel.DEBUG` is used here to enable all debug messages. This requires importing `Miniflare`, `Log`, and `LogLevel` from 'miniflare'. ```javascript import { Miniflare, Log, LogLevel } from "miniflare"; const mf = new Miniflare({ scriptPath: "worker.js", log: new Log(LogLevel.DEBUG), // Enable debug messages }); ``` -------------------------------- ### Initialize Miniflare with ES Module Script Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Demonstrates initializing Miniflare in ES module mode and running a basic 'Hello Miniflare!' worker. It shows how to dispatch a fetch event and log the response, then dispose of the Miniflare instance. ```javascript import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: "\n export default {\n async fetch(request, env, ctx) {\n return new Response(\"Hello Miniflare!\");\n }\n }\n ", }); const res = await mf.dispatchFetch("http://localhost:8787/"); console.log(await res.text()); // Hello Miniflare! await mf.dispose(); ``` -------------------------------- ### Create New Worker Project with C3 (npm) Source: https://github.com/ceccato88/workers/blob/main/get-started/guide.mdx Uses the `npm create cloudflare@latest` command to scaffold a new Cloudflare Worker project. It takes the project name as an argument and sets up the basic files for a 'hello-world' Worker. This is the primary method for starting a new Worker project. ```sh npm create cloudflare@latest my-first-worker ``` -------------------------------- ### Bash Command Line Interface for Langchain Example Source: https://github.com/ceccato88/workers/blob/main/languages/python/packages/langchain.mdx This bash script outlines the steps to set up and run a Langchain example within a Cloudflare Workers environment. It involves cloning a repository containing worker examples, navigating into the Langchain example directory, and then starting the development server using Wrangler. ```bash git clone https://github.com/cloudflare/python-workers-examples cd 04-langchain npx wrangler@latest dev ``` -------------------------------- ### Access Specific Bindings and Caches Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Shows how to retrieve specific binding instances like KV namespaces, R2 buckets, Durable Object namespaces, and CacheStorage instances. ```javascript const TEST_NAMESPACE = await mf.getKVNamespace("TEST_NAMESPACE"); const BUCKET = await mf.getR2Bucket("BUCKET"); const caches = await mf.getCaches(); const defaultCache = caches.default; const namedCache = await caches.open("name"); const TEST_OBJECT = await mf.getDurableObjectNamespace("TEST_OBJECT"); const id = TEST_OBJECT.newUniqueId(); const storage = await mf.getDurableObjectStorage(id); ``` -------------------------------- ### Initialize Miniflare with Script from File Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This JavaScript code shows how to initialize Miniflare by specifying the path to your worker script file using the `scriptPath` option. This is an alternative to providing the script content directly as a string. ```javascript const mf = new Miniflare({ scriptPath: "worker.js", }); ``` -------------------------------- ### Configure Storage Bindings (KV, R2, Durable Objects) Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Binds various storage resources like KV namespaces, R2 buckets, and Durable Objects, with options for persisting data locally. ```javascript kvNamespaces: ["TEST_NAMESPACE"], kvPersist: "./kv-data", r2Buckets: ["BUCKET"], r2Persist: "./r2-data", durableObjects: { TEST_OBJECT: "TestObject", API_OBJECT: { className: "ApiObject", scriptName: "api" }, }, durableObjectsPersist: "./durable-objects-data", ``` -------------------------------- ### Initialize Cloudflare Worker with Wrangler Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-existing.mdx Initializes a new Cloudflare Worker project with a basic setup. This command adds or updates essential configuration files like `wrangler.jsonc`, `package.json`, `tsconfig.json`, and `src/index.ts`. It requires the Wrangler CLI to be installed. ```sh wrangler init -y ``` -------------------------------- ### Basic package.json for Vite Worker Source: https://github.com/ceccato88/workers/blob/main/vite-plugin/get-started.mdx This package.json file sets up a new Vite project for Cloudflare Workers. It includes scripts for development, building, previewing, and deploying. Ensure 'type': 'module' is present for ES module support. ```json { "name": "cloudflare-vite-get-started", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite dev", "build": "vite build", "preview": "npm run build && vite preview", "deploy": "npm run build && wrangler deploy" } } ``` -------------------------------- ### Turso CLI Version Output Source: https://github.com/ceccato88/workers/blob/main/tutorials/connect-to-turso-using-workers.mdx Example output from the `turso --version` command, showing the installed version of the Turso CLI. The version number may vary. ```text # This should output your current Turso CLI version (your installed version may be higher): turso version v0.51.0 ``` -------------------------------- ### Create Static Site Project with C3 CLI Source: https://github.com/ceccato88/workers/blob/main/static-assets/get-started.mdx Uses the `create-cloudflare-cli` (C3) tool to scaffold a new Cloudflare Worker project for a static site. This command-line tool helps in setting up the initial project structure. ```bash npm create cloudflare@latest my-static-site -- --type=static-site ``` -------------------------------- ### Hono App - Basic Routes Source: https://github.com/ceccato88/workers/blob/main/tutorials/build-a-slackbot.mdx Defines a basic Hono application with GET and POST routes for '/posts'. This serves as a foundational example for creating API endpoints. ```typescript import { Hono } from "hono"; const app = new Hono(); app.get("/posts", (c) => c.text("Posts!")); app.post("/posts", (c) => c.text("Created!", 201)); export default app; ``` -------------------------------- ### Create New Qwik Project with Cloudflare CLI Source: https://github.com/ceccato88/workers/blob/main/framework-guides/web-apps/more-web-frameworks/qwik.mdx Initializes a new Qwik project using the create-cloudflare CLI (C3). This command sets up the project structure, integrates Qwik's official setup tool, and offers immediate deployment options. Ensure create-cloudflare is installed globally. ```sh npm create cloudflare@latest my-qwik-app -- --framework=qwik ``` -------------------------------- ### Create Nuxt Project with Workers Assets Source: https://github.com/ceccato88/workers/blob/main/framework-guides/web-apps/more-web-frameworks/nuxt.mdx Uses the create-cloudflare CLI (C3) to set up a new Nuxt project and configure it for Cloudflare Workers Assets. This command initializes the project structure and Nuxt's setup tool. ```sh npx cloudflare@latest my-nuxt-app --framework=nuxt ``` -------------------------------- ### Configure Named Workers with Bindings Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx Sets up a named worker ('worker2') with various bindings, including KV namespaces, service bindings, and custom functions. This demonstrates advanced worker orchestration within Miniflare. ```javascript workers: [{ name: "worker2", kvNamespaces: { COUNTS: "counts" }, serviceBindings: { INCREMENTER: "incrementer", async CUSTOM(request) { return new Response(message); }, }, modules: true, script: `export default { async fetch(request, env, ctx) { const response = await env.CUSTOM.fetch("http://host/"); const message = await response.text(); await env.INCREMENTER.fetch("http://host/"); await env.INCREMENTER.fetch("http://host/"); await env.INCREMENTER.fetch("http://host/"); const count = await env.COUNTS.get("count"); return new Response(message + count); } }`, }] ``` -------------------------------- ### Dispose Miniflare Instance Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This command demonstrates how to properly clean up and shut down a Miniflare instance. Calling `dispose()` stops any listeners and releases resources, which is crucial for preventing memory leaks in testing scenarios. ```javascript await mf.dispose(); ``` -------------------------------- ### Configure package.json for ES Modules Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This JSON configuration snippet is added to your `package.json` file to enable Node.js to run JavaScript files in ES module mode. This is a prerequisite for using modern JavaScript features like top-level imports. ```json { "type": "module" } ``` -------------------------------- ### Basic Cloudflare Worker Entry File Source: https://github.com/ceccato88/workers/blob/main/vite-plugin/get-started.mdx This is a simple entry file for a Cloudflare Worker using Vite. It exports an object with a `fetch` method that returns a Response. The response includes the user agent, demonstrating that the code is running within the Workers runtime. ```typescript export default { fetch() { return new Response(`Running in ${navigator.userAgent}!`); }, }; ``` -------------------------------- ### Create Full-Stack Application Project with C3 CLI Source: https://github.com/ceccato88/workers/blob/main/static-assets/get-started.mdx Uses the `create-cloudflare-cli` (C3) tool to scaffold a new Cloudflare Worker project for a full-stack application. This command-line tool helps in setting up the initial project structure for dynamic applications. ```bash npm create cloudflare@latest my-dynamic-site -- --type="SSR / full-stack app" ``` -------------------------------- ### Rust Cloudflare Worker CORS Proxy Logic Source: https://github.com/ceccato88/workers/blob/main/examples/cors-header-proxy.mdx Handles incoming requests to the worker. If the request path starts with '/corsproxy/', it routes the request to an appropriate handler based on the HTTP method (OPTIONS, GET, POST, HEAD). Otherwise, it returns the demo HTML page. ```Rust let cors_headers = HashMap::from([ ("Access-Control-Allow-Origin", "*"), ("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS"), ("Access-Control-Max-Age", "86400"), ]); let api_url = "https://examples.cloudflareworkers.com/demos/demoapi"; let proxy_endpoint = "/corsproxy/"; if req.url()?.path().starts_with(proxy_endpoint) { match req.method() { Method::Options => return handle_options(req, &cors_headers), Method::Get | Method::Head | Method::Post => return handle_request(req, api_url).await, _ => return Response::error("Method Not Allowed", 405), } } raw_html_response(&demo_page) ``` -------------------------------- ### GET /proxy Source: https://github.com/ceccato88/workers/blob/main/examples/cors-header-proxy.mdx Makes a GET request to the specified API URL through the CORS proxy. ```APIDOC ## GET /proxy ### Description This endpoint fetches data from a target API URL by routing the request through a CORS proxy. This is useful for circumventing cross-origin restrictions when making requests from a browser. ### Method GET ### Endpoint `/proxy?apiurl={target_api_url}` ### Parameters #### Query Parameters - **apiurl** (string) - Required - The URL of the API endpoint you wish to request data from. ### Request Example ``` GET /proxy?apiurl=https://api.example.com/data ``` ### Response #### Success Response (200) - **(any)** - The JSON response from the target API. #### Response Example ```json { "message": "Data retrieved successfully" } ``` ``` -------------------------------- ### Aggregate GET Requests using Hono (TypeScript) Source: https://github.com/ceccato88/workers/blob/main/examples/aggregate-requests.mdx This example uses the Hono framework (TypeScript) to aggregate responses from two GET requests. It efficiently fetches and parses data from two URLs concurrently using `Promise.all`. The aggregated results are then returned as a JSON response. It requires the `hono` package. ```typescript import { Hono } from "hono"; const app = new Hono(); app.get("*", async (c) => { // someHost is set up to return JSON responses const someHost = "https://jsonplaceholder.typicode.com"; const url1 = someHost + "/todos/1"; const url2 = someHost + "/todos/2"; // Fetch both URLs concurrently const responses = await Promise.all([fetch(url1), fetch(url2)]); // Parse JSON responses concurrently const results = await Promise.all(responses.map((r) => r.json())); // Return aggregated results return c.json(results); }); export default app; ``` -------------------------------- ### Install KV Asset Handler for Workers Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-existing.mdx Installs the `@cloudflare/kv-asset-handler` package as a development dependency. This package is essential for serving static assets efficiently from a Cloudflare Worker. ```sh npm i -D @cloudflare/kv-asset-handler ``` -------------------------------- ### Configuring Cloudflare Request Context (cf) Object in Miniflare Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This example demonstrates how to disable Miniflare's default behavior of fetching the `Request#cf` object from a trusted Cloudflare endpoint by setting `cf: false`. Alternatively, a custom `cf` object can be provided via a filepath, indicated by a string path. This configuration affects how request context data is handled. ```javascript const mf = new Miniflare({ cf: false, }); ``` ```javascript const mf = new Miniflare({ cf: "cf.json", }); ``` -------------------------------- ### Initialize Hono Cloudflare Worker Project with C3 CLI Source: https://github.com/ceccato88/workers/blob/main/tutorials/build-a-slackbot.mdx This snippet demonstrates how to initialize a new Cloudflare Workers project using the C3 CLI, selecting a Hono framework starter. It outlines the interactive prompts for project setup and the necessary command to navigate into the created project directory. ```sh npm create cloudflare@latest -- --template "slack-bot" cd slack-bot ``` -------------------------------- ### Hono Worker Example (`index.ts`) Source: https://github.com/ceccato88/workers/blob/main/framework-guides/web-apps/more-web-frameworks/hono.mdx A basic Hono application setup within a Cloudflare Worker. This example demonstrates a simple API endpoint '/api' that returns a message, intended to be consumed by a frontend SPA. ```typescript import { Hono } from 'hono' const app = new Hono() app.get('/api', (c) => { return c.json({ message: 'Hello from Hono API!' }) }) export default app ``` -------------------------------- ### Preview Worker Site (Shell) Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-scratch.mdx Starts a local development server to preview the Workers Site project. This command allows developers to test changes in real-time before deploying to Cloudflare. ```shell wrangler dev ``` -------------------------------- ### Start Worker for Integration Tests (JavaScript) Source: https://github.com/ceccato88/workers/blob/main/wrangler/api.mdx The unstable_startWorker API allows you to start a server for running integration tests against your Worker. It exposes Wrangler's dev server internals for customization. This example demonstrates its usage with node:test for running a simple 'Hello world' test. ```javascript import assert from "node:assert"; import test, { after, before, describe } from "node:test"; import { unstable_startWorker } from "wrangler"; describe("worker", () => { let worker; before(async () => { worker = await unstable_startWorker({ config: "wrangler.json" }); }); test("hello world", async () => { assert.strictEqual( await (await worker.fetch("http://example.com")).text(), "Hello world", ); }); after(async () => { await worker.dispose(); }); }); ``` -------------------------------- ### Fetch to Hostname with DNS Record in Partial CNAME Setup Source: https://github.com/ceccato88/workers/blob/main/platform/known-issues.mdx In a partial CNAME DNS setup, Workers' Fetch API requires a dedicated DNS entry in Cloudflare's DNS for any hostname the Worker needs to resolve. This example illustrates the correct way to fetch a hostname that has a corresponding DNS record. ```javascript await fetch('http://server.example.com') ``` -------------------------------- ### Cloudflare Worker Deployment Output Example Source: https://github.com/ceccato88/workers/blob/main/tutorials/connect-to-turso-using-workers.mdx Shows the output after successfully deploying a Worker to Cloudflare. It includes binding information, deployment status, the published URL, and the deployment ID. ```text Your worker has access to the following bindings: - Vars: - LIBSQL_DB_URL: "your-url" ... Published worker-turso-ts (0.19 sec) https://worker-turso-ts..workers.dev Current Deployment ID: f9e6b48f-5aac-40bd-8f44-8a40be2212ff ``` -------------------------------- ### Clone Worker Sites Template (Shell) Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-scratch.mdx Clones the `worker-sites-template` starter repository to begin a new project. It uses a specific branch (`wrangler2`) for the latest Wrangler version and creates a project directory with a specified name (e.g., `my-site`). ```shell git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template my-site ``` -------------------------------- ### JavaScript: API GET with CORS Proxy Source: https://github.com/ceccato88/workers/blob/main/examples/cors-header-proxy.mdx This snippet demonstrates how to make a GET request to an API using a Cloudflare Worker as a CORS proxy. It fetches data from a specified API URL, forwards it through the proxy endpoint, and returns the JSON response. It's useful for bypassing CORS restrictions in browser-based applications. ```javascript reqs.proxy = async () => { let href = "{proxy_endpoint}?apiurl={api_url}" return fetch(window.location.origin + href).then(r => r.json()) } ``` -------------------------------- ### Authenticate and Create Turso Database Source: https://github.com/ceccato88/workers/blob/main/databases/third-party-integrations/turso.mdx Steps to authenticate with Turso using a GitHub account and create a new Turso database. Includes example commands and output. ```sh turso auth login turso db create my-db turso db shell my-db ``` -------------------------------- ### Node.js Streams: Readable and Transform Example Source: https://github.com/ceccato88/workers/blob/main/runtime-apis/nodejs/streams.mdx Demonstrates how to create a Node.js-style Readable stream from an array of chunks and a Transform stream to convert data to uppercase and append a newline. It utilizes the `pipeline` function for efficient stream processing and `text` consumer to get the final output. This example is suitable for environments supporting Node.js stream APIs. ```javascript import { Readable, Transform } from "node:stream"; import { text } from "node:stream/consumers"; import { pipeline } from "node:stream/promises"; // A Node.js-style Transform that converts data to uppercase // and appends a newline to the end of the output. class MyTransform extends Transform { constructor() { super({ encoding: "utf8" }); } _transform(chunk, _, cb) { this.push(chunk.toString().toUpperCase()); cb(); } _flush(cb) { this.push("\n"); cb(); } } export default { afterStart() { // Example of how to use the streams API }, async fetch() { const chunks = [ "hello ", "from ", "the ", "wonderful ", "world ", "of ", "node.js ", "streams!", ]; function nextChunk(readable) { readable.push(chunks.shift()); if (chunks.length === 0) readable.push(null); else queueMicrotask(() => nextChunk(readable)); } // A Node.js-style Readable that emits chunks from the // array... const readable = new Readable({ encoding: "utf8", read() { nextChunk(readable); }, }); const transform = new MyTransform(); await pipeline(readable, transform); return new Response(await text(transform)); }, }; ``` -------------------------------- ### Starting Local Development Server with Wrangler Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/migrations/from-v2.mdx This command initiates a local development server using Wrangler v3, which defaults to using Miniflare v3. It's the recommended way to start local development after migrating. ```sh npx wrangler@3 dev ``` -------------------------------- ### Aggregate GET Requests using JavaScript Source: https://github.com/ceccato88/workers/blob/main/examples/aggregate-requests.mdx This JavaScript snippet sends two concurrent GET requests to specified URLs, aggregates their JSON responses, and returns them as a single aggregated JSON response. It uses `Promise.all` for efficient parallel fetching and JSON parsing. No external dependencies are required beyond standard Fetch API. ```javascript export default { aSync fetch(request) { // someHost is set up to return JSON responses const someHost = "https://jsonplaceholder.typicode.com"; const url1 = someHost + "/todos/1"; const url2 = someHost + "/todos/2"; const responses = await Promise.all([fetch(url1), fetch(url2)]); const results = await Promise.all(responses.map((r) => r.json())); const options = { headers: { "content-type": "application/json;charset=UTF-8" }, }; return new Response(JSON.stringify(results), options); }, }; ``` -------------------------------- ### Create a basic Cloudflare Worker project Source: https://github.com/ceccato88/workers/blob/main/tutorials/send-emails-with-resend.mdx Initializes a new Cloudflare Worker project using C3, the recommended Cloudflare tooling. This command sets up a basic 'Hello World' Worker structure. ```sh npm create cloudflare@latest ``` ```sh npm create cloudflare@latest email-with-resend -- --type=hello-world --ts=false --git=true --deploy=false ``` -------------------------------- ### Aggregate GET Requests using Python Source: https://github.com/ceccato88/workers/blob/main/examples/aggregate-requests.mdx This Python snippet demonstrates aggregating responses from two concurrent GET requests. It utilizes the `asyncio` library and the `workers` SDK to fetch data from two specified URLs, parse their JSON content in parallel, and return the combined results. It requires the `workers` package and standard Python `asyncio`. ```python from workers import Response, fetch, WorkerEntrypoint import asyncio import json class Default(WorkerEntrypoint): aSync def fetch(self, request): # some_host is set up to return JSON responses some_host = "https://jsonplaceholder.typicode.com" url1 = some_host + "/todos/1" url2 = some_host + "/todos/2" responses = await asyncio.gather(fetch(url1), fetch(url2)) results = await asyncio.gather(*(r.json() for r in responses)) headers = {"content-type": "application/json;charset=UTF-8"} return Response.json(results, headers=headers) ``` -------------------------------- ### Define and Populate `example_users` Table Source: https://github.com/ceccato88/workers/blob/main/tutorials/connect-to-turso-using-workers.mdx SQL statements to execute within the Turso database shell. This code creates a table named `example_users` with an `email` column and inserts a sample email address into it. ```sql create table example_users (email text); insert into example_users values ("foo@bar.com"); ``` -------------------------------- ### Aggregate GET Requests using TypeScript Source: https://github.com/ceccato88/workers/blob/main/examples/aggregate-requests.mdx This TypeScript snippet performs the same functionality as the JavaScript version: sending two concurrent GET requests, aggregating their JSON responses, and returning a single aggregated JSON response. It leverages `Promise.all` for parallel operations and includes type safety with `ExportedHandler`. Dependencies are minimal, relying on the Fetch API. ```typescript export default { aSync fetch(request) { // someHost is set up to return JSON responses const someHost = "https://jsonplaceholder.typicode.com"; const url1 = someHost + "/todos/1"; const url2 = someHost + "/todos/2"; const responses = await Promise.all([fetch(url1), fetch(url2)]); const results = await Promise.all(responses.map((r) => r.json())); const options = { headers: { "content-type": "application/json;charset=UTF-8" }, }; return new Response(JSON.stringify(results), options); }, } satisfies ExportedHandler; ``` -------------------------------- ### Develop Worker Locally with Wrangler Source: https://github.com/ceccato88/workers/blob/main/get-started/guide.mdx Starts a local development server for a Cloudflare Worker project using the `wrangler dev` command. This command enables live previewing and testing of the Worker on `http://localhost:8787`. Wrangler handles compilation and routing for local development. The first time it's run, it may prompt for Cloudflare account login. ```sh npx wrangler dev ``` -------------------------------- ### Example Wrangler.toml Configuration Source: https://github.com/ceccato88/workers/blob/main/wrangler/migration/v1-to-v2/wrangler-legacy/configuration.mdx A sample configuration file demonstrating the usage of various keys in Wrangler. This example illustrates how to define project name, type, account and zone IDs, routes, environment variables, KV namespaces, and custom build configurations. ```toml name = "my-worker" type = "javascript" account_id = "YOUR_ACCOUNT_ID" zone_id = "YOUR_ZONE_ID" [site] bucket = "./public" [vars] API_KEY = "some-key" [build] command = "npm run build" [kv_namespaces] MY_KV = { id = "your-kv-namespace-id", binding = "MY_KV" } ``` -------------------------------- ### Create TanStack Start Project with Cloudflare Source: https://github.com/ceccato88/workers/blob/main/framework-guides/web-apps/tanstack-start.mdx Uses the create-cloudflare CLI (C3) to scaffold a new TanStack Start application. This command initializes the project and offers an option for instant deployment. ```sh npm create cloudflare@latest my-tanstack-start-app --framework=tanstack-start cd my-tanstack-start-app ``` -------------------------------- ### Basic Environment Variables Setup (.dev.vars/.env) Source: https://github.com/ceccato88/workers/blob/main/development-testing/environment-variables.mdx This snippet demonstrates the basic setup for environment variables using either a .dev.vars or .env file in the project root. It shows how to define key-value pairs for local development. ```ini API_HOST="localhost:3000" DEBUG="true" SECRET_TOKEN="my-local-secret-token" ``` -------------------------------- ### Create Cloudflare Workers Project with create-cloudflare CLI Source: https://github.com/ceccato88/workers/blob/main/tutorials/build-a-jamstack-app.mdx Uses the create-cloudflare CLI to scaffold a new Cloudflare Workers project. It takes the project name as an argument and uses the default 'Hello World' template. This is a prerequisite for starting the tutorial. ```sh npx create-cloudflare todos ``` -------------------------------- ### HTML and JavaScript for CORS Proxy Demo Source: https://github.com/ceccato88/workers/blob/main/examples/cors-header-proxy.mdx Generates an HTML page with embedded JavaScript that demonstrates API calls with and without the CORS proxy. It includes functionality to test GET requests without the proxy, GET requests with the proxy, and POST requests with the proxy and preflight handling. The script dynamically updates the page with the results or errors from these requests. ```HTML

API GET without CORS Proxy

Shows TypeError: Failed to fetch since CORS is misconfigured

Waiting

API GET with CORS Proxy

Waiting

API POST with CORS Proxy + Preflight

Waiting ``` -------------------------------- ### Dispatching Fetch, Queues, and Scheduled Events to Workers with Miniflare Source: https://github.com/ceccato88/workers/blob/main/testing/miniflare/get-started.mdx This snippet demonstrates how to use Miniflare to dispatch fetch, queues, and scheduled events to a worker. It shows setting up Miniflare with a worker script and then programmatically triggering these events. Dependencies include the 'miniflare' package. It takes no direct input but simulates worker responses to specific event types. ```javascript import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: "\n\tlet lastScheduledController;\n\tlet lastQueueBatch;\n\texport default {\n\t\tasync fetch(request, env, ctx) {\n\t\t\tconst { pathname } = new URL(request.url);\n\t\t\tif (pathname === \"/scheduled\") {\n\t\t\t return Response.json({\n\t\t\t scheduledTime: lastScheduledController?.scheduledTime,\n\t\t\t cron: lastScheduledController?.cron,\n\t\t\t });\n\t\t\t} else if (pathname === \"/queue\") {\n\t\t\t return Response.json({\n\t\t\t queue: lastQueueBatch.queue,\n\t\t\t messages: lastQueueBatch.messages.map((message) => ({\n\t\t\t id: message.id,\n\t\t\t timestamp: message.timestamp.getTime(),\n\t\t\t body: message.body,\n\t\t\t bodyType: message.body.constructor.name,\n\t\t\t })),\n\t\t\t });\n\t\t\t} else if (pathname === \"/get-url\") {\n\t\t\t return new Response(request.url);\n\t\t\t} else {\n\t\t\t return new Response(null, { status: 404 });\n\t\t\t}\n\t\t},\n\t\tasync scheduled(controller, env, ctx) {\n\t\t lastScheduledController = controller;\n\t\t if (controller.cron === \"* * * * *\") controller.noRetry();\n\t\t},\n\t\tasync queue(batch, env, ctx) {\n\t\t lastQueueBatch = batch;\n\t\t if (batch.queue === \"needy\") batch.retryAll();\n\t\t for (const message of batch.messages) {\n\t\t if (message.id === \"perfect\") message.ack();\n\t\t }\n\t\t}\n\t}", }); const res = await mf.dispatchFetch("http://localhost:8787/", { headers: { "X-Message": "Hello Miniflare!" }, }); console.log(await res.text()); // Hello Miniflare! const worker = await mf.getWorker(); const scheduledResult = await worker.scheduled({ cron: "* * * * *", }); console.log(scheduledResult); // { outcome: "ok", noRetry: true }); const queueResult = await worker.queue("needy", [ { id: "a", timestamp: new Date(1000), body: "a", attempts: 1 }, { id: "b", timestamp: new Date(2000), body: { b: 1 }, attempts: 1 }, ]); console.log(queueResult); // { outcome: "ok", retryAll: true, ackAll: false, explicitRetries: [], explicitAcks: []} ``` -------------------------------- ### Implement 103 Early Hints with Hono Source: https://github.com/ceccato88/workers/blob/main/examples/103-early-hints.mdx This Hono code snippet shows how to set up 103 Early Hints within a Hono application. It defines routes for serving the CSS file and the main HTML page. The HTML response includes a `link` header to preload the CSS, enabling early hints for faster asset loading. ```typescript import { Hono } from "hono"; const app = new Hono(); const CSS = "body { color: red; }"; const HTML = "\ \ \ Early Hints test\ \ \

Early Hints test page

\ \ "; // Serve CSS file app.get("/test.css", (c) => { return c.body(CSS, { headers: { "content-type": "text/css", }, }); }); // Serve HTML with early hints app.get("*", (c) => { return c.html(HTML, { headers: { link: \"; rel=preload; as=style\", }, }); }); export default app; ``` -------------------------------- ### Navigate to Worker Project Directory Source: https://github.com/ceccato88/workers/blob/main/get-started/guide.mdx Changes the current directory to the newly created Worker project. This is a standard shell command required before running other project-specific commands like `wrangler dev`. ```sh cd my-first-worker ``` -------------------------------- ### Clone and Develop Worker Repository Locally Source: https://github.com/ceccato88/workers/blob/main/get-started/dashboard.mdx Commands to clone a Git repository for a Cloudflare Worker, navigate to its directory, and prepare for local development. Assumes the repository is already set up with Cloudflare. ```bash git clone cd ``` -------------------------------- ### Wrangler Configuration for Cloudflare Worker Source: https://github.com/ceccato88/workers/blob/main/vite-plugin/get-started.mdx This `wrangler.toml` file configures your Cloudflare Worker. It specifies the Worker's name, the compatibility date for runtime features, and the main entry point file for your Worker code. ```toml name = "cloudflare-vite-get-started" compatibility_date = "2025-04-03" main = "./src/index.ts" ``` -------------------------------- ### Deploy Worker Site (Shell) Source: https://github.com/ceccato88/workers/blob/main/configuration/sites/start-from-scratch.mdx Deploys the Workers Site project to Cloudflare. This command bundles the Worker code and static assets, then uploads them to the Cloudflare network. ```shell npx wrangler deploy ``` -------------------------------- ### Turso Database Creation Output Source: https://github.com/ceccato88/workers/blob/main/tutorials/connect-to-turso-using-workers.mdx Example output during the creation of a Turso database, showing the progress and the chosen location. It concludes with a success message and the time taken. ```text # Example: [===> ] Creating database my-db in Los Angeles, California (US) (lax) # Once succeeded: Created database my-db in Los Angeles, California (US) (lax) in 34 seconds. ```