User privacy is a fundamental requirement in building responsible digital experiences. With regulations like the General Data Protection Regulation (GDPR) in the EU and the California Consumer Privacy Act (CCPA) in the U.S., websites must handle cookie consent properly especially for analytics and personalization purposes.

This article explains how to manually integrate OneTrust, a Consent Management Platform (CMP), with Sitecore 10.4. The implementation uses JavaScript on the frontend and the IConsentManager interface on the backend to provide full control over Sitecore’s analytics tracking based on user consent.

Implementation Goal

  • Load only strictly necessary cookies on initial page load.
  • Enable Sitecore’s analytics cookie (SC_ANALYTICS_GLOBAL_COOKIE) only if the user provides explicit consent.
  • Synchronize consent state between OneTrust and Sitecore programmatically.

Cookies used in this solution are grouped into two categories:

1. Necessary Cookies

  • SC_TRACKING_CONSENT: A Sitecore-generated cookie that stores the user’s consent state. This is essential for managing analytics and is always loaded.

2. Analytics Cookies

  • SC_ANALYTICS_GLOBAL_COOKIE: Used by Sitecore to identify unique visitors and track their behavior. Should only be created if the user accepts analytics cookies.

Technical Implementation

OneTrust Script

For this tutorial, the OneTrust script was manually added to the main layout file in Sitecore (Default.cshtml), before the closing </head> tag:

<script type="text/javascript" src="https://cdn.cookielaw.org/consent/YOUR_SCRIPT_ID.js" 
charset="UTF-8"
data-document-language="true">
</script>

This script initializes the cookie consent banner and controls cookie categories.

To manage user consent in Sitecore, we created a custom MVC controller using the IConsentManager interface. This allows explicit consent to be granted or revoked via HTTP PATCH requests.

using Sitecore.Analytics.Tracking.Consent;

public class TrackingConsentController : Controller
{
private readonly IConsentManager _consentManager;

public TrackingConsentController(IConsentManager consentManager)
{
this._consentManager = consentManager;
}

[HttpPatch]
public ActionResult GiveConsent()
{
this._consentManager.GiveConsent(null);

return new JsonResult()
{
Data = new { Message = "Consent has been granted" }
};
}

[HttpPatch]
public ActionResult RevokeConsent()
{
this._consentManager.RevokeConsent(null);

return new JsonResult
{
Data = new { Message = "Consent has been revoked" }
};
}
}

On the frontend, we implemented a script that listens for OneTrust consent events and synchronizes the consent status with Sitecore via AJAX.

🔗 View the full source code on GitHub

javascriptCopyEdit(function ($) {
    function hasSitecoreConsent() {
        const match = document.cookie.match(/(?:^|;\s*)SC_TRACKING_CONSENT=([^;]+)/);
        if (!match) return false;

        try {
            let decoded = atob(match[1]);
            decoded = decoded.replace(/[^}\]]*$/, "");
            const consentList = JSON.parse(decoded);
            return consentList.some(e => e.IsConsentGiven === true);
        } catch (e) {
            console.warn("Error parsing SC_TRACKING_CONSENT:", e);
            return false;
        }
    }

    function ApplyScAnalyticsConsent() {
        if (typeof window.OptanonActiveGroups !== "string" || OptanonActiveGroups === "0") return;

        const scGroup = GetOneTrustCategory("SC_ANALYTICS_GLOBAL_COOKIE");
        const hasConsent = OptanonActiveGroups.includes(scGroup);
        const alreadyGiven = hasSitecoreConsent();

        if (hasConsent !== alreadyGiven) {
            const url = hasConsent
                ? '/api/metadata/giveconsent'
                : '/api/metadata/revokeconsent';

            $.ajax({
                type: 'PATCH',
                url: url,
                success: function (response) {
                    console.log(response.Message);
                },
                error: function (jqxhr, settings, ex) {
                    console.error("Error applying consent:", ex);
                }
            });
        }
    }

    window.addEventListener("OneTrustGroupsUpdated", function () {
        ApplyScAnalyticsConsent($);
    });
})(jQuery);

This JavaScript code manages the synchronization of user cookie consent between OneTrust and Sitecore. It listens for the OneTrustGroupsUpdated event, which is triggered when a user updates their cookie preferences, and then compares OneTrust’s consent state with Sitecore’s. If there’s a mismatch, it sends a request to Sitecore to either give or revoke consent accordingly.

The function hasSitecoreConsent() checks if the Sitecore consent cookie (SC_TRACKING_CONSENT) exists and is valid. It decodes the cookie value from base64, parses it into a JSON object, and determines whether consent has already been given. This helps avoid unnecessary updates when both systems are already in sync.

Finally, if a change is needed, the script sends a PATCH request using jQuery to either /api/metadata/giveconsent or /api/metadata/revokeconsent. This ensures Sitecore accurately reflects the user’s preferences as stored in OneTrust, maintaining both compliance with privacy regulations and consistency in user tracking behavior.

Leave a Reply

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