GDPR and disabling Sitecore Tracker lead to Exception in Sitecore.Analytics.Media.MediaRequestEventHandler.OnMediaRequest

As many Europe-based businesses we had to comply with GDPR legislation, which requires us to not track analytical data from visitors without their consent.
When it comes to Sitecore 8.x, this requires to implicitly stop the Sitecore Tracker from initializing unless the corresponding Conseny Cookie has been accepted:
    if (Request.Cookies["our_analytics_cookie_name"] != null) {
        Tracker.Initialize();
        Tracker.Current.StartTracking();
        Tracker.Enabled = true;
    } else {
    Tracker.Enabled = false;
    // and more code to force the expiration of the SC_ANALYTICS_GLOBAL_COOKIE
    }
So, problem solved right? Well, not exactly, because in the Sitecore Config, Xdb.Enabled is still true; this comes with the unfortunate side-effect that Sitecore _expects_ the Tracker object to be instantiated.
This results in the following Exception:
Exception: System.InvalidOperationException
Message: Tracker.Current is not initialized
Source: Sitecore.Analytics
   at Sitecore.Analytics.Media.MediaRequestEventHandler.OnMediaRequest(Object sender, EventArgs args)
And we had this exception flood our logs every time a user that did not accept the Analtyics Cookie wanders around the website.
The solution was intercepting the `media:request` event and executing a custom event that inherits from `Sitecore.Analytics.Media.MediaRequestEventHandler`; if the `Sitecore.Analytics.Tracker.Current` object is null, which is what happens when the Tracking is disabled, the event will return harmleslly; otherwise, the base OnMediaRequest from `Sitecore.Analytics.Media.MediaRequestEventHandler` will be invoked, now with no risk of an exception being thrown.
public class MediaRequestEventHandler : Sitecore.Analytics.Media.MediaRequestEventHandler {
    public override void OnMediaRequest(object sender, EventArgs args) {
        if (Sitecore.Analytics.Tracker.Current == null) {
            return;
        }
        base.OnMediaRequest(sender, args);
    }
}
We will then handle the media:request Event overriding’s Sitecore handling:
<handler patch:instead="handler[@type='Sitecore.Analytics.Media.MediaRequestEventHandler, Sitecore.Analytics']"
type="Sitecore.Foundation.MediaFiles.Handlers.MediaRequestEventHandler, Sitecore.Foundation.MediaFiles" method="OnMediaRequest" />
And this will prevent further exceptions from being needlessly logged.

Leave Comment