new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · all subjects

code-patterns

261 notes in this subject, read out of this brain and free to use. This is page 5 of 5.

Hono middleware for initializing context

Use `app.use('*', async (c, next) => { ... await next() })` in Hono to initialize middleware that runs for all routes. This can be used to set values on context via `c.set()` that are accessible in route handlers via `c.get()`.

Hono error handling

Use `app.onError((err, c) => { return c.text(err.message, 500) })` to define a global error handler in Hono that catches errors and returns appropriate responses.

Create fine-tuned OpenAI model with Worker

Use `openai.fineTuning.jobs.create({ training_file: fileId, model: "gpt-4o-mini" })` to create a fine-tuned OpenAI model. The training_file parameter should be the ID returned from uploading a file to OpenAI.

GitHub webhook signature validation using HMAC SHA-256

To validate GitHub webhook requests, use the `createHmac` function from `node:crypto` with SHA-256 algorithm and the GitHub secret token to hash the request body. GitHub sends the signature in the `x-hub-signature-256` header. Use `timingSafeEqual` from `node:crypto` to safely compare the computed signature with the one from the header. This requires the `nodejs_compat` compatibility flag in the wrangler configuration.

HTML form action attribute for Workers submission

Set an HTML form's action attribute to point to the deployed Workers URL with the submit endpoint path. Example: action="https://workers-airtable-form.cloudflare.workers.dev/submit". The form must use method="POST" to match the Worker's expected request method.

Airtable base ID and table name from API documentation

To find your Airtable base ID, navigate to the Airtable API documentation page (airtable.com/api) while logged in and select your base. The base ID appears at the top of the API documentation page. Table names are configured when setting up the Airtable base and can be customized by the user.

Airtable API record creation format

To create a new record in Airtable via its REST API, send a POST request with a JSON body containing a 'fields' object where keys are Airtable field names (case-sensitive) and values are the data to store. Field names must exactly match the column names configured in the Airtable table.

Airtable REST API authentication

Authenticate with Airtable's REST API by including an Authorization header with the format 'Bearer {token}', where the token is a Personal Access Token created in Airtable. The API endpoint format is https://api.airtable.com/v0/{BASE_ID}/{TABLE_NAME}, where TABLE_NAME must be URL-encoded using encodeURIComponent().

Hyperdrive connection string usage

Use Hyperdrive with pg Client: new Client({ connectionString: env.HYPERDRIVE.connectionString }). Hyperdrive accelerates database queries through connection pooling and request caching across global locations.

PostgreSQL products table schema example

Example CREATE TABLE statement for products: CREATE TABLE products (id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, price DECIMAL(10, 2) NOT NULL). This defines columns with id as auto-incrementing primary key, name and price as required fields.

pg Client connection using connection string

Create a pg Client instance with a connection string: new Client({ connectionString: env.DB_URL }). Call await sql.connect() to establish the connection to the PostgreSQL database.

pg Client connection using explicit parameters

Create a pg Client instance with explicit parameters: new Client({ username: env.DB_USERNAME, password: env.DB_PASSWORD, host: env.DB_HOST, port: env.DB_PORT, database: env.DB_NAME, ssl: true }). Call await sql.connect() to establish the connection.

PostgreSQL query example in Worker

Execute a query with pg client: const result = await sql.query('SELECT * FROM products'). The result object has a rows property containing the query results. Return results as JSON: new Response(JSON.stringify(result.rows), { headers: { 'Content-Type': 'application/json' } }).

PostgreSQL INSERT with parameterized query example

Insert data into PostgreSQL using parameterized queries to prevent SQL injection: await sql.query('INSERT INTO products(name, description, price) VALUES($1, $2, $3) RETURNING *', [name, description, price]). Use $1, $2, $3 as placeholders and pass values as an array to the query method.

Basic Worker export default fetch handler

A minimal Worker entry file exports a default object with a fetch method that returns a Response. Example: export default { fetch() { return new Response(`Running in ${navigator.userAgent}!`); } };

WebAssembly.instantiateStreaming not supported

Cloudflare Workers does not support WebAssembly.instantiateStreaming().

Import text files as strings

Text files (.txt) can be imported as strings. For example: import text from "./example.txt"; will make text contain the file contents as a string.

Import and instantiate WebAssembly modules

WebAssembly modules (.wasm or .wasm?module) are imported as WebAssembly.Module objects. They should be instantiated in module scope using WebAssembly.instantiate(). Example: import wasm from "./example.wasm"; const instance = await WebAssembly.instantiate(wasm); exports.exported_func() can then be called on instance.exports.

Module types automatically configured for import

Workers automatically configure the following module types to be importable: .txt (imported as string), .html (imported as string), .sql (imported as string), .bin (imported as ArrayBuffer), .wasm (imported as WebAssembly.Module), and .wasm?module (imported as WebAssembly.Module).

Worker handling non-navigation requests example

A Worker is invoked for any non-navigation request that does not match a static asset. In the example, if the request path starts with '/api/', it returns a JSON response; otherwise it returns a 404 response.

Example React SPA calling API Worker

This example shows a React component with a button that calls the API using fetch('/api/'), receives a JSON response with a name field, and updates component state. The application preserves UI state (counter) while fetching new data from the Worker.

Give your agent this brain