AI Automation
How to Generate Images with Cloudflare Workers AI in a Small Business Workflow
TL;DR: Cloudflare Workers AI lets you call hosted diffusion models (e.g., Stable Diffusion) via a simple HTTP endpoint. Create a Worker script that forwards a prompt, secure the secret token with Cloudflare Access, add rate‑limiting with fetch guards, then connect the Worker to a no‑code orchestrator such as n8n. Monitor usage with Cloudflare Analytics and set budget alerts to avoid surprise bills.
What is Cloudflare Workers AI and which models can generate images?
Cloudflare Workers AI is a serverless runtime that gives you direct access to pre‑trained large language and diffusion models without managing GPU infrastructure. The Models documentation lists several image‑generation models, including stable-diffusion-xl and stable-diffusion-v1-5. These models accept a text prompt and optional parameters (size, steps, guidance scale) and return a base64‑encoded PNG.
How to set up a Workers AI project for image generation
- Create a Cloudflare account and enable Workers.
- Navigate to the Workers dashboard and click Create a Service →
image‑gen‑worker.
- Navigate to the Workers dashboard and click Create a Service →
- Add the AI binding.
export default { async fetch(request, env) { const { prompt, width = 512, height = 512 } = await request.json(); const response = await env.AI.run( "@cf/stabilityai/stable-diffusion-xl", { prompt, width, height } ); return new Response(JSON.stringify({ image: response.output } ), { headers: { "Content-Type": "application/json" } }); } };Replace
@cf/stabilityai/stable-diffusion-xlwith the model you prefer. TheAIbinding is automatically provisioned when you enable the Workers AI preview. - Secure the endpoint.
- Enable Cloudflare Access for the route
/image‑genand require a short‑lived JWT issued by your identity provider. - Store the JWT secret in a
KVnamespace orSecretsand reference it viaenv.SECRETin the script.
- Enable Cloudflare Access for the route
- Deploy.
wrangler publishThe Worker is now reachable at
https://image-gen-worker.YOUR_ACCOUNT.workers.dev.
Adding rate limiting and cost controls
Cloudflare does not enforce per‑user quotas out of the box, so you need a lightweight guard inside the Worker.
const LIMIT = 100; // max requests per hour per token
const cache = caches.default;
async function checkRate(token) {
const key = `rate:${token}`;
const resp = await cache.match(key);
let count = resp ? parseInt(await resp.text()) : 0;
if (count >= LIMIT) return false;
await cache.put(key, new Response((count + 1).toString()), { expirationTtl: 3600 });
return true;
}
Call checkRate at the start of fetch. If the limit is exceeded, return 429 Too Many Requests. Pair this with Cloudflare’s Billing Alerts to receive an email when usage crosses a budget threshold.
Connecting the Worker to a no‑code orchestrator (n8n)
Many small teams already use n8n for workflow glue. The n8n documentation shows how to call an HTTP endpoint.
- Add an HTTP Request node.
- Method:
POST - URL:
https://image-gen-worker.YOUR_ACCOUNT.workers.dev - Headers:
{ "Authorization": "Bearer {{ $json.token }}" } - Body (JSON):
{ "prompt": "{{ $json.prompt }}", "width": 768, "height": 768 }
- Method:
- Parse the response with a Set node to extract
imageand store it in anR2bucket or send it to Slack. - Optional: add a IF node that checks
response.statusCodefor429and routes the job to a retry queue.
This pattern keeps the heavy diffusion work in Cloudflare’s edge, while the rest of the workflow stays in the familiar n8n UI.
Testing, monitoring, and iterative improvement
- Local testing: Use
wrangler devto run the Worker locally and feed sample prompts. - Observability: Enable Workers Analytics. Create a dashboard that shows request count, latency, and error rate.
- Cost awareness: Each image generation call is billed per 1,000 tokens processed. Track the
AI model usagemetric in the Cloudflare dashboard and set a monthly budget. - Quality tuning: Adjust
guidance_scaleandstepsin the request payload to balance fidelity vs. compute time.
When to consider a custom solution
If you need full control over model versioning, on‑premise data residency, or ultra‑low latency (< 50 ms) for a public‑facing UI, a self‑hosted diffusion server (e.g., Automatic1111) might be more appropriate. Cloudflare Workers AI shines for occasional or bursty image generation where operational overhead must stay minimal.
For small teams that already use Cloudflare for DNS, CDN, and Workers, adding image generation is a low‑friction way to enrich marketing assets, product mock‑ups, or internal brainstorming sessions.
If you’d like a hands‑on review of your Workers AI setup or a quick proof‑of‑concept integration with n8n, AISecAll can help you get production‑ready in days.
Want this kind of automation built for your workflow?
AISecAll designs, builds, deploys, and maintains focused AI automations for small companies and independent entrepreneurs.