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

  1. Create a Cloudflare account and enable Workers.
    • Navigate to the Workers dashboard and click Create a Serviceimage‑gen‑worker.
  2. 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-xl with the model you prefer. The AI binding is automatically provisioned when you enable the Workers AI preview.

  3. Secure the endpoint.
    • Enable Cloudflare Access for the route /image‑gen and require a short‑lived JWT issued by your identity provider.
    • Store the JWT secret in a KV namespace or Secrets and reference it via env.SECRET in the script.
  4. Deploy.
    wrangler publish

    The 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.

  1. 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 }
  2. Parse the response with a Set node to extract image and store it in an R2 bucket or send it to Slack.
  3. Optional: add a IF node that checks response.statusCode for 429 and 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

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.

Book a call Discuss a project