Table of contents Show Hide
- Why Astro <Image /> Defaults to Runtime /_image Transforms on Cloudflare Workers
- Batch-Transcoding Source Rasters with Sharp—and Which PNG/JPEG Files Must Stay Untouched
- Fixing Silent og:image and Sitemap 404s Caused by Raw image.src Under imageService: 'compile'
- Verifying Emitted Build Artifacts Instead of Trusting Exit Code 0
Using <Image /> from astro:assets everywhere does not automatically guarantee precompiled static images when deploying to Cloudflare Workers. While investigating sluggish cover and screenshot loads on this site (Astro 7 + @astrojs/cloudflare v14, commit d5cd057), the browser Network panel exposed two compounding bottlenecks: 34 blog covers and project screenshots were checked into Git as 450–734 KB .jpg and .png files (17.02 MB total), and calling adapter: cloudflare() with default options rewrote every <img> into a runtime /_image?href=%2F_astro%2F...&w=...&f=webp Worker request instead of precompiling static files.
Batch-transcoding source rasters to .webp and switching to cloudflare({ imageService: 'compile' }) cut source asset weight to 2.13 MB (-87.5%), shrank blog card thumbnails to 8–21 KB, and eliminated runtime Worker image transforms completely. Right after flipping that setting, however, our post-build verification script caught a subtle production trap: astro build exited 0, yet 31 og:image, JSON-LD image, and image sitemap URLs silently pointed to deleted 404 files. Here is the full root-cause breakdown and verification workflow.
Why Astro <Image /> Defaults to Runtime /_image Transforms on Cloudflare Workers
Without a server adapter, astro build runs Node sharp at build time to emit static .webp variants; adding @astrojs/cloudflare with bare cloudflare() switches the default imageService to 'cloudflare-binding', which skips build-time optimization, ships raw source images into dist/client/_astro/, and routes every <img> request through an on-demand /_image Worker endpoint.
For prerendered blogs, documentation sites, and portfolios where every cover and screenshot is known at build time, runtime edge resizing adds latency without adding flexibility. Cold edge locations incur a Worker invocation plus an image-transform round trip on uncached breakpoints, while your deployment bundle still carries hundreds of kilobytes per unoptimized JPEG or PNG.
| Dimension | cloudflare() Default (cloudflare-binding) |
cloudflare({ imageService: 'compile' }) |
|---|---|---|
| When resizing runs | At request time via /_image?href=... Worker + Images binding |
Once during astro build via Node.js sharp |
Emitted HTML src |
/_image?href=%2F_astro%2Fcover.xxx.jpg&w=640&f=webp |
/_astro/cover.xxx_Z21kPRn.webp (immutable static asset) |
| Edge caching | Dynamic endpoint cache; cold POPs pay transform latency | Auto-injected _headers rule: Cache-Control: public, max-age=31536000, immutable |
| Worker & binding cost | Requires IMAGES binding and bills Worker/transform requests |
Zero Worker invocations; served directly by Cloudflare Static Assets CDN |
Setting imageService: 'compile' in astro.config.mjs instructs @astrojs/cloudflare to collect static image transforms during workerd prerendering and compile every responsive variant with sharp before packaging dist/client:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
output: 'static',
// Pre-generate responsive static /_astro/*.webp variants at build time via Sharp
adapter: cloudflare({ imageService: 'compile' }),
});
Pair this with explicit widths and sizes props on <Image />—such as widths={[320, 640, 960]} on index cards and widths={[640, 960, 1280]} on wide inline MDX screenshots (alongside stable aspect-ratio containers, much like preventing 1px subpixel carousel seams)—so mobile viewports pick lightweight variants cleanly.
Batch-Transcoding Source Rasters with Sharp—and Which PNG/JPEG Files Must Stay Untouched
Even with build-time compilation enabled, converting repository .jpg and .png content assets to .webp cut our 34 source files from 17.02 MB to 2.13 MB (-87.5%), speeding up Git clones and CI Sharp decode passes. The key is tuning chroma subsampling separately for illustrations versus UI screenshots—and leaving OS/PWA icons strictly in PNG.
Editorial cover illustrations compress cleanly at quality: 82, whereas UI screenshots with crisp dark-mode text or dense node graphs (like ChatCrystal note views or Telegram inline-button cards) suffer from color fringing under standard 4:2:0 chroma subsampling unless smartSubsample: true and quality: 86 are enabled:
import fs from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
const targets = [
['src/assets/blog', { quality: 82, effort: 6 }],
['src/assets/projects', { quality: 86, effort: 6, smartSubsample: true }],
];
for (const [dir, webpOptions] of targets) {
const files = (await fs.readdir(dir)).filter((f) => /\.(jpe?g|png)$/i.test(f));
for (const file of files) {
const srcPath = path.join(dir, file);
const outPath = path.join(dir, file.replace(/\.(jpe?g|png)$/i, '.webp'));
const srcMeta = await sharp(srcPath).metadata();
await sharp(srcPath).webp(webpOptions).toFile(outPath);
// Verify format and pixel dimensions match before removing the legacy source
const outMeta = await sharp(outPath).metadata();
if (
outMeta.format !== 'webp' ||
outMeta.width !== srcMeta.width ||
outMeta.height !== srcMeta.height
) {
throw new Error(`Dimension mismatch on ${outPath}`);
}
await fs.unlink(srcPath);
}
}
Never run a blind repo-wide extension sweep across public/ or branding templates. Three categories of raster files have strict client or pipeline requirements and must not be converted to WebP:
| Asset Path & Role | Required Format | Why WebP Breaks Compatibility |
|---|---|---|
public/apple-touch-icon.png |
PNG | iOS Safari requires PNG for home-screen icons; WebP falls back to generic page screenshots |
public/pwa-*.png & favicon-*.png |
PNG | Web App Manifest install prompts and legacy browser tab parsers expect PNG icons |
src/assets/branding/og-background.jpg |
JPG / PNG | Consumed by build-time Sharp composition to emit /og/*.png cards with universal scraper support |
Fixing Silent og:image and Sitemap 404s Caused by Raw image.src Under imageService: 'compile'
Enabling imageService: 'compile' introduces a silent metadata trap: if a layout copies entry.data.image.src from an Astro Content Collection straight into <meta property="og:image">, Schema.org JSON-LD, or your XML image sitemap, astro build succeeds with zero warnings while every one of those URLs 404s in production.
Here is why the mismatch happens under the hood:
- When Astro’s
image()content schema imports a cover,image.srcholds Vite’s untransformed module asset URL (for example,/_astro/agent_memory_loop_cover.BNw6CG8C.webp). - Under
cloudflare-binding, that untransformed file stays indist/client/_astro/because the runtime/_imageWorker needs the raw source at request time—masking the bug. - Under
compile, Astro emits only transformed files registered via<Image />orgetImage()(such as/_astro/agent_memory_loop_cover.BNw6CG8C_1cBDnt.webp) and garbage-collects the unreferenced rawimage.srcfile sodist/client/_astro/does not ship duplicate originals.
Fix both blog and project layouts by resolving metadata covers through getImage() from astro:assets, and update your ogImageAlt check so it tests the resolved shareableCover variable rather than comparing against the discarded image?.src:
---
// src/layouts/BlogLayout.astro (and src/layouts/ProjectLayout.astro)
import { getImage } from 'astro:assets';
import { getBlogOgPath, getDefaultOgPath, isShareableImage } from '@/lib/og/svg';
// ❌ Broken under imageService: 'compile' — raw image.src is cleaned up after Sharp runs
// const ogImage = image && isShareableImage(image.src) ? image.src : fallbackOgPath;
// ✅ Register the cover with getImage() so Sharp emits a real static WebP artifact
const shareableCover =
image && isShareableImage(image.src)
? (await getImage({ src: image, format: 'webp' })).src
: null;
const ogImage =
shareableCover ?? (slug ? getBlogOgPath(postSlug, localePrefix) : getDefaultOgPath());
// Preserve custom cover alt text when using the cover; fall back to title for generated OG cards
const ogImageAlt = shareableCover ? imageAlt || title : title;
---
Verifying Emitted Build Artifacts Instead of Trusting Exit Code 0
Just as we saw when fixing GSC “Alternate page with proper canonical tag” warnings in Astro, a 0 exit code from astro build only proves the bundler finished—not that every metadata URL resolves on disk. Catching broken social cards and sitemap entries before deployment requires asserting against the emitted dist/client directory.
Our post-build verify-article-images.mjs check caught all 28 blog covers and—once extended to inspect SoftwareApplication JSON-LD alongside BlogPosting—all 3 project covers before a single broken link reached production:
// Excerpt from scripts/verify-article-images.mjs
const entries = [
...(await collectArticleMetadata(outDir)), // BlogPosting JSON-LD image URLs
...(await collectProjectMetadata(outDir)), // SoftwareApplication JSON-LD image URLs
];
for (const entry of entries) {
if (!sitemapImages.get(entry.canonical)?.includes(entry.image)) {
failures.push(`Sitemap image missing: ${entry.canonical}`);
}
const url = new URL(entry.image);
const filePath = join(outDir, decodeURIComponent(url.pathname));
const bytes = await readFile(filePath).catch(() => null);
if (!bytes) {
failures.push(`Article image file missing: ${entry.image}`);
}
}
Paired with a fast Vitest guard that fails whenever a .jpg or .png lands in src/assets/blog or src/assets/projects or if cloudflare({ imageService: 'compile' }) is removed from astro.config.mjs, the end-to-end results across all 247 built pages are locked in:
- Source raster footprint: 17.02 MB -> 2.13 MB (-87.5%) across 34 blog and project assets;
- Client transfer weight: 0 runtime
/_image?href=requests, 8.2–20.8 KB responsive card thumbnails, and 40–78 KB full-width hero images served withimmutableCDN headers; - Metadata & SEO integrity: 142 article and project pages verified against emitted files on disk and
<image:loc>entries insitemap-0.xml.