Episerver Personalization: Geolocation based on Cloudflare HTTP header

As we all know all DXP environments use Cloudflare as CDN. There are loads of functionality that Cloudflare provides out-of-the-box and GeoLocation header is one of them. Episerver enable this header by default in all DXP environments (https://world.episerver.com/

episerver Geolocation of user

Why not MaxMind IP database?

Although Episerver provides us with a separate NuGet package called EPiServer.Personalization.MaxMindGeolocation that uses MaxMind GeoLite2 database but there are still advantages of using Cloudflare HTTP header such as

  • It’s always up-to-date
  • It does not base on a lite version
  • You can use it in client-side scripting & does not always need server-side scripting.
  • It’s lightweight as compared to finding a record in App hosted CSV file.

But there are few scenarios where you can not use http header

  • HTTP header just gives you visitor’s country ISO code. Unlike the MaxMind database, it does not give city information.

Visitor Group Criteria

Cloudflare Geo location Model

    [EPiServerDataStore(AutomaticallyCreateStore = true, AutomaticallyRemapStore = true)]
    public class CloudflareGeolocationModel : CriterionModelBase
        public string CountryCode { get; set; }
        public override ICriterionModel Copy()
            return ShallowCopy();

Cloudflare Geo location Criterion

        Category = "Visitor Groups",
        DisplayName = "Cloudflare Geolocation",
        Description = "Geolocation based on Cloudflare HTTP header")]
    public class CloudflareGeolocationCriterion : CriterionBase<CloudflareGeolocationModel>
        public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
            // uncomment if you want this Criterion to apply only to Authenticated users
            //if (principal == null || !principal.Identity.IsAuthenticated) return false;
            var geolocationHeader = httpContext.Request?.Headers["CF-IPCountry"];
            return Model.CountryCode.ToLower() == geolocationHeader.ToLower();

Source Code: The source code of this Episerver personalization criteria can be downloaded from this link.

About the author

Naveed Ul-Haq

I am a UK-based Technical Architect, Founder & Technology Evangelist. I'm Optimizely MVP & Optimizely SME on Content Cloud and Commerce Cloud. I love working on .NET-based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I'm also a Certified Optimizely Content Cloud Developer, Certified Optimizely Commerce Cloud developer, Optimizely B2B Commerce developer and Microsoft Certified Professional in Azure application development. I spend my free time with my family and reading books. You can contact me at hello@naveedulhaq.com

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *