> For the complete documentation index, see [llms.txt](https://docs.adpage.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.adpage.io/integrations-websites/shopify/installing-adpage-on-a-shopify-markets-store.md).

# Installing AdPage on a Shopify Markets store

A Shopify Markets store needs a different AdPage setup: each market gets its own GTM container and tagging domain, selected in the theme code instead of in the AdPage app.

Shopify Markets lets you sell in several countries or regions from one Shopify store, each market on its own domain. Two things don't work the standard way. The AdPage Shopify app can't store different settings per domain, and Shopify only lets you create one order webhook for the whole store. This article covers only the steps that differ from the standard implementation.

### Before you start

Duplicate your live theme first (Online Store → Themes → Actions (…) → Duplicate), so you can roll back if needed.

Collect these values for every market:

| Placeholder            | What to fill in                                                               | Example                      |
| ---------------------- | ----------------------------------------------------------------------------- | ---------------------------- |
| \[LANGUAGE CODE]       | The market's language code, as Shopify returns it in request.locale.iso\_code | de                           |
| \[SERVER URL]          | The market's tagging URL, including https\://                                 | <https://tagging.example.de> |
| \[SERVER DOMAIN]       | The same tagging domain, without https\://                                    | tagging.example.de           |
| \[LOADER ID]           | The custom loader ID, if the container uses one                               | Leave empty ('') if not used |
| \[GTM-ID]              | The market's GTM web container ID                                             | GTM-ABC1234                  |
| \[GTM-ID without GTM-] | The same ID without the GTM- prefix                                           | ABC1234                      |
| \[STORE DOMAIN]        | The market's storefront domain                                                | example.de                   |

The theme code selects the container by language code, so every market must use a different language.

### Step 1: Add the Cookie Keeper script

Go to Online Store → Themes → Actions (…) → Edit code and open theme.liquid. Paste the script below in the \<head> section, above the Google Tag Manager code.

The script stores a visitor ID in the \_taggingmk cookie and keeps a backup in localStorage, so the ID is restored if the cookie disappears.

```html
<script type="text/javascript">
(function() {
    'use strict';
    
    // Generate UUID v4 (compatible method)
    function mkTagging_generateUUID() {
        // Fallback for older browsers without crypto API
        if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
            return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, function(c) {
                return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
            });
        } else {
            // Less secure fallback for very old browsers
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0;
                var v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    }
    
    // Get cookie value by name
    function mkTagging_getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    
    // Set cookie with expiration
    function mkTagging_setCookie(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        // Set both path and SameSite for better compatibility
        document.cookie = name + "=" + value + expires + "; path=/; SameSite=Lax";
    }
    
    // Safe localStorage wrapper
    function mkTagging_getLocalStorage(key) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                return localStorage.getItem(key);
            }
        } catch (e) {
            // localStorage might be blocked or unavailable
            console.log('localStorage not available:', e);
        }
        return null;
    }
    
    function mkTagging_setLocalStorage(key, value) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                localStorage.setItem(key, value);
                return true;
            }
        } catch (e) {
            // localStorage might be blocked or unavailable
            console.log('localStorage not available:', e);
        }
        return false;
    }
    
    // Main initialization function
    function mkTagging_initVisitorId() {
        var cookieName = '_taggingmk';
        var storageKey = '_taggingmk_backup';
        var visitorId = null;
        
        // 1. Check if cookie exists
        visitorId = mkTagging_getCookie(cookieName);
        
        // 2. If no cookie, check localStorage backup
        if (!visitorId) {
            visitorId = mkTagging_getLocalStorage(storageKey);
            
            // If found in localStorage but not in cookie, restore the cookie
            if (visitorId) {
                mkTagging_setCookie(cookieName, visitorId, 365);
                console.log('MK Tagging: Visitor ID restored from localStorage:', visitorId);
            }
        }
        
        // 3. If still no ID, generate a new one
        if (!visitorId) {
            visitorId = mkTagging_generateUUID();
            mkTagging_setCookie(cookieName, visitorId, 365);
            console.log('MK Tagging: New visitor ID generated:', visitorId);
        }
        
        // 4. Always sync to localStorage as backup (if available)
        if (mkTagging_setLocalStorage(storageKey, visitorId)) {
            console.log('MK Tagging: Visitor ID backed up to localStorage');
        }
        
        // Return the visitor ID for potential use
        return visitorId;
    }
    
    // Run on DOM ready or immediately if already loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', mkTagging_initVisitorId);
    } else {
        // DOM is already loaded
        mkTagging_initVisitorId();
    }
    
    // Create a namespaced object for any exposed functionality
    window.mkTagging = window.mkTagging || {};
    window.mkTagging.getVisitorId = function() {
        return mkTagging_getCookie('_taggingmk') || mkTagging_getLocalStorage('_taggingmk_backup');
    };
    
})();
</script>
```

### Step 2: Add the GTM head code

Paste the code below directly after the Cookie Keeper script, still in the \<head> section. It loads the right GTM container for each market through that market's tagging domain. It also passes consent updates from your cookie banner to Shopify's Customer Privacy API.

Replace \[LANGUAGE CODE], \[GTM-ID], \[SERVER URL] and \[LOADER ID] for each market. The example has three markets: add or remove a when block (four lines) to match your number of markets.

```liquid
{%- case request.locale.iso_code -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
{%- endcase -%}

<script>
  window.trytagging_new_version = {% if loader_id != blank %}true{% else %}false{% endif %};
  window.dataLayerName = "dataLayer";
  window[window.dataLayerName] = window[window.dataLayerName] || [];
  window.trytagging_disable_order_notes = true;
</script>

<script>
  (function () {
    function t(t, e, r) {
      if ("cookie" === t) {
        var n = document.cookie.split(";");
        for (var o = 0; o < n.length; o++) {
          var i = n[o].split("=");
          if (i[0].trim() === e) return i[1];
        }
      } else if ("localStorage" === t) return localStorage.getItem(e);
      else if ("jsVariable" === t) return window[e];
      else console.warn("invalid uid source", t);
    }
    function e(e, r, n) {
      var o = document.createElement("script");
      (o.async = !0), (o.src = r), e.insertBefore(o, n);
    }
    function r(r, n, o, i, a) {
      var c,
        s = !1;
      try {
        var u = navigator.userAgent,
          f = /Version\/([0-9\._]+)(.*Mobile)?.*Safari.*/.exec(u);
        f && parseFloat(f[1]) >= 16.4 && ((c = t(o, i, "")), (s = !0));
      } catch (t) {
        console.error(t);
      }
      var l = (window[a] = window[a] || []);
      l.push({ "gtm.start": new Date().getTime(), event: "gtm.js" });

      var dl = a != "dataLayer" ? "&l=" + a : "";

      var g =
          r +
          "{% if loader_id != blank %}/{{ loader_id }}.js?sp={{ gtm_id | remove: 'GTM-' }}{% else %}/script.js?id={{ gtm_id | remove: 'GTM-' }}{% endif %}" +
          (s ? "&enableCK=true" : "") +
          (c ? "&mcookie=" + encodeURIComponent(c) : "") +
          dl,
        d = document.getElementsByTagName("script")[0];
      e(d.parentNode, g, d);
    }
    r(
      "{{ tagging_url }}",
      "{{ gtm_id | remove: 'GTM-' }}",
      "undefined",
      "undefined",
      window.dataLayerName
    );
  })();

const dataLayerName = window.dataLayerName ?? "dataLayer";
let hasSentConsent = false;

if (window[dataLayerName]) {
  const originalDataLayerPush = window[dataLayerName].push;

  window[dataLayerName].push = (...args) => {
    originalDataLayerPush.apply(window[dataLayerName], args);

    try {
      if (args[0][0] === "consent" && args[0][1] === "update") {
        const consentArgs = {
          analytics: args[0][2].analytics_storage === "granted",
          marketing:
            args[0][2].ad_storage === "granted" &&
            args[0][2].ad_personalization === "granted" &&
            args[0][2].ad_user_data === "granted",
          preferences: args[0][2].personalization_storage === "granted",
          sale_of_data: args[0][2].ad_user_data === "granted",
        };

        // Wait for the consent to be set
        if (!hasSentConsent) {
          window.Shopify.loadFeatures(
            [
              {
                name: "consent-tracking-api",
                version: "0.1",
              },
            ],
            function (error) {
              if (error) console.error("Error loading consent-tracking-api", error);
              window.Shopify.customerPrivacy.setTrackingConsent(
                consentArgs,
                () => {}
              );
            }
          );
          hasSentConsent = true;
        }
      }
    } catch (error) {
      console.error("Error setting tracking consent", error);
    }
  };
}
</script>
```

### Step 3: Update the body section

In the same theme.liquid file, find the GTM code directly after the opening \<body> tag and replace it with the code below. It adds the noscript fallback and loads the AdPage Shopify dataLayer script from the market's tagging domain.

Replace \[LANGUAGE CODE], \[GTM-ID] and \[SERVER URL] with the same values as in step 2. Add or remove a when block (three lines) to match your number of markets.

```liquid
{%- case request.locale.iso_code -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
{%- endcase -%}

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="{{ tagging_url }}/ns.html?id={{ gtm_id }}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager -->

<script>
  (function() {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.defer = true;
    script.src = "{{ tagging_url }}/shopify-datalayer-minified.js";

    script.onerror = () => {
      console.error("Tagging Data Layer: JS script failed to load");
    };

    script.onload = async () => {
      window.taggingHelpers.updateShopSettings(({{- page_title | json -}}), {{- cart.currency.iso_code | json -}});
      await window.taggingHelpers.initFetching();
      window.taggingHelpers.userDataWithCart({{- cart | json -}});

      {%- if collection and template.name == "collection" -%}
      const listId = {{- collection.id | json -}};
      const listName = {{- collection.title | json -}};
      const items = [
        {%- assign itemIndex = 1 -%}
        {%- for product in collection.products -%}
        {%- for variant in product.variants limit:1 -%} {
          item_id : {{- variant.id | json -}},
          item_name: {{- product.title | json -}},
          item_brand: {{- product.vendor | json -}},
          item_category: {{- product.type | json -}},
          item_variant: {{- variant.title | json -}},
          item_sku: {{- variant.sku | json -}},
          price: "{{- product.price | times: 0.01 | json -}}",
          position: {{- itemIndex -}},
          item_variant_id: {{- variant.id | json -}},
          item_product_id: {{- product.id | json -}},
          item_image: {{- product.featured_image | json -}},
          handle: {{- product.handle | json -}}
        },
        {%- endfor -%}
        {%- assign itemIndex = itemIndex | plus: 1 -%}
        {%- endfor -%}];
      window.taggingHelpers.viewItemList(listId, listName, items);
      window.taggingHelpers.bindListItems(listId, listName, items);
      {%- endif -%}

      {%- if product -%}
      const item = {
        {% assign default_variant = product.selected_or_first_available_variant %}
        {%- if default_variant != blank -%}
        defaultVariant : {
          item_id : {{- default_variant.id | json -}},
          item_name: {{- product.title | json -}},
          item_brand: {{- product.vendor | json -}},
          item_category: {{- product.type | json -}},
          item_variant: {{- default_variant.title | json -}},
          item_sku: {{- default_variant.sku | json -}},
          price: "{{- default_variant.price | times: 0.01 | json -}}",
          item_product_id: {{- product.id | json -}},
          item_variant_id: {{- default_variant.id | json -}},
          compareAtPrice: "{{- default_variant.compare_at_price | times: 0.01 | json -}}",
          item_image: {{- product.featured_image | json -}},
          currency: {{- cart.currency.iso_code | json -}},
        },
        {%- else -%}
        defaultVariant : null,
        {%- endif -%}
        items: [
          {%- for variant in product.variants -%} {
            item_id : {{- variant.id | json -}},
            item_name: {{- product.title | json -}},
            item_brand: {{- product.vendor | json -}},
            item_category: {{- product.type | json -}},
            item_variant: {{- variant.title | json -}},
            item_sku: {{- variant.sku | json -}},
            price: "{{- variant.price | times: 0.01 | json -}}",
            item_product_id: {{- product.id | json -}},
            item_variant_id: {{- variant.id | json -}},
            compareAtPrice: "{{- variant.compare_at_price | times: 0.01 | json -}}",
            item_image: {{- product.featured_image | json -}}
          },
          {%- endfor -%}],
      };
      const value = item.defaultVariant?.price ?? item.items[0].price;
      window.taggingHelpers.viewItem(item, value);
      {%- endif -%}

      {%- if request.page_type == "cart" -%}
      window.taggingHelpers.handleViewCart();
      {%- endif -%}

      window.taggingHelpers.init();
    }

    document.body.appendChild(script);
  })();
</script>
```

### Step 4: Add the Customer Events pixel

Go to Settings → Customer events → Add custom pixel and create a new pixel with the code below. This pixel handles tracking in the checkout, where the theme code doesn't run.

Replace \[SERVER DOMAIN], \[STORE DOMAIN], \[GTM-ID] and \[GTM-ID without GTM-]. Note: here \[SERVER DOMAIN] goes in without https\://, because the code adds it. In apShopifyConfig at the top, fill in your main market. Add or remove an if block to match your number of markets.

If one store domain contains another (for example example.com and shop.example.com), put the longer domain first.

```javascript
const apShopifyConfig = {
  version: "1.0.0",
  cookieKeeperType: "cookie",
  cookieKeeperStorageName: "_taggingmk",
  domain: "[SERVER DOMAIN]",
  pixelId: "[GTM-ID]",
};
const page_location = init?.context?.document?.location?.href ?? "";
const load_pixel =
  page_location.includes("checkout") || page_location.length === 0;

function getShopConfig() {
  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  return apShopifyConfig;
}

if (load_pixel) {
  (function () {
    function t(t, e, r) {
      if ("cookie" === t) {
        var n = document.cookie.split(";");
        for (var o = 0; o < n.length; o++) {
          var i = n[o].split("=");
          if (i[0].trim() === e) return i[1];
        }
      } else if ("localStorage" === t) return localStorage.getItem(e);
      else if ("jsVariable" === t) return window[e];
      else console.warn("invalid uid source", t);
    }
    function e(e, r, n) {
      var o = document.createElement("script");
      (o.async = !0), (o.src = r), e.insertBefore(o, n);
    }
    function r(r, n, o, i, a) {
      var c,
        s = !1;
      try {
        var u = navigator.userAgent,
          f = /Version\/([0-9\._]+)(.*Mobile)?.*Safari.*/.exec(u);
        f && parseFloat(f[1]) >= 16.4 && ((c = t(o, i, "")), (s = !0));
      } catch (t) {
        console.error(t);
      }
      var l = (window[a] = window[a] || []);
      l.push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
      var g =
          r +
          "/Q1dUWlEmZW52.js?tg=" +
          n +
          (s ? "&enableCK=true" : "") +
          (c ? "&mcookie=" + encodeURIComponent(c) : ""),
        d = document.getElementsByTagName("script")[0];
      e(d.parentNode, g, d);
    }
    r(
      `https://${getShopConfig().domain}`,
      getShopConfig().truncatedPixelId,
      "cookie",
      "_taggingmk",
      "dataLayer"
    );
  })();
}

