Development

Optimizing Performance with Cloudflare Image Transformation

By Ginbok2 min read

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


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.

 

#CoreWebVitals#WebPerformance#ImageOptimization#Cloudflare#Optimizely#CSharp#WebDev
← Back to Articles
SEO Title: Boost Optimizely Performance with Cloudflare Image Resizing - Ginbok