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
| Measure | Value | Tool |
|---|---|---|
| Source images | 6,100 | find |
| Generated files (5 widths × 2 formats) | ~61,000 | Build output |
| Cold build | 21 min 10 s | GitHub Actions |
| Warm build (image cache restored) | 4 min 30 s | GitHub Actions |
| Cache restore time | 1 min 50 s (2.9 GB) | Actions logs |
| Deploy upload | 3.1 GB | Wrangler 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
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.
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
| Measure | Build-time | Edge | Tool |
|---|---|---|---|
| Cold build | 21 min 10 s | 2 min 25 s | GitHub Actions |
| Warm build | 4 min 30 s | 2 min 05 s | GitHub Actions |
| Image bytes per page (median, mobile) | 410 KB | 360 KB | DevTools |
| Image TTFB, cached | 38 ms | 41 ms | RUM resource timing |
| Image TTFB, first request (uncached) | — | 210–430 ms | RUM resource timing |
| LCP p75, mobile | 2.1 s | 2.0 s | CrUX |
| Unique transformations / month | — | ~7,800 | Cloudflare 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.
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. Withformat=auto,<Image>is enough. - Local development.
/cdn-cgi/image/does not exist onastro dev; the service returns the original URL whenimport.meta.env.DEVis true. - Rollback: remove the
image.servicesetting 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.
Related
- Parent: Image Optimization Pipelines in Astro — the full pipeline.
- Building an Image CDN Pipeline for Static Sites — image CDNs in general.
- Caching Processed Images Between Builds — the build-time alternative made faster.
- Fixing Blurry Images From astro:assets Resizing — getting widths right with either approach.
- Deploying Astro to Cloudflare Workers Static Assets — the hosting this assumes.
Filed underHow-tosAstroCloudflare