skip to content

In a Cloudflare Worker, how do fetch()'s cf.image options resize images, and how do you keep the Worker from resizing its own source requests?

level: middleimportance: should knowfreq 25%

answer

  1. options on a subrequest, not the URL
  2. route the Worker on an image path
  3. the resizer marks its own fetches
  4. Via contains image-resizing
  5. Accept is the Worker's job

basics

~10 s

A Worker calls fetch(sourceURL, { cf: { image: {...} } }) and returns the result. Route it only on an image path, keep originals elsewhere, and pass through requests whose Via header contains image-resizing.

solid answer

~50 s

`cf.image` is the same pipeline as the `/cdn-cgi/image/` URL, driven from code: the Worker computes the source URL and options, calls `fetch(src, { cf: { image: { width, fit, format } } })` and returns the response. That lets the URL carry a preset name (`/img/card/...`) instead of pixel sizes, and lets the Worker validate or hide the source host. Scope the Worker to a path such as `/images/*`, never `/*`, and keep originals under another path. When paths overlap, the resizer's fetch of the original arrives with `image-resizing` in its `Via` header; the Worker must pass that request through with `fetch(request)` or it loops (error 9403). `format: "auto"` is not a `cf.image` value: the Worker reads `Accept` and sets `avif` or `webp` itself. Resized results are cached under the source URL; the Worker's own response is not.

code

javascript · 22 lines
javascript
const PRESETS = { thumb: 160, card: 320, zoom: 960 };

export default {
  async fetch(request) {
    // A fetch made by the resizer itself: serve the original untouched.
    if (/image-resizing/.test(request.headers.get("via") || "")) {
      return fetch(request);
    }
    const url = new URL(request.url);
    const m = url.pathname.match(/^\/img\/([a-z]+)\/(.+)$/);
    const width = m && PRESETS[m[1]];
    if (!width) return new Response("unknown size", { status: 400 });

    const accept = request.headers.get("accept") || "";
    const image = { width, fit: "scale-down" };
    if (/image\/avif/.test(accept)) image.format = "avif";
    else if (/image\/webp/.test(accept)) image.format = "webp";

    const res = await fetch(`${url.origin}/originals/${m[2]}`, { cf: { image } });
    return res.ok ? res : Response.redirect(`${url.origin}/originals/${m[2]}`, 307);
  },
};

go deeper

for a junior

Recall that cf.image is an option on a fetch() subrequest inside a Worker, and that the Worker should run only on an image path.

for a middle

Explain the loop: the resizer fetches the original, overlapping routes re-run the Worker, and the Via header containing image-resizing is the pass-through signal.

for a senior

Show the production habits: presets instead of free-form sizes, source validation, error fallbacks, and purging the source URL because the Worker's response is never cached.

for a principal

Weigh whether a team standardises on a resizing Worker with presets, and who owns its routes, preset table and fallback policy.

