---
title: Installing in a Shopify Theme
slug: analytics-developer-docs/installing-in-a-shopify-theme
docTags: 
createdAt: 2024-03-13T18:41:38.313Z
---

## Requirements

Chord's Shopify theme analytics library assumes that a CDP Javascript library is already installed on the site. Segment's [analytics.js](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/) library is currently the only supported option. You can install Segment's [analytics.js](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/) by pasting [Segment's code snippet](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2b-add-the-segment-snippet) into the `<head>` tag of your theme. It should be added to every page of the site, so you'll likely choose to include it in `layout/theme.liquid` and `layout/checkout.liquid` (if using).

See [Segment's instructions](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2a-add-the-segment-snippet) for adding the code snippet. You can find the latest version of the Segment snippet in the **Overview** tab of your Javascript source in your Segment workspace.

Remove `analytics.page();` from the snippet after you paste it into your theme. Chord will handle calling `analytics.page();` and add some extra metadata.

## Installation

In the theme code, add create a Liquid file called `snippets/chord.liquid` and paste in this code:

::::CodeDrawer{title="chord.liquid" isResponseExpanded="false" autoGeneratedAnchorSlug="chordliquid" legacyHash="ZkUVGn9DiPvx5XAJEjnUf"}
:::CodeblockTabsExamples
Chord Liquid snippet

```html
<script>
  (function () {
    var CHORD_OMS_ID = '';
    var CHORD_STORE_ID= '';
    var CHORD_TENANT_ID = '';
    var STORE_DOMAIN = '';

    var chord = (window.chord = window.chord || []);
    if (chord.initialize) return;
    if (chord.invoked) return;
    chord.invoked = true;
    chord.methods = [
      'identify',
      'page',
      'reset',
      'track',
      'trackCartViewed',
      'trackCheckoutStarted',
      'trackCouponApplied',
      'trackCouponDenied',
      'trackCouponEntered',
      'trackCouponRemoved',
      'trackEmailCaptured',
      'trackProductAdded',
      'trackProductClicked',
      'trackProductListFiltered',
      'trackProductListViewed',
      'trackProductRemoved',
      'trackProductViewed',
      'trackProductsSearched',
      'trackSignedIn',
      'trackSignedOut',
      'trackSignedUp',
    ];
    chord.queue = [];
    chord.factory = function (method) {
      return function () {
        try {
          var args = Array.prototype.slice.call(arguments);
          args.unshift(method);
          chord.queue.push(args);
          return chord;
        } catch (e) {
          console.error('Could not track events from queue', e);
        }
      };
    };
    for (var i = 0; i < chord.methods.length; i++) {
      var key = chord.methods[i];
      chord[key] = chord.factory(key);
    }
    chord.load = function (options) {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src = 'https://cdn.chord.co/analytics-liquid/v1/analytics-liquid.min.js';
      var first = document.getElementsByTagName('script')[0];
      first.parentNode.insertBefore(script, first);
      chord._loadOptions = options;
    };
    chord.SNIPPET_VERSION = '0.1.0';
    chord.load({
      cdp: function() {
        return window.analytics;
      },
      metadata: {
        i18n: {
          currency: {{ cart.currency.iso_code | default: 'USD' | json }},
          locale: "{{ localization.language.iso_code | default: 'en' }}-{{ localization.country.iso_code | default: 'US' }}",
        },
        ownership: {
          omsId: CHORD_OMS_ID,
          storeId: CHORD_STORE_ID,
          tenantId: CHORD_TENANT_ID,
        },
        platform: {
          name: 'shopify',
          type: 'web',
        },
        store: {
          domain: STORE_DOMAIN,
        },
      },
      syncIdentifiers: {
        'Google Analytics 4': true
      }
    });
    chord.page();
    {% assign customer = checkout.customer | default: customer %}
    {% if customer.id %}
    chord.identify({{ customer.id | append: "" | json }}, {
      address: {
        city: {{ customer.default_address.city | json }},
        country: {{ customer.default_address.country | json }},
        firstName: {{ customer.default_address.first_name | json }},
        id: {{ customer.default_address.id | append: "" | json }},
        isDefault: true,
        lastName: {{ customer.default_address.last_name | json }},
        phone: {{ customer.default_address.phone | json }},
        postalCode: {{ customer.default_address.zip | json }},
        state: {{ customer.default_address.province | json }},
        street: {{ customer.default_address.address1 | json }},
        street2: {{ customer.default_address.address2 | json }},
      },
      company: {
        name: {{ customer.default_address.company | json }},
      },
      createdAt: {{ customer.created_at | json }},
      email: {{ customer.email | json }},
      firstName: {{ customer.first_name | json }},
      id: {{ customer.id | append: "" | json }},
      lastName: {{ customer.last_name | json }},
      name: {{ customer.name | json }},
      phone: {{ customer.phone | json }},
    });
    {% endif %}
    {% if checkout.id and order_completed %}
    if (window.Shopify?.Checkout?.page === 'thank_you') {
      chord.track('Order Completed', {
        checkout_id: {{ checkout.id | append: "" | json }},
        checkout_type: 'Shopify',
        coupon: {{ checkout.discount_applications | where: 'type', 'discount_code' | map: 'title' | first | json }},
        currency: {{ checkout.currency | json }},
        discount: {{ checkout.discounts_amount | money_without_currency | remove: "," | default: 0 }},
        email: {{ checkout.email | json }},
        first_name: {{ checkout.customer.first_name | json }},
        last_name: {{ checkout.customer.last_name | json }},
        order_date: {{ checkout.order.created_at | date: '%FT%T%:z' | json }},
        order_id: {{ checkout.order_id | append: "" | json }},
        order_number: {{ checkout.order_number | append: "" | json }},
        phone: {{ checkout.customer.phone | json }},
        revenue: {{ checkout.subtotal_price | money_without_currency | remove: "," | default: 0 }},
        shipping: {{ checkout.shipping_price | money_without_currency | remove: "," | default: 0 }},
        subtotal: {{ checkout.subtotal_price | money_without_currency | remove: "," | default: 0 }},
        tax: {{ checkout.tax_price | money_without_currency | remove: "," | default: 0 }},
        total: {{ checkout.total_price | money_without_currency | remove: "," | default: 0 }},
        products: [
          {% for line_item in checkout.line_items %}
            {
              brand: {{ line_item.vendor | json }},
              description: {{ line_item.product.description | strip_html | json }},
              image_url: {{ line_item | img_url | json }},
              name: {{ line_item.product.title | strip_html | json }},
              position: {{ forloop.index }},
              price: {{ line_item.original_price | money_without_currency | remove: "," | default: 0 }},
              product_id: {{ line_item.product_id | append: "" | json }},
              quantity: {{ line_item.quantity | default: 0 }},
              revenue: {{ line_item.original_line_price | money_without_currency | remove: "," | default: 0 }},
              sku: {{ line_item.sku | json }},
              slug: {{ line_item.product.handle | json }},
              url: {{ line_item.url | json }},
              variant: {{ line_item.variant.title | json }},
              variant_id: {{ line_item.variant_id | append: "" | json }},
            },
          {% endfor %}
        ],
      });
    }
    {% endif %}
  })();
</script>

```
:::

:::CodeblockTabsResponses
```javascript
```
:::
::::

### Add your store identifiers

Before the code is deployed to production, there are four variables at the top of the snippet that need to be updated with different values:

```text
var CHORD_OMS_ID = ''; // Chord will provide.
var CHORD_STORE_ID= ''; // Chord will provide.
var CHORD_TENANT_ID = ''; // Chord will provide.
var STORE_DOMAIN = ''; // comes before .myshopify.com
```

The value of `STORE_DOMAIN` should be the Shopify store name that comes before `.myshopify.com`. For example, if the store is `https://chord-store.myshopify.com`, it should be `chord-store`.

Chord will provide the values for the other three variables.

### Add snippet to your layout

Include the Chord snippet on every page of the Shopify theme by rendering it inside the `<head>` tag in `layout/theme.liquid`:

:::CodeblockTabs
layout/theme.liquid

```html
{% render 'chord' %}
```
:::

To add tracking events to Shopify checkout and send an "Order Completed" tracking event from the order confirmation page, render the Chord snippet inside the `<head>` tag on `layout/checkout.liquid`, with the `order_completed` variable set to `true`:

:::CodeblockTabs
layout/checkout.liquid

```html
{% render 'chord' order_completed: true %}
```
:::

:::hint{type="warning"}
Chord tracking cannot currently be installed on Shopify checkouts that have been upgraded to [Checkout Extensibility](https://help.shopify.com/en/manual/checkout-settings/checkout-extensibility/checkout-upgrade).&#x20;
:::

## Usage

Without any further code changes to your theme, Chord's snippet will send the CDP:

- A `page` event for every page view
- An `identify` event for every page view for a logged in user
- The following `track` events:
  - "Cart Viewed"
  - "Checkout Started"
  - "Email Captured"
  - "Order Completed" (if Chord's snippet is added to `checkout.liquid`)
  - "Product Clicked"
  - "Product Viewed"

You can add more events using the global `window.chord` object. See the [Shopify Theme API Reference](docId\:w1JcCHTdf49P8u7lWVuJM) for a complete list of available methods. You can also customize the DOM selectors used for the `track` events that Chord automatically sends.

## Configuration

Chord's Liquid tracking library can be configured with the following options. To modify the default options, change the `options` object argument passed to `chord.load()`:

| Property                | Type                                                       | Required | Description                                                                                                                                                                                                                                                                                                                       |
| ----------------------- | ---------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| autoInstrument          | boolean                                                    | no       | Defaults to `true`. When set to `false`, `track` events are not automatically sent.                                                                                                                                                                                                                                               |
| autoInstrumentSelectors | object (see **Auto-Instrument Selectors&#x20;**&#x62;elow) | no       | Provide custom DOM selectors for automatic instrumentation of events.                                                                                                                                                                                                                                                             |
| baseUrl                 | string                                                     | no       | The base URL of the Shopify site, to use in Shopify Ajax API requests. Ex. `https://example.myshopify.com`. If not provided, the current origin will be used.                                                                                                                                                                     |
| cdp                     | function or object                                         | yes      | A reference to the CDP library, or a function that returns a reference to the CDP library. For example, if using Segment's [analytics.js](https://www.npmjs.com/package/@segment/analytics-next) library, this could be `window.analytics` or `() => window.analytics`. If omitted, no tracking events are sent.                  |
| debug                   | boolean                                                    | no       | Defaults to `false`. When set to `true`, events are validated against Chord's tracking plan. An error is logged using `console.log` if the event doesn't match the tracking plan and the `enableLogging` option is set to `true`. We recommend enabling `debug` and `enableLogging` for development and disabling for production. |
| enableLogging           | boolean                                                    | no       | Defaults to `true`. When set to `true`, Javascript and `debug` errors are logged using `console.log`. We recommend enabling `debug` and `enableLogging` for development and disabling for production.                                                                                                                             |
| metadata                | object (see **Metadata&#x20;**&#x62;elow)                  | yes      | Event metadata. See below for details.                                                                                                                                                                                                                                                                                            |
| stripNull               | boolean                                                    | no       | Defaults to `true`. When set to `true`, event properties with a `null` value are removed. CDPs typically treat `null` and `undefined` as separate values, so be sure you intend to send `null` values before setting to false.                                                                                                    |
| syncIdentifiers         | object (see **Sync Identifiers&#x20;**&#x62;elow)          | no       | Enable adding integration identifiers as cart attributes, so they can be included in server-side events. Each integration defaults to `false`.                                                                                                                                                                                    |

**Auto-Instrument Selectors&#x20;**

This optional object allows you to customize the DOM selector that Chord uses to automatically track certain events. Events related to page view, such as "Cart Viewed," aren't configurable here, because they are based on the current URL instead of an interaction with the page.

Each event property can be a boolean or a string. When set to `false`, Chord won't send that event automatically. To customize the DOM element that triggers the event, set the matching event property to the DOM selector you want to use. That selector will be passed to `document.querySelectorAll(selector)` and an event listener will be added that the library will use to trigger the event. If the selector is a `<form>` element, the event will be triggered when the form is submitted. Otherwise, the event will be triggered when the element is clicked.

| Property                                     | Type               | Required | Description                                                                                                                            |
| -------------------------------------------- | ------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| autoInstrumentSelectors\['Checkout Started'] | string or boolean  | no       | The default selector is `form[action="/cart" i][method="post"]`.                                                                       |
| autoInstrumentSelectors\['Email Captured']   | string or boolean  | no       | The default selector is `form[action="/contact#contact_form" i][method="post"], form[action="/contact#contactform" i][method="post"]`. |
| autoInstrumentSelectors\['Product Clicked']  | string or boolean  | no       | The default selector is `a[href*="/products/" i]`.                                                                                     |

**Metadata**

This required object provides metadata about the event context that is appended to every event. Chord uses this metadata when providing insights.

| Property                    | Type   | Required | Description                                                                                                                                           |
| --------------------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| metadata.i18n.currency      | string | yes      | The order currency in ISO 4217 currency code, uppercase. For example, `USD`.                                                                          |
| metadata.i18n.locale        | string | yes      | The order locale. For example, `en-US`.                                                                                                               |
| metadata.ownership.omsId    | string | yes      | A UUID assigned by Chord. This identifier is unique to the store, and will be the same across every environment and Segment source for a given store. |
| metadata.ownership.storeId  | string | yes      | A UUID assigned by Chord. This identifier is unique to the store, and will be the same across every environment and Segment source for a given store. |
| metadata.ownership.tenantId | string | yes      | A UUID assigned by Chord. This identifier is unique to the store, and will be the same across every environment and Segment source for a given store. |
| metadata.platform.name      | string | yes      | The name of the e-commerce platform used. For example, `Shopify`.                                                                                     |
| metadata.platform.type      | string | yes      | The type of platform where the event originated. Either `web` or `pos`.                                                                               |
| metadata.store.domain       | string | yes      | The store slug that comes before `.myshopify.com`.                                                                                                    |

**Sync Identifiers&#x20;**

This optional object allows Chord's library to save identifiers from other libraries and integrations as attributes on the cart. Chord will use these attributes to connect your front-end website events with your server events. Read more about this in [Unifying Data Across Sources](docId\:FYmI5G8eWB-YYpyh-GU4o).

Each integration defaults to `false`. Set the integration to `true` if you plan to send both front-end and server events to the integration via the CDP.&#x20;

Currently, only the Google Analytics 4 identifier is supported. Contact Chord to request help adding more identifiers.

| Property                               | Type    | Required | Description                                                                                                                                                                                   |
| -------------------------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| syncIdentifiers\['Google Analytics 4'] | boolean | no       | When set to `true`, adds the client ID from the `_ga` cookie as a cart attribute. Chord will include this client ID on server events for the order, so sessions can be tied together in GA4.  |



