---
title: "Astro Cloudflare Workers: Precompile WebP & Avoid 404s"
description: "Replace slow /_image Worker transforms in @astrojs/cloudflare with imageService: compile, transcode WebP via Sharp, and fix og:image 404s with getImage()."
image: "https://zengliangyi.com/og/blog/en/astro-cloudflare-compile-webp-images.png"
---

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`](https://github.com/ZengLiangYi/zengliangyi.com/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'`](https://docs.astro.build/en/guides/integrations-guide/cloudflare/#imageservice) 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`:



```js
// 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](/en/blog/carousel-subpixel-1px-seam/))—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:



```js
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.src` holds Vite’s  untransformed module asset URL  (for example, `/_astro/agent_memory_loop_cover.BNw6CG8C.webp`).

- Under `cloudflare-binding`, that untransformed file stays in `dist/client/_astro/` because the runtime `/_image` Worker needs the raw source at request time—masking the bug.

- Under `compile`, Astro emits only transformed files registered via `<Image />` or `getImage()` (such as `/_astro/agent_memory_loop_cover.BNw6CG8C_1cBDnt.webp`) and  garbage-collects the unreferenced raw `image.src` file  so `dist/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`:



```astro
---  
  // 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](/en/blog/gsc-alternate-page-trailing-slash/), 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:



```js
// 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 with `immutable` CDN headers;

- Metadata & SEO integrity : 142 article and project pages verified against emitted files on disk and `<image:loc>` entries in `sitemap-0.xml`.

Share:

##  Related Posts

[##  Fix GSC "Alternate Page with Proper Canonical" in Astro

Fix Google Search Console "Alternate page with proper canonical tag" in Astro and Cloudflare Workers with trailing-slash links, 301s, and build checks.          Leon Zeng       October 29, 2026      6 min read

#Astro

#SEO

#Google](/en/blog/gsc-alternate-page-trailing-slash/)    [##  Google Indexing API in Astro: Incremental Sitemap Cache

How to fix Google indexing deadlocks in static Astro sites using incremental cache-driven API submissions, Git SHA hashing, and sitemap lastmod timestamps.          Leon Zeng       October 13, 2026      4 min read

#Astro

#SEO

#Google](/en/blog/google-indexing-incremental-cache/)    [##  Fixing 1px Carousel Seams: Subpixel Layout and Scale Fixes

Debug 1px mobile carousel seams caused by subpixel rounding. Compare negative margins, CSS translation, and scale transforms to eliminate rendering gaps.          Leon Zeng       October 13, 2026      5 min read

#CSS

#Frontend

#Performance](/en/blog/carousel-subpixel-1px-seam/)

##  From writing to code

Explore ChatCrystal, KeelDesk, n8n workflows and daily learning notes on my GitHub. Questions about the implementation are welcome.

[Visit my GitHub](https://github.com/ZengLiangYi)

```json
{
  "@context": "https://schema.org",
  "@id": "https://zengliangyi.com/#website",
  "@type": "WebSite",
  "name": "ZengLiangYi Blog",
  "alternateName": [
    "Leon Zeng",
    "Zeng Liangyi",
    "ZengLiangYi",
    "zengliangyi.com"
  ],
  "url": "https://zengliangyi.com",
  "description": "Frontend engineering, AI coding and open-source practice",
  "inLanguage": "en",
  "author": {
    "@id": "https://zengliangyi.com/#person"
  }
}
{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Astro Cloudflare Workers: Precompile WebP & Avoid 404s",
  "description": "Replace slow /_image Worker transforms in @astrojs/cloudflare with imageService: compile, transcode WebP via Sharp, and fix og:image 404s with getImage().",
  "url": "https://zengliangyi.com/en/blog/astro-cloudflare-compile-webp-images/",
  "image": "https://zengliangyi.com/images/blog/astro-cloudflare-compile-webp-images.svg",
  "datePublished": "2026-11-15T00:00:00.000Z",
  "dateModified": "2026-11-15T00:00:00.000Z",
  "inLanguage": "en",
  "keywords": [
    "Astro",
    "Performance",
    "Frontend",
    "SEO"
  ],
  "articleSection": "Astro",
  "isPartOf": {
    "@id": "https://zengliangyi.com/#website"
  },
  "author": {
    "@id": "https://zengliangyi.com/#person",
    "@type": "Person",
    "name": "曾亮懿",
    "alternateName": [
      "Leon Zeng",
      "Zeng Liangyi",
      "ZengLiangYi",
      "夜雪闻竹"
    ],
    "jobTitle": "AI Native Developer",
    "knowsAbout": [
      "AI Native Development",
      "AI Agents",
      "Model Context Protocol",
      "TypeScript",
      "React",
      "Full-Stack Development",
      "Developer Tools"
    ],
    "url": "https://zengliangyi.com/en/about/",
    "email": "contact@zengliangyi.com",
    "image": "https://zengliangyi.com/branding/zeng-liangyi-avatar.png",
    "address": {
      "@type": "PostalAddress",
      "addressLocality": "深圳",
      "addressRegion": "广东",
      "addressCountry": "CN"
    },
    "sameAs": [
      "https://github.com/ZengLiangYi",
      "https://x.com/LeonZeng_",
      "https://bsky.app/profile/yizel9.bsky.social",
      "https://www.reddit.com/user/ExternalActive4238/",
      "https://juejin.cn/user/1669474445171547",
      "https://blog.csdn.net/2201_75708499",
      "https://www.linkedin.com/in/zeng-liangyi/",
      "https://gravatar.com/radangelb905e883e0"
    ]
  },
  "publisher": {
    "@type": "Organization",
    "name": "ZengLiangYi Blog",
    "url": "https://zengliangyi.com",
    "logo": {
      "@type": "ImageObject",
      "url": "https://zengliangyi.com/favicon-96x96.png"
    }
  },
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "https://zengliangyi.com/en/blog/astro-cloudflare-compile-webp-images/"
  }
}
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "name": "Astro Cloudflare Workers: Precompile WebP & Avoid 404s",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Why does @astrojs/cloudflare rewrite Astro <Image /> tags to /_image URLs on static pages?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Calling cloudflare() with no options defaults imageService to cloudflare-binding, which defers responsive resizing to runtime Cloudflare Worker /_image requests. Passing cloudflare({ imageService: \"compile\" }) restores build-time Sharp static WebP generation."
      }
    },
    {
      "@type": "Question",
      "name": "Why do og:image and image sitemap URLs return 404 after enabling imageService: compile in Astro?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Under compile mode, Astro emits only transformed image variants registered via <Image /> or getImage() and deletes unreferenced raw Vite asset copies (image.src). Layouts must call await getImage({ src: image, format: \"webp\" }) instead of reading entry.data.image.src directly."
      }
    },
    {
      "@type": "Question",
      "name": "Which site images should stay PNG or JPEG instead of converting to WebP?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Browser and OS app icons (favicon-16x16.png, favicon-32x32.png, apple-touch-icon.png, and PWA 192x192/512x512 icons) must remain PNG for iOS home-screen and Web App Manifest compatibility, and build-time template backgrounds used to rasterize /og/*.png social cards should stay in their native input format."
      }
    },
    {
      "@type": "Question",
      "name": "Do I still need Astro compile-time optimization if my source files are already WebP?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. Source WebP transcoding shrinks repository and CI decode weight (17.02 MB down to 2.13 MB here), while Astro compile-time optimization generates responsive 320w, 640w, 960w, and 1280w srcset variants so mobile cards download 8-21 KB thumbnails instead of full-resolution covers."
      }
    }
  ]
}
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "name": "Breadcrumb",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Home",
      "item": "https://zengliangyi.com/en/"
    },
    {
      "@type": "ListItem",
      "position": 2,
      "name": "Blog",
      "item": "https://zengliangyi.com/en/blog/"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": "Astro Cloudflare Workers: Precompile WebP & Avoid 404s",
      "item": "https://zengliangyi.com/en/blog/astro-cloudflare-compile-webp-images/"
    }
  ]
}
```
