Cloudflare Workers AVIF Image Transformation at the Edge
Cloudflare Workers enables programmatic, edge-based AVIF image transformation by intercepting incoming asset requests at the network edge, detecting browser support, and dynamically converting images using integrated transformation features. By handling format conversion before requests reach the origin server, Workers delivers highly compressed, next-generation AVIF images with minimal latency, significantly reducing page load times and bandwidth consumption.
Edge Interception and Format Negotiation
When a client requests an image, the Cloudflare Worker intercepts the
HTTP request via a fetch event listener before it hits the
cache or origin. The Worker inspects the client's Accept
request header to determine if the browser natively supports the AVIF
format (indicated by image/avif).
Because AVIF offers superior compression compared to WebP and JPEG, identifying support at the edge allows the Worker to tailor the response specifically to modern clients without serving incompatible assets to older browsers.
Programmatic
Transformation Using cf.image
Once AVIF support is confirmed, the Worker utilizes Cloudflare's
built-in image transformation capabilities by appending a
cf.image configuration object to a subrequest
fetch() call.
Developers can programmatically specify transformation properties directly in JavaScript:
- Format Conversion: Setting
format: 'avif'explicitly instructs the edge node to decode the source image and encode it into AVIF. - Dynamic Sizing: Developers can parse URL parameters
(such as
?width=800or?quality=80) and inject them into thecf.imageobject, allowing on-the-fly resizing and quality adjustments alongside format conversion. - Fallback Handling: If the client does not send
image/avifin theAcceptheader, the code can gracefully fall back toformat: 'webp'or retain the original format.
Edge Caching and Performance Gains
After the Worker initiates the transformation, Cloudflare handles the compute-heavy AVIF encoding across its distributed edge network. The resulting AVIF file is automatically cached in Cloudflare’s CDN tier based on the cache-control directives.
Subsequent requests from other AVIF-compatible browsers in the same geographic region are served directly from the edge cache, bypassing both the origin server and the compute cost of re-encoding. This programmatic edge workflow eliminates the need for pre-generating static AVIF variants during build steps or running dedicated image processing servers at the origin.