Cloudflare Adapter Image Optimization
Host originals on Cloudflare, let the edge transcode/crop, and emit proper src/srcset from Astro—save bandwidth and speed up LCP.
Why optimize images?
- Originals are heavy (MB-level).
- Devices vary; need different sizes and formats (WebP/AVIF/JPEG).
- Optimized assets improve LCP and cut bandwidth.
Cloudflare Images (recommended)
-
Upload originals (dashboard/CLI/API).
-
Define variants (size, quality, format).
-
URLs:
https://imagedelivery.net/{hash}/{id}/{variant}. -
Astro example:
--- const base = "https://imagedelivery.net/<hash>/<id>"; const variants = [ { name: "thumb", media: "(max-width: 640px)" }, { name: "mid", media: "(max-width: 1024px)" }, { name: "lg", media: "" }, ]; --- <picture> {variants.map((v) => ( <source srcset={`${base}/${v.name}`} media={v.media} /> ))} <img src={`${base}/lg`} alt="demo" loading="lazy" width="1200" height="600" /> </picture>
Adapter Image Service
- compile: transcode at build; faster first visit, bigger build time/size.
- passthrough: transcode at runtime; smaller build, first hit may be slower, depends on Cloudflare runtime.
Passthrough config:
import cloudflare from "@astrojs/cloudflare";
import { defineConfig } from "astro/config";
export default defineConfig({
adapter: cloudflare({
imageService: { service: "cloudflare", config: { mode: "passthrough" } },
}),
});
Edge function transforms (object storage)
- If images live in S3/OSS: use Pages Functions/Workers + image resizing.
- URLs like
/img?w=800&fmt=webp&url=https://bucket/xxx.jpg. - Cache transformed results; cache originals even longer.
Astro usage tips
<img>withsrcset/sizes; or lightweight@astrojs/image.- Always set
width/heightoraspect-ratioto avoid CLS; addloading="lazy",decoding="async". - Backgrounds: multiple sizes/media queries instead of one huge asset.
Quality and formats
- Prefer WebP/AVIF; fall back to JPEG/PNG when needed.
- Quality 70–85 is common; use SVG for vectors.
Troubleshooting
- 404: variant/path mismatch.
- Slow first hit: passthrough needs initial transcode; pre-warm or switch to compile.
- Color issues: check quality/format and color space.
- Large size: lower quality or add more size variants.
- CLS: ensure width/height.
Summary
With Cloudflare Images or the adapter’s image service, you can:
- Improve performance via format/size/quality optimization.
- Simplify workflow—no manual image processing.
- Leverage CDN caching for optimized assets.
Choose the mode that fits your project to balance build time and runtime performance.***