Skip to content

Instantly share code, notes, and snippets.

@lambtron
Last active October 23, 2023 17:48
Show Gist options
  • Save lambtron/4a6ac9ab322e94f5bfc6 to your computer and use it in GitHub Desktop.
Save lambtron/4a6ac9ab322e94f5bfc6 to your computer and use it in GitHub Desktop.
segment event tracking for shopify
title sidebar
Segment Event Tracking for Shopify
Shopify

Segment makes it simple for Shopify merchants to integrate analytics, email marketing, advertising and optimization tools. Rather than installing all your tools individually, you just install Segment once. We collect your data, translate it, and route it to any tool you want to use with the flick of a switch. Using Segment as the single platform to manage and install your third-party services will save you time and money.

The guide below explains how to install Segment in your Shopify store. All you need to get up and running is copy and paste a few snippets of code into your theme editor. (You don't have to edit the code or be versed in JavaScript.) The following guide will show you how, step by step.


Step 1: Segment Account

Start by creating a Segment account. We recommend creating an organization so you can invite teammates to your account in the future.

Once your account is created, add a new project for your store.

Step 2: Install Segment Code

Once your Segment account is ready to go you'll need to install a few lines of javascript into your Shopify theme templates.

Everything you need can be found in your Shopify Admin under Themes > Customize Theme > Edit HTML/CSS. Each section below includes a reference to one of the folders and liquid templates that can be found on the left side of this page.

If you want to track all events as noninteraction to GA make sure to add an event prop for that.

2a: Add Your Snippet to All Pages

  • Folder: Layouts
  • File: theme.liquid

Add the following snippet to the line above the </head> tag on your main theme.liquid template file. Doing this will load the Segment javascript library (Analytics.js) on every page of your Shopify store.

Make sure you replace YOUR_WRITE_KEY with the write key found in your setup page (click on the wrench icon from inside your Segment project).

<script type="text/javascript">
  window.analytics=window.analytics||[],window.analytics.methods=["identify","group","track","page","pageview","alias","ready","on","once","off","trackLink","trackForm","trackClick","trackSubmit"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var key=window.analytics.methods[i];window.analytics[key]=window.analytics.factory(key)}window.analytics.load=function(t){if(!document.getElementById("analytics-js")){var a=document.createElement("script");a.type="text/javascript",a.id="analytics-js",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.io/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)}},window.analytics.SNIPPET_VERSION="2.0.9",

  window.analytics.load("YOUR_WRITE_KEY");

  // identify the customer if they have an account
  {% if {{ customer.id }} %}
  window.analytics.identify({{customer.id}}, {
    name: "{{ customer.name }}",
    firstName: "{{ customer.first_name }}",
    lastName: "{{ customer.last_name }}",
    email: "{{ customer.email }}",
    phone: "{{ customer.default_address.phone }}",
    address: {  // uses the default address
      street: "{{ customer.default_address.street }}",
      city: "{{ customer.default_address.city }}",
      state: "{{ customer.default_address.province }}",
      stateCode: "{{ billing_address.province_code }}",
      postalCode: "{{ customer.default_address.zip }}",
      country: "{{ customer.default_address.country }}",
      countryCode: "{{ customer.default_address.country_code }}"
    },
    totalSpent: "{{ customer.total_spent }}",
    allOrdersCount: {{ customer.orders_count }},
    allOrderIds: [{% for order in customer.orders %}{{ order.id }},{% endfor %}],
    tags: ["{{ customer.tags | join: '", "' }}"]
  });
  {% endif %}
  window.analytics.page();
</script>

2b: Category (Collection) Pages

  • Folder: Templates
  • File: collection.liquid

This tracks your proudct category pages (referred to as collections in Shopify).

<script type="text/javascript">
  analytics.track('Viewed Product Category', {
    category: "{{ collection.title }}",
    categoryUrl: "{{ collection.url }}",
    categoryProductCount: {{ collection.all_products_count }},
    {% if collection.current_type %} filteredType: "{{ collection.current_type }}"{% endif %},
    {% if collection.current_vendor %} filteredVendor: "{{ collection.current_vendor }}"{% endif %},
    defaultSortBy: "{{ collection.default_sort_by }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
  });
</script>

2c: Product Pages

  • Folder: Templates
  • File: product.liquid

This script tracks when visitors view producta and an Added Product event when they add products to their cart.

