Hugo Santos - Head of Search Practice
17 Aug 2023
Introduction
As businesses seek to optimize their technology investments, migrating from Sitecore XP to Sitecore XM has become attractive, offering cost reduction and greater budget efficiency. However, in this migration, one of the primary concerns for clients is the loss of some advanced analytics and personalization features available in Sitecore XP. These tools are crucial for enhancing user experiences and offering highly personalized content based on collected data.
The good news is, if you are facing this challenge, there is an effortless solution that might surprise you. In this blog post, we will explore how you can leverage the power of Google Analytics to obtain valuable data and utilize it for highly personalized content, even in a Sitecore XM environment. The best part? The implementation is simpler than you might think, especially considering that nearly every company in the world is already using Google Analytics.
How to Use Google Analytics with Sitecore?
Integrating Google Analytics with Sitecore XM is a smart strategy to bridge the gap in analytics and personalization. Google provides a NuGet package that simplifies access to its APIs through .NET projects. You can find the required package here.
Before we dive into the implementation details, there is a crucial step to configure Google Analytics properly. You need to set up access credentials for the Google Analytics APIs, and this requires adding an environment variable to your Windows system. This variable will point to the JSON file containing the credentials for your Google Analytics account.
Configuring Google Analytics
Once you have obtained the necessary credentials and set up the environment variable, we can proceed with configuring Google Analytics for use in your Sitecore XM environment. The credentials will grant your application the necessary permissions to access data from your specific Google Analytics account.
With the environment variable set up, your application will be able to access the Google Analytics APIs seamlessly.
Creating the Management Class
With the configuration complete, we will develop a custom management class that enables seamless interaction between your project and Google Analytics. This class will make precise requests, defining the necessary filters, dimensions, and metrics to obtain the desired data from Google Analytics.
The approach to obtaining the most popular articles using Google Analytics instead of Sitecore Analytics is highly efficient. We will use the Sitecore search API to obtain a comprehensive list of all articles on the site. Then, we will use the URLs of these articles as keys to obtain the pageview count from Google Analytics. We will organize this information to identify the Top X most accessed pages, and we will do this for each language on the site.
public class KonabosGoogleAnalyticsManagerGA4 { private readonly string GoogleAnalyticsPropertyId; private readonly string GoogleAnalyticsNewsInterval; public KonabosGoogleAnalyticsManagerGA4(string googleAnalyticsPropertyId) { this.GoogleAnalyticsPropertyId = googleAnalyticsPropertyId; this.GoogleAnalyticsNewsInterval = Settings.GetSetting("GoogleAnalyticsNewInterval", "15") + "daysAgo"; } public IList<KonabosArticleDto> GetMostPopularArticles(int maxResults, Language language) { var articlesResult = this.SearchArticlesByLanguage(language); var articleUrls = articlesResult.Articles.Select(post => post.UrlByLanguage); var pageViewEvents = new List<KonabosPageViewdDto>(); var postUrlsBatches = articleUrls.Batch(100); foreach (IEnumerable<string> postUrlsBatch in postUrlsBatches) pageViewEvents.AddRange(this.FetchPageViewsByUrls(postUrlsBatch.ToList())); var topPageViewedEvents = pageViewEvents .OrderByDescending(post => post.PageViews) .Take(maxResults) .ToList(); var postsDic = articlesResult.Articles.ToDictionary(post => post.UrlByLanguage); var topPageViewedArticles = topPageViewedEvents.Select(page => postsDic[page.ItemUrl]).ToList(); return topPageViewedArticles; } private KonabosArticleResultsDto SearchArticlesByLanguage(Language language) { using (var context = ContentSearchManager.GetIndex("articles-index").CreateSearchContext()) { var queryable = context.GetQueryable<KonabosArticleIndexedItem>(); queryable = queryable.Filter(item => item.Language == language.Name); queryable = queryable.OrderByDescending(item => item.Date); var results = queryable.GetResults(); return KonabosArticleResultsFactory.Create(results); } } private IEnumerable<KonabosPageViewdDto> FetchPageViewsByUrls(IList<string> urls) { BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); RunReportRequest request = new RunReportRequest { Property = "properties/" + this.GoogleAnalyticsPropertyId, Dimensions = { new Dimension { Name = "pagePath" } }, Metrics = { new Metric { Name = "screenPageViews" } }, DateRanges = { new DateRange { StartDate = GoogleAnalyticsNewsInterval, EndDate = "today" } }, }; var fiterExpressionByUrls = new FilterExpression(); fiterExpressionByUrls.OrGroup = new FilterExpressionList(); if (urls != null && urls.Count() > 0) { var filtersExpression = ""; for (int i = 0; i < urls.Count(); i++) { var url = urls[i]; if (!string.IsNullOrEmpty(url)) { if (i > 0) filtersExpression += ","; filtersExpression += $"pagePath=={url}"; var filterExpression = new FilterExpression { Filter = new Filter { FieldName = "pagePath", StringFilter = new Filter.Types.StringFilter { Value = url } } }; fiterExpressionByUrls.OrGroup.Expressions.Add(filterExpression); } } request.DimensionFilter = fiterExpressionByUrls; } var response = client.RunReport(request); var pagesViewed = ExtractPageViewedItems(response); return pagesViewed; } private IEnumerable<KonabosPageViewdDto> ExtractPageViewedItems(RunReportResponse response) { foreach (Row row in response.Rows) { if (row.DimensionValues?.Count > 0 && row.MetricValues?.Count > 0) { Int32.TryParse(row.MetricValues[0].Value, out int pageViews); var pageViewed = new KonabosPageViewdDto() { PageViews = pageViews, ItemUrl = row.DimensionValues[0].Value }; yield return pageViewed; } } } }
Optimizing Performance
With the process of obtaining the Top X most accessed pages in place, we can further enhance your site's performance. The call to Google Analytics doesn't need to be made for every new page view, as this operation can be relatively heavy when dealing with data from all previously viewed pages.
A simple yet effective solution is to create a scheduled task in Sitecore responsible for making this call only once a day. The results of the Top X most viewed news can be stored in a Sitecore item. Subsequently, pages that need to display this information can simply fetch the data from the Sitecore item and present it on the screen using the appropriate rendering.
Conclusion: Leveraging the Power of Google Analytics for Effortless Personalization
Migrating to Sitecore XM offers numerous advantages, and by leveraging Google Analytics with our guidance, you don't need to forgo powerful analytics and personalization tools. Embrace the power of this integration to offer personalized and relevant experiences to your users while maintaining efficiency and performance on your site.
Our team of experts is ready to guide you through this journey, ensuring your transition from Sitecore XM to XP is successful and that you continue to provide exceptional experiences to your clients. Take advantage of our expertise and unlock extraordinary results for your Sitecore implementation. To learn more about how Konabos can help you, contact us today!
Hugo specializes in search and automation, including testing automation. He is bright, amiable, and energetic. As a Sitecore Architect, he is passionate about creating great solutions that don't just follow best practices but further them. His passion for doing great work is equaled only by his willingness to share his expertise with the Sitecore community by blogging and advocacy, like helping to organize the Quebec Sitecore User Group while in Canada. Hugo is a four-time Sitecore Technology MVP, in recognition for all that he does for the Sitecore Community.
Share on social media