const execute = async (api) => {
  if (load_pixel) {
    console.log(`Loading pixel for ${getShopConfig().domain}`);
    const scriptUrl = `https://${getShopConfig().domain}/pixel-minified.js`;
    try {
      if (scriptUrl) {
        const module = await import(scriptUrl);
        module.default(api, getShopConfig());
      }
    } catch (e) {
      console.error(e);
    }
  }
};

execute({ analytics, browser, init });
```

Save the pixel and click Connect to activate it.

### Step 5: Set up the webhook and the RegEx Table variable

Shopify doesn't let you create a separate manual webhook per market domain. Create one webhook for /order\_created in the Shopify backend.

As a result, the server container and Google Tag Manager receive every webhook from one domain, even though the orders were placed on different market domains.

In Google Tag Manager, don't base your RegEx Table variable on marketing.hostname, as you would for a standard Shopify store. Use parsed\_data.order\_status\_url as its input instead. This URL contains the domain of the market where the order was placed.

The input is now a full URL instead of a hostname. If your RegEx Table patterns match exact hostnames, untick Full matches only under Advanced Settings, or adjust the patterns (for example `.*example\.de.*`).

### Step 6: Check the implementation

Check the following on every market domain:

* Browser console: no JavaScript errors.
* Cookies: the \_taggingmk cookie is created.
* Network tab: requests go to the tagging domain of that market.
* GTM preview: after a test order, the RegEx Table variable returns the value for the market where the order was placed.

### Step 7: Uninstall the AdPage app

Only do this after step 6 confirms that all tracking works with the new implementation.

1. Go to Apps → AdPage.
2. Click Uninstall app or Disable app.
3. Confirm.

The app is no longer needed, because tracking now runs fully through the server-side implementation. No AdPage app installed? Skip this step.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.adpage.io/integrations-websites/shopify/installing-adpage-on-a-shopify-markets-store.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