<script type="text/javascript">
  analytics.track('Viewed Product', {
    id: "{{ product.id }}",
    name: "{{ product.title }}",
    type: "{{ product.type }}",
    url: "{{ product.url }}",
    price: {{ product.price }},
    priceMin: {{ product.price_min }},
    priceMax: {{ product.price_max }},
    priceVaries: {{ product.price_varies }},
    variantsCount: {{ product.variants.size }},
    firstAvailVariant: "{{ product.first_available_variant.title }}",
    variantId: {{ product.selected_variant.id }},
    variantAvailable: {{ variant.available }},
    variantCompareAtPrice: {{ variant.compare_at_price }},,
    variantQuantity: {{ variant.inventory_quantity }},
    variantPrice: {{ variant.price }},
    variantSelected: {{ variant.selected }},
    sku: "{{ variant.sku }}",
    variantTitle: "{{ variant.title }}",
    variantUrl: "{{ variant.url }}",
    variantWeight: "{{ variant.weight }}",
    vendor: "{{ product.vendor }}",
    collections: [{% for collection in product.collections %}"{{ collection.title }}",{% endfor %}],
    available: {{ product.available }},
    options: ["{{ product.options | join: '", "' }}"],
    optionsCount: {{ product.options.size }},
    tag: ["{{ product.tags | join: '", "' }}"]
  });
  
  // track Product Added event
  
  var form = document.getElementById('add-to-cart');
  // or your form's ID

  analytics.trackForm(form, 'Added Product', {
    id: {{ item.id }},
    name: "{{ item.title }}",
    price: {{ item.price }},
    quantity: {{ item.quantity }},
    value: {{ item.quantity }}*{{ item.price }}
  });
</script>

2d: Cart Page

  • Folder: Templates
  • File: cart.liquid

This script tracks the cart page and events for Removed Product and Updated Product when a product is removed from the cart or the quantity is updated.

<script type="text/javascript">
  analytics.track('Viewed Cart', {
    itemCount: {{ cart.item_count }},
    totalPrice: {{ cart.total_price }},
    totalWeight: {{ cart.total_weight }}
  });

</script>

2f: Thank You Page

This tracks the Completed Order event that records all your transaction data to Segment. To add a script to your thank you page, you'll leave the theme editor and go to your checkout settings page: http://myshopify.com/admin/settings/checkout

In the "Additional content scripts" field, shown above, paste the following code:

  <script type="text/javascript">
  var discounts = {{ order.discounts | json }}
  var totalDiscount = 0;
  
  for (var i = 0; i< discounts.length; i++ ) {
    totalDiscount += discounts[i].savings;
  }
  
  window.analytics.track('Completed Order', {
    orderId: {{ order_number }},
    total: {{ total_price | money_without_currency }},
    revenue: {{subtotal_price | money_without_currency }},
    shipping: {{shipping_price | money_without_currency }},
    tax: {{tax_price | money_without_currency }},
    discount: totalDiscount,
    products: [
    {% for line_item in line_items %}
    {
      id: "{{ line_item.id }}",
      sku: "{{ line_item.sku }}",
      name: "{{ line_item.title }}",
      price: "{{ line_item.price }}",
      quantity: {{ line_item.quantity }}
    },
    {% endfor %} ]
    });
  </script>

2x: Track the Index Page

  • Folder: Templates
  • File: index.liquid
<script type="text/javascript">
  analytics.track('Viewed Index');
</script>

2x: Track Other Pages

  • Folder: Templates
  • File: page.liquid

This will also track the contact page automatically (page.contact.liquid).

<script type="text/javascript">
  analytics.track('Viewed Page', {
    title: "{{ page.title }}",
    url: "{{ page.url }}",
    author: "{{ page.author }}",
    handle: "{{ page.handle }}",
    id: {{ page.id }}
  });
</script>

2x: Track Blog Pages

  • Folder: Templates
  • File: blog.liquid

This script tracks your blog home page.

  <script type="text/javascript">
  window.analytics.track('Viewed Blog', {
    pageType: 'Front Page',
    pageTitle: document.title,
    blogArticleCount: {{ blog.articles_count }},
    blogTitle: "{{ blog.title }}",
    blogUrl: "{{ blog.url }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
    });
  </script>
  • Folder: Templates
  • File: article.liquid

