Add a cookie consent banner to a Magento store

Cookbook · platform Last verified View raw markdown (for agents)

In short: paste the live snippet as the first thing inside <head> in your theme's Magento_Theme/templates/root.phtml. That one template renders the head of every storefront page, ahead of RequireJS and your analytics tags.

Confirmed on a Magento Open Source store: the snippet is the first script in the rendered page's <head>, on the home page and on a CMS page.

You need #

Where it goes #

  1. Copy the live snippet (see above).

  2. Copy Magento's vendor/magento/module-theme/view/base/templates/root.phtml to app/design/frontend/<Vendor>/<theme>/Magento_Theme/templates/root.phtml (skip this if your theme already has that file).

  3. Paste the snippet as the first thing inside <head>, above the $requireJs line:

    <!doctype html>
    <html <?= /* @noEscape */ $htmlAttributes ?>>
        <head <?= /* @noEscape */ $headAttributes ?>>
            <!-- Cookie Compliance: first script on the page (paste live snippet here) -->
            <script>
                var huOptions = { "appID": "YOUR_APP_ID", "currentLanguage": "en", "blocking": true, "globalCookie": false };
            </script>
            <script src="https://cdn.hu-manity.co/v2/hu-banner.min.js" type="text/javascript" charset="utf-8"></script>
    
            <?= /* @noEscape */ $requireJs ?>
            <?= /* @noEscape */ $headContent ?>
            <?= /* @noEscape */ $headCritical ?>
            <?= /* @noEscape */ $headAssets ?>
            <?= /* @noEscape */ $headAdditional ?>
        </head>
    
  4. Flush the cache: bin/magento cache:flush. Your analytics and other tags stay as they are; the banner holds the recognised ones until the visitor chooses, in regions whose rule requires consent first.

What the order controls #

The banner holds recognised trackers that load after it until the visitor chooses, in regions whose rule requires consent first. A script placed above the snippet runs straight away, and a script you mark data-hu-category="1" is treated as essential. What runs before consent is your decision, so keep analytics and pixels below the snippet.

Confirm the result #

Open the home page and one inner page (for example Privacy and Cookie Policy), then view the page source (not the browser's Elements panel): the huOptions script and hu-banner.min.js are the first two <script> tags in <head>, with no async or defer, followed by Magento's RequireJS scripts and your analytics tag.

Then run the browser checks in plain-html in a private window (banner shows, no tracking cookies before the visitor chooses in a region whose rule requires consent first, trackers start after Allow) and, for the full procedure, verify-install. Test from a region your strictest rule covers (for example the EU), or confirm region rules are off.

Gotchas #

More help #