Serving Astro Images Through Cloudflare Image Resizing

Astro's built-in image pipeline does its work at build time: every image, every width, every format, encoded with sharp before the site deploys. That is ideal until the image count grows. A content site with 6,000 images and five widths in two formats asks the build to encode 60,000 files; even with a cache, every new or changed image adds encoding time, and a cold build — a new CI runner, a cleared cache, a dependency upgrade — takes as long as encoding everything.

This guide moves that work to Cloudflare's image transformations: Astro still generates srcset, sizes, width and height, but each URL points at an on-the-fly transformation that Cloudflare encodes on first request and caches at the edge. It is done for a 2,800-page travel content site deployed on Cloudflare, with about 6,100 source images. It belongs to Image Optimization Pipelines in Astro; the general approach is in Building an Image CDN Pipeline for Static Sites.

Prerequisites

  • A site served through Cloudflare on a plan with image transformations enabled for the zone.
  • Original images published with the site (or in R2), reachable at a stable URL.
  • Astro 5.

Before: Build-Time Processing

MeasureValueTool
Source images6,100find
Generated files (5 widths × 2 formats)~61,000Build output
Cold build21 min 10 sGitHub Actions
Warm build (image cache restored)4 min 30 sGitHub Actions
Cache restore time1 min 50 s (2.9 GB)Actions logs
Deploy upload3.1 GBWrangler output

Even warm builds spent nearly two minutes restoring a 2.9 GB cache, and the deploy pushed 3.1 GB of image variants.

How It Works

Sequence of an image request through Cloudflare image transformations Four actors, the browser, the Cloudflare edge, the transformation service and the origin. The HTML contains a srcset of transformation URLs generated by the Astro image service. The browser requests the width it needs in its preferred format. On a cache miss the edge asks the transformation service, which fetches the original from the origin, resizes and encodes it, and the edge caches the result. Later requests for the same URL are served from the edge cache. Image request with edge transformation Browser CF edge Transform Origin GET /cdn-cgi/image/width= 960,format=auto/… cache miss fetch original resized AVIF cached response (later: HIT)
Only the first request for each width and format pays the encoding cost; after that it is an ordinary cached file.

Step 1: Write a Custom Image Service

An Astro image service has two jobs: produce a URL for given transform options, and report which options it supports. For an external transformer, getURL is enough:

// src/image-service/cloudflare.ts
import type { ExternalImageService } from 'astro';
import { baseService } from 'astro/assets';

const service: ExternalImageService = {
  ...baseService,
  getURL(options) {
    const src = typeof options.src === 'string' ? options.src : options.src.src;
    const params = [`width=${options.width}`, `quality=${options.quality ?? 80}`, 'format=auto', 'fit=scale-down'];
    if (options.height) params.push(`height=${options.height}`);
    return `/cdn-cgi/image/${params.join(',')}${src}`;
  },
};
export default service;
// astro.config.mjs
export default defineConfig({
  image: { service: { entrypoint: './src/image-service/cloudflare.ts' } },
});

format=auto lets Cloudflare pick AVIF or WebP from the browser's Accept header, so one URL serves both — which means <Picture> with separate formats is no longer needed; <Image> with widths and sizes is enough. fit=scale-down never upscales beyond the original.

Step 2: Keep the Originals Published

The transformation fetches the original from the site. With build-time processing disabled, Astro copies each imported image's original to dist/_astro/ with a hashed name, which the service's URLs reference. Those originals are the only image files the deploy uploads — 6,100 files, 1.4 GB, rather than 61,000 and 3.1 GB. Restricting transformations to the zone's own origin in the Cloudflare dashboard prevents others using the endpoint to resize arbitrary images.

Step 3: Check the Output Markup

<img src="/cdn-cgi/image/width=1440,quality=80,format=auto,fit=scale-down/_astro/canyon.Bq8f.jpg"
     srcset="/cdn-cgi/image/width=480,…/_astro/canyon.Bq8f.jpg 480w, … 1920w"
     sizes="(max-width: 48rem) 100vw, 960px" width="1440" height="960" alt="…" loading="lazy" decoding="async">

Width and height are still present, read from the original's header at build time, so there is no layout shift. srcset and sizes are unchanged from the build-time version.

Step 4: Handle the LCP Image

The first request for a new transformation is slower than a cached file: on a cold edge, a hero image transformation took 180–420 ms longer. For LCP images, the deploy job warms the cache for the hero image of each page's most-visited variants by requesting them right after deploy (about 1,200 URLs, 40 seconds), and hero images are marked loading="eager" with fetchpriority="high", as in Optimizing LCP on Astro with Priority Hints.

Build time, cache size and deploy upload with build-time and edge image processing Paired bars. Cold build went from 21.2 to 2.4 minutes. Warm build from 4.5 to 2.1 minutes. Deploy upload from 3.1 to 1.4 gigabytes. Build and deploy, before and after Build-time sharp Edge transformations Cold build (min) 21.2 2.4 Warm build (min) 4.5 2.1 Deploy upload (GB) 3.1 1.4
GitHub Actions timings and Wrangler upload sizes, median of five builds each.