This script tracks all your blog articles.

  <script type="text/javascript">
  window.analytics.track('Viewed Blog', {
    pageType: 'Article',
    pageTitle: document.title,
    articleTitle: "{{ article.title }}",
    articleAuthor: "{{ article.author }}",
    articleCreatedAt: "{{ article.created_at | date: "%F" }}",
    articlePublishedAt: "{{ article.published_at | date: "%F" }}",
    articleCommentCount: {{article.comments_count }},
    articleTags: ["{{ article.tags | join: '", "'}}"],
    articleUrl: "{{ article.url }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
    });
  </script>

2e: Search Page

  • Folder: Templates
  • File: search.liquid

This tracks your search page.

{% if search.performed %}

<script type="text/javascript">
  analytics.track('Searched Products', {
    resultsCount: {{ search.results_count }},
    terms: "{{ search.terms }}"
  });
</script>
{% endif %}

Registration (customers/register.liquid)

<script type="text/javascript">
    analytics.track('Viewed Registration');
</script>

--- Use our analytics.trackForm() method to call a "Signed Up" event on registration:

<script type="text/javascript">
var form = document.querySelector('form[id="create_customer"]');
  
 analytics.trackForm(form, "Signed Up", function(form){
  var firstName = document.querySelector('input[name="customer[first_name]"]').value;
  var lastName = document.querySelector('input[name="customer[last_name]"]').value;
  var email = document.querySelector('input[name="customer[email]"]').value;

  return {
    firstName: firstName,
    lastName: lastName,
    email: email
  }
});
</script>

404 Page (404.liquid)

<script type="text/javascript"> analytics.track('Viewed 404 Page'); </script>
@kriskayyal
Copy link

For the thank you page. I don't know if you are using the shopify plus but segment code doesn't show up on that page unless you include it specifically in the additional scripts part. So you may want to include the segment code above that.

Also i had issues with the discount piece when there was no discount. So I removed that part.

It is working fine now :)

@BrunoBoehm
Copy link

Wow thanks for this gist... have you made an update based on @kriskayyal 's remark?

@emcmanus
Copy link

Awesome to see this laid out in one place! Thanks @lambtron

There's a Shopify app that does this, too: https://apps.shopify.com/segment

@jonthornham
Copy link

jonthornham commented Dec 19, 2019

For the thank you page. I don't know if you are using the shopify plus but segment code doesn't show up on that page unless you include it specifically in the additional scripts part. So you may want to include the segment code above that.

Also i had issues with the discount piece when there was no discount. So I removed that part.

It is working fine now :)

** UPDATED **
I loaded the code for the Thank You page in the additional scripts part of the Checkout Settings a suggested. I do not see this load in the debugger when an order is completed. You mentioned to include the Segment code above it. By Segment code do you mean the code added to theme.liquid?

** NEW **
I was able to resolve this issue by adding this full script to the "Additional Scripts" section on the "Checkout Settings" page. NOTE: The discounts code caused an issue for me as well, which was pointed out by @kriskayyal. Once this is removed, the code works fine.

<!-- Segment Code -->
<script>
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.1.0";
  analytics.load("YOUR_SEGMENT_ID");
  
  window.analytics.track('Completed Order', {
    orderId: {{ order_number }},
    total: {{ total_price | money_without_currency }},
    revenue: {{subtotal_price | money_without_currency }},
    shipping: {{shipping_price | money_without_currency }},
    tax: {{tax_price | money_without_currency }},
    products: [
    {% for line_item in line_items %}
    {
      id: "{{ line_item.id }}",
      sku: "{{ line_item.sku }}",
      name: "{{ line_item.title }}",
      price: "{{ line_item.price }}",
      quantity: {{ line_item.quantity }}
    },
    {% endfor %} ]
    });

  }}();
</script>

@kiwinode
Copy link

Great to find - thank you! It led me to this, which seems to be an update, although itself, deprecated https://community.segment.com/t/k98abg/shopify-store-event-tracking-deprecated

@ejwhite7
Copy link

ejwhite7 commented Nov 4, 2021

Hello!

It looks like 2a needs a closing }}(); before the closing </script>, and the liquid block identifying whether a user is logged in should be: {% if customer %}. I'm not sure if Shopify updated since this was posted, but I made those tweaks debugging the implementation and it worked well. Thank you!

@MIDIculous
Copy link

I know this is an old post, but just wondering if this code is still valid?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment