Optimizing Performance with Cloudflare Image Transformation

Large, unoptimized images are the primary enemy of Core Web Vitals. By offloading image manipulation to Cloudflare, we can serve perfectly sized, next-gen formats (WebP/AVIF) without taxing our Optimizely CMS servers.


Step-by-Step Implementation

1. Create the Url Builder Extension

First, create a robust extension method to handle the URL rewriting. This ensures we only apply transformations to appropriate assets.

File: CmsIv.Web/Business/Extensions/UrlExtensions.cs

C#
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using System.Web;

namespace CmsIv.Web.Business.Extensions
{
    public static class UrlExtensions
    {
        public static string GetCloudflareUrl(this ContentReference imageRef, int width, int quality = 80)
        {
            if (ContentReference.IsNullOrEmpty(imageRef)) return string.Empty;

            var urlResolver = ServiceLocator.Current.GetInstance<EPiServer.Web.Routing.IUrlResolver>();
            var originalUrl = urlResolver.GetUrl(imageRef);

            // Ensure we are working with a valid relative path
            if (string.IsNullOrEmpty(originalUrl)) return string.Empty;

            // Cloudflare Image Resizing syntax: /cdn-cgi/image/format=auto,width={width},quality={quality}/{path}
            return $"/cdn-cgi/image/format=auto,width={width},quality={quality}{originalUrl}";
        }
    }
}

2. Implement in Razor Views

Update your views to request the exact size needed for the container.

File: CmsIv.Web/Views/Shared/Blocks/HeroBlock.cshtml

HTML
@using CmsIv.Web.Business.Extensions
@model CmsIv.Web.Models.Blocks.HeroBlock

<img src="@Model.HeroImage.GetCloudflareUrl(1200)"
     alt="@Model.Heading"
     width="1200"
     height="600"
     loading="eager"
     fetchpriority="high" />


Common Errors and Solutions

Error Cause Solution
"Image Resizing is Disabled" Feature isn't enabled in Cloudflare Dashboard. Go to Speed > Optimization > Image Resizing and enable it.
Broken Images on Localhost Cloudflare cannot fetch images from localhost. Wrap logic in !IsDevelopment() check or use a tunnel like Ngrok.
Cumulative Layout Shift (CLS) Loading images without explicit dimensions. Always strictly define width and height attributes in HTML.

Best Practices

  • Do: Use format=auto to let Cloudflare serve AVIF to Chrome users and WebP to others.

  • Do: Create specific breakpoints (e.g., Mobile: 400px, Tablet: 800px, Desktop: 1200px) rather than 1:1 user-agent matching.

  • Don't: Apply resizing to SVG or GIF files, as this can break animations or vector quality.


Verification

To verify the implementation:

  1. Open the Network tab in Chrome DevTools.

  2. Inspect the image request headers.

  3. Look for cf-bg-managed: img or content-type: image/avif.

  4. Confirm the file size is significantly smaller than the original asset in the CMS.

 

← Quay lại Blog