Images From a CMS or R2

About 900 of the site's images were uploaded by editors to an R2 bucket rather than committed to the repository. Those never went through Astro's pipeline at all before — they were plain <img> tags with whatever size the editor uploaded, often 4,000 pixels wide. The same image service handles them: remote images are authorised in image.remotePatterns for the R2 public hostname, the content loader records each image's width and height when it syncs entries from the CMS, and components pass those dimensions to <Image> with inferSize turned off. Every editor-uploaded image now gets a proper srcset and AVIF without the build ever downloading it. Median bytes for pages with CMS images fell from 2.3 MB to 520 KB, the largest single improvement of the change.

Watching Cost and Cache Behaviour

Unique transformations are the billing unit, so anything that creates many unique URLs costs money: arbitrary widths, per-request quality values, or query strings. The service only ever emits the five widths in the site's widths list and two quality values, which keeps the monthly count close to images × widths. A dashboard query on unique transformations per day alerts if the count doubles, which would point at a template generating unusual sizes. The edge cache hit ratio for /cdn-cgi/image/ paths settled at 96% after the first week, similar to other static assets on the site.

Measured Impact

MeasureBuild-timeEdgeTool
Cold build21 min 10 s2 min 25 sGitHub Actions
Warm build4 min 30 s2 min 05 sGitHub Actions
Image bytes per page (median, mobile)410 KB360 KBDevTools
Image TTFB, cached38 ms41 msRUM resource timing
Image TTFB, first request (uncached)—210–430 msRUM resource timing
LCP p75, mobile2.1 s2.0 sCrUX
Unique transformations / month—~7,800Cloudflare dashboard

Image bytes fell slightly because format=auto served AVIF to every supporting browser, where the old pipeline had served AVIF only through <Picture> on some templates. LCP held steady thanks to cache warming for heroes.

Decision tree for choosing build-time or edge image processing The root asks how many images the site has and how often it builds. Under about 1,000 images, build-time processing is simpler. Thousands of images with frequent builds favour edge resizing. Sites not behind Cloudflare could use another image CDN with the same custom service approach. Sites needing offline or fully self-contained output should keep build-time processing. Build-time or edge resizing? How many images, how often built? Under ~1,000 images Build-time simplest Thousands, frequent builds Edge resizing this guide Not on Cloudflare Other image CDN same service pattern Self-contained output needed Build-time no runtime dependency
The custom service is about 20 lines whichever image CDN it points at.

Testing the Service

A Vitest test calls the service's getURL with representative options and asserts the exact URL shape, including that widths outside the allowed list are rounded to the nearest allowed width. A Playwright check on preview deploys loads three image-heavy pages and asserts every image response is AVIF or WebP with a 200 status and a width no larger than requested. Together they take under 20 seconds and caught one regression: a component passing width={undefined} that produced width=undefined in URLs.

Pitfalls & Rollback

  • Leaving transformations open to any origin. Restrict them to your zone.
  • Uncached LCP images after deploy. Warm hero images or accept a slower first view.
  • Keeping <Picture> with format lists. With format=auto, <Image> is enough.
  • Local development. /cdn-cgi/image/ does not exist on astro dev; the service returns the original URL when import.meta.env.DEV is true.
  • Rollback: remove the image.service setting and Astro returns to sharp at build time; nothing in components changes.

Conclusion

Moving image processing from the Astro build to Cloudflare's transformations kept everything the components produce — srcset, sizes, dimensions — while making builds fast again. On a site with 6,100 images, the cold build fell from 21 minutes to under 2.5, the deploy halved in size, and readers got AVIF more often, at the cost of a slower first request for each new variant, which cache warming hides for LCP images.

FAQ

Why move image resizing out of the Astro build?

Because processing thousands of images into several widths and formats at build time takes minutes and multiplies with every new image. Resizing at the edge on first request, then caching the result, keeps builds fast and still serves correctly sized modern formats. It suits sites with many images and frequent builds.

Do I lose srcset and sizes with an edge image service?

No. A custom Astro image service only changes how image URLs are generated. Astro's Image and Picture components still produce srcset, sizes, width and height; each candidate URL points at a Cloudflare transformation with the requested width and format instead of a prebuilt file.

How are image dimensions known if the build does not process images?

Astro still reads each local image's metadata at build time, which is fast because it only reads the file header. Width and height attributes are therefore still correct, so there is no layout shift. Only the resizing and encoding move to the edge.

What does Cloudflare image transformation cost?

Cloudflare bills transformations by unique transformations per month, with a free allowance on paid plans, and caches the results at the edge. For the site in this guide, about 7,800 unique transformations a month cost a few dollars. Check current pricing, as plans and allowances change.

Filed underHow-tosAstroCloudflare