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/
documentation/developer-guides/CMS/Deployment/content-delivery-network-cdn-configuration/)

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
    {
        [DojoWidget]
        public string CountryCode { get; set; }

        public override ICriterionModel Copy()
        {
            return ShallowCopy();
        }
    }

Cloudflare Geo location Criterion

    [VisitorGroupCriterion(
        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. I love working with .NET based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I am a Certified Episerver CMS developer, MCSD (Microsoft Certified Solution Developer) and MCP in Azure application development. I spend my free time with my family and reading books. You can contact me on [email protected]

View all posts

Leave a Reply

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