## Same pipeline, driven from code The `/cdn-cgi/image/` URL is one front door to Cloudflare's image transformations. A **Worker** (Cloudflare's serverless code running in front of your zone) can use the same pipeline by adding a `cf.image` object to the options of an outgoing `fetch()` subrequest: ```js return fetch(sourceURL, { cf: { image: { width: 320, fit: "scale-down", format: "webp" } } }); ``` The subrequest fetches the original, the resizer transforms it, and the Worker returns the transformed response to the browser. `cf.image` works on any zone that hosts a Worker, including `workers.dev` subdomains, and each transformation is billed to the account that owns the Worker. ## Why teams put a Worker in front - **Presets instead of pixels.** The public URL names a size (`/img/thumb/...`, `/img/card/...`) and the Worker maps it to dimensions, so nobody can ask for width 5000 or a thousand odd widths. - **A hidden or authenticated source.** The original can live on a private host or behind signed requests; visitors only see the Worker's URL. - **Validation.** The Worker can check the extension, the source hostname and the parameters before any transformation is spent. - **Fallbacks.** A failed transformation comes back with an error status such as 400, 404 or 502; the Worker can redirect to the original or serve a placeholder instead of passing the error on. ## Format negotiation is your code's job With the URL interface, `format=auto` picks AVIF or WebP from the browser's capabilities. The `cf.image.format` field accepts concrete formats such as `avif`, `webp`, `jpeg`, `png` and `json`, not `auto`. The Worker therefore inspects the visitor's `Accept` header: 1. If `Accept` contains `image/avif`, set `format: "avif"`. 2. Otherwise, if it contains `image/webp`, set `format: "webp"`. 3. Otherwise leave `format` unset and the original format is kept. ## Request loops and how the resizer marks itself The resizer must fetch the original. If the Worker's route also matches the original's path, the resizer's fetch runs the Worker again, which asks for another resize, and so on. Cloudflare's guidance is: - route the Worker on a dedicated path (`/img/*`, `/thumbnails/*`), **never on `/*`**, which would also break every non-image request; - keep originals under a different path (`/originals/*`); - where the paths must overlap, test whether the `Via` request header contains **`image-resizing`**. That string marks a fetch made by the resizer itself, so the Worker should return `fetch(request)` untouched. A loop that slips through fails with error code 9403 in `Cf-Resized`. Resizing is also forgotten once one Worker calls another, so an extra Worker in the chain is a common reason a `Cf-Resized` header never appears. ## Private or authenticated originals By default the resizer's fetch of the original is **anonymized**: no cookies, no `Authorization` and no custom headers reach the origin. Cloudflare keeps one public cache of resized images, and sharing images personalized for individual visitors from it would be unsafe. When a team accepts that the results will sit in that public cache, a Worker can set `"origin-auth": "share-publicly"` inside `cf.image`. Headers such as `Authorization`, `Cookie`, the storage-signature date headers and `cf-access-client-id` / `cf-access-client-secret` then pass through to the origin. The trade is explicit in the option's name: the original is protected, the derivatives are not. Per-visitor images that must stay private belong in hosted storage with signed URLs instead. ## Caching, purging and testing | Concern | What Cloudflare does | |---|---| | Derivatives | always cached, as variants under the cache entry of the full-size source URL | | The Worker's own response | not cached; the Worker code runs on every request | | Purging | purge the source image's URL; purging the Worker's URL does nothing | | `cacheKey` option | if you use it to unify sources, give it the full-size source URL only, never resize options | The dashboard's Worker preview ignores `cf` options and always shows the unresized image. Under `wrangler dev`, `cf.image` runs through a low-fidelity local mock that applies only a subset of options, such as resizing, rotation and format conversion, and ignores the rest. Test full behaviour on a deployed Worker. ## A worked example The snippet below maps three presets to widths, picks the format from `Accept`, and guards the overlapping path with the `Via` check. Run locally, a request for `/img/card/...` with `Accept: image/webp` returned a 320-pixel-wide WebP, the same request with `image/avif` returned AVIF, a request with no `Accept` kept PNG, and an unknown preset returned 400 before any transformation ran.

  • Why would a team route the resizing Worker on /img/* rather than on the whole zone?
    A Worker on `/*` runs for every request, so HTML, CSS and scripts would be sent to the resizer and fail, and the resizer's fetch of each original would re-enter the Worker. A dedicated image path keeps non-image traffic away and separates the originals' path from the resized one.
  • How should a cf.image Worker react when the transformation fails?
    Check `response.ok`; on failure either redirect to the original with a 307 or serve a placeholder image. For very large originals a placeholder is safer, because falling back to the full-size file can waste bandwidth and break the page layout.

  • Setting cf.image.format to auto and expecting the runtime to read Accept
  • Routing the resizing Worker on the whole zone with /*
  • Purging the Worker's URL to refresh a resized image
  • Putting width and quality into the cacheKey fetch option
  • Trusting the dashboard preview to show cf.image results