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

framework-guides

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

Rust Worker project structure for assets

Store custom font files in an /assets directory at the project root. Reference them in lib.rs using include_bytes!("../assets/filename.ttf") to embed the font data directly in the compiled Worker.

Rust Worker text length validation

Validate text length in a Rust Worker before processing. If text.len() > 128, replace it with a default value like 'Nope' to prevent processing excessively long input strings.

Access templates in Cloudflare dashboard

Templates can be accessed and deployed through the Cloudflare dashboard at the Workers and Pages templates section.

Templates are starting points for Workers projects

Templates are GitHub repositories designed to be a starting point for building a new Cloudflare Workers project. They can be browsed in the Cloudflare dashboard and deployed directly.

Express.js GET single member by ID example

app.get('/api/members/:id', async (req, res) => { try { const { id } = req.params; const { results } = await env.DB.prepare('SELECT * FROM members WHERE id = ?').bind(id).all(); if (results.length === 0) { return res.status(404).json({ success: false, error: 'Member not found' }); } res.json({ success: true, member: results[0] }); } catch (error) { res.status(500).json({ success: false, error: 'Failed to fetch member' }); } });

Express.js app.use(express.json()) middleware for JSON parsing

Include app.use(express.json()) as middleware to parse incoming request bodies as JSON. This must be added before defining routes that handle JSON request bodies.

Install Express with TypeScript types for Cloudflare Workers

Install Express and its TypeScript types with: npm install express @types/express or yarn add express @types/express

Express.js example with D1 database on Cloudflare Workers

import { env } from "cloudflare:workers"; import { httpServerHandler } from "cloudflare:node"; import express from "express"; const app = express(); app.use(express.json()); app.get("/", (req, res) => { res.json({ message: "Express.js running on Cloudflare Workers!" }); }); app.get('/api/members', async (req, res) => { try { const { results } = await env.DB.prepare('SELECT * FROM members ORDER BY joined_date DESC').all(); res.json({ success: true, members: results }); } catch (error) { res.status(500).json({ success: false, error: 'Failed to fetch members' }); } }); app.listen(3000); export default httpServerHandler({ port: 3000 });

Import env and httpServerHandler to integrate Express with Workers

Import env from cloudflare:workers to access bindings like D1 databases throughout your code. Import httpServerHandler from cloudflare:node to integrate Express with the Workers runtime. Export the httpServerHandler with the port number (e.g., export default httpServerHandler({ port: 3000 })) to enable your application to handle HTTP requests on Cloudflare's network.

Express.js on Cloudflare Workers requires nodejs_compat compatibility flag

To run Express.js on Cloudflare Workers, you must enable the nodejs_compat compatibility flag in your wrangler configuration file. This flag enables Node.js APIs and allows Express to run on the Workers runtime. Add "nodejs_compat" to the compatibility_flags array in wrangler.json.

Express.js PUT update member example

app.put("/api/members/:id", async (req, res) => { try { const { id } = req.params; const { name, email } = req.body; if (!name && !email) { return res.status(400).json({ success: false, error: "At least one field (name or email) is required" }); } if (email && (!email.includes("@") || !email.includes("."))) { return res.status(400).json({ success: false, error: "Invalid email format" }); } const updates: string[] = []; const values: any[] = []; if (name) { updates.push("name = ?"); values.push(name); } if (email) { updates.push("email = ?"); values.push(email); } values.push(id); const result = await env.DB.prepare(`UPDATE members SET ${updates.join(", ")} WHERE id = ?`).bind(...values).run(); if (result.meta.changes === 0) { return res.status(404).json({ success: false, error: "Member not found" }); } res.json({ success: true, message: "Member updated successfully" }); } catch (error: any) { if (error.message?.includes("UNIQUE constraint failed")) { return res.status(409).json({ success: false, error: "Email already exists" }); } res.status(500).json({ success: false, error: "Failed to update member" }); } });

Express.js DELETE member example

app.delete("/api/members/:id", async (req, res) => { try { const { id } = req.params; const result = await env.DB.prepare("DELETE FROM members WHERE id = ?").bind(id).run(); if (result.meta.changes === 0) { return res.status(404).json({ success: false, error: "Member not found" }); } res.json({ success: true, message: "Member deleted successfully" }); } catch (error) { res.status(500).json({ success: false, error: "Failed to delete member" }); } });

Express.js POST create member example

app.post("/api/members", async (req, res) => { try { const { name, email } = req.body; if (!name || !email) { return res.status(400).json({ success: false, error: "Name and email are required" }); } if (!email.includes("@") || !email.includes(".")) { return res.status(400).json({ success: false, error: "Invalid email format" }); } const joined_date = new Date().toISOString().split("T")[0]; const result = await env.DB.prepare("INSERT INTO members (name, email, joined_date) VALUES (?, ?, ?)").bind(name, email, joined_date).run(); if (result.success) { res.status(201).json({ success: true, message: "Member created successfully", id: result.meta.last_row_id }); } else { res.status(500).json({ success: false, error: "Failed to create member" }); } } catch (error: any) { if (error.message?.includes("UNIQUE constraint failed")) { return res.status(409).json({ success: false, error: "Email already exists" }); } res.status(500).json({ success: false, error: "Failed to create member" }); } });

Give your agent this brain