How to set up Google Analytics 4 (GA4) Custom Pixel in Shopify

Follow the steps in this guide to set up Google Analytics 4 tracking in Shopify using Customer events (Custom pixel)

NOTE: Read this guide if you prefer using Google Tag Manager template https://knowledge.profitmetrics.io/how-to-set-up-google-analytics-4-with-e-commerce-events-in-google-tag-manager

NOTE: Read this guide if you prefer to configure in Google Tag Manager manually
Click here for instructions on How to manually set up Google Analytics 4 (GA4) in Google Tag Manager 



  1. Log in to https://admin.shopify.com
  2. Click "Settings"
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 2
  3. Click "Customer Events"
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 3
  4. Click "Add custom pixel"
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 4
  5. Name the custom pixel "ProfitMetrics - GA4" and click "Add pixel"
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 7
  6. Click "Permissions" and select your preferred permission set.
    CAUTION: Choosing the correct "Permission" and "Data Sale" settings is ultimately your responsibility. Please consult a lawyer or legal expert.

    By default, the pixel will only fire when Marketing and Statistics consent is granted. Please ensure your Cookie Banner and Shopify Consent API are connected properly in order for consent to be registered. 

    Some countries allow the use of "basic statistic tracking" without consent. This requires that all Marketing related settings and options in Google Analytics 4 are disabled. If this relevant to you, you can opt for the "Not required" option under "Permissions" and "Data collection does not qualify as data sale" under "Data Sale. "
  7. Click "Permission"

    Set Up Custom Pixel for Customer Events in Shopify - Step 8

  8. Select "Not required"

    Set Up Custom Pixel for Customer Events in Shopify - Step 9

  9. Click "Data sale"

    Set Up Custom Pixel for Customer Events in Shopify - Step 10

  10. Select "Data collected does not qualify as data sale"

    Set Up Custom Pixel for Customer Events in Shopify - Step 11
  11. Delete all default text then copy the Pixel code from the 'Open Script Setup Guide' button  in ProfitMetrics Google Analytics connection and paste the code into the Code field

    Temporary code
    // Start - ProfitMetrics - Google Analytics 4 (v2)
    // Configuration
    let customerPrivacyStatus = init.customerPrivacy;
    // Default consent values
    let cc_statistics = true;
    let cc_marketing = true;


    const script = document.createElement( 'script' );
    script.setAttribute( 'src', 'https://www.googletagmanager.com/gtag/js?id=G-03E10PRYLQ' );
    script.setAttribute( 'async', '' );
    document.head.appendChild( script );


    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-XXXXXXXXXX');
    gtag('config', 'G-YYYYYYYYYY');




    analytics.subscribe("all_standard_events", event => {
    });




    // Page view
    analytics.subscribe("page_viewed", async event => {
    console.log("pageview");
     if (!customerPrivacyStatus || 
        customerPrivacyStatus.analyticsProcessingAllowed === undefined || 
        customerPrivacyStatus.marketingAllowed === undefined) {
      try {
        const cmp_a = await browser.cookie.get('_cmp_a');
        const cookiedecoded = JSON.parse(decodeURIComponent(cmp_a));
        cc_statistics = cookiedecoded?.purposes?.a ?? cc_statistics;
        cc_marketing = cookiedecoded?.purposes?.m ?? cc_marketing;
      } catch (e) {
        // Handle any errors that might occur
      }
    } else {
      cc_statistics = customerPrivacyStatus.analyticsProcessingAllowed;
      cc_marketing = customerPrivacyStatus.marketingAllowed;
    }


        gtag('consent', 'update', {
            'ad_storage': cc_marketing ? 'granted' : 'denied',
            'ad_user_data': cc_marketing ? 'granted' : 'denied',
            'ad_personalization': cc_marketing ? 'granted' : 'denied',
            'analytics_storage': cc_statistics ? 'granted' : 'denied'
        });


        const getPageViewData = (data) => {
          const ctx = data.context;
          return {
            page_location: ctx.document.location.href,
            page_title: ctx.document.title,
            language: ctx.language,
          };
        };
      
        gtag("event", "page_view", getPageViewData(event.data));
      });


    // Product view
    analytics.subscribe("product_viewed", async event => {
      console.log("product view");
      const getViewItemData = (data) => {
        const product = data.productVariant;
        return {
          currency: product.price.currencyCode,
          value: product.price.amount,
          items: [{ item_id: product.id, item_name: product.product.title }],
        };
      };


      gtag("event", "view_item", getViewItemData(event.data));
    });


    // Search
    analytics.subscribe("search_submitted", async event => {
      gtag("event", "search", {
        search_term: event.data.searchResult.query,
      });
    });


    // Add to cart
    analytics.subscribe("product_added_to_cart", async event => {
      const getAddToCartData = (data) => {
        const item = data.cartLine.merchandise;
        return {
          currency: item.price.currencyCode,
          value: item.price.amount,
          items: [{ item_id: item.id, item_name: item.product.title }],
        };
      };


      gtag("event", "add_to_cart", getAddToCartData(event.data));
    });


    // Add payment method
    analytics.subscribe("payment_info_submitted", async event => {
      const getItemsFromLineItems = (lineItems) => {
        return lineItems.map(item => ({
          item_id: item.variant.product.id,
          item_name: item.variant.product.title,
        }));
      };


      const getPaymentInfoData = (data) => {
        return {
          currency: data.checkout.currencyCode,
          value: data.checkout.totalPrice.amount,
          items: getItemsFromLineItems(data.checkout.lineItems),
        };
      };


      gtag("event", "add_payment_info", getPaymentInfoData(event.data));
    });


    // Begin checkout
    analytics.subscribe("checkout_started", async event => {
      const getItemsFromLineItems = (lineItems) => {
        return lineItems.map(item => ({
          item_id: item.variant.product.id,
          item_name: item.variant.product.title,
        }));
      };


      const getCheckoutData = (data) => {
        return {
          currency: data.checkout.currencyCode,
          value: data.checkout.totalPrice.amount,
          items: getItemsFromLineItems(data.checkout.lineItems),
        };
      };


      gtag("event", "begin_checkout", getCheckoutData(event.data));
    });


    // Purchase
    // analytics.subscribe("checkout_completed", async event => {
    //   const getItemsFromLineItems = (lineItems) => {
    //     return lineItems.map(item => ({
    //       item_id: item.variant.product.id,
    //       item_name: item.variant.product.title,
    //     }));
    //   };
    // 
    //   const getCheckoutCompleteData = (data) => {
    //     return {
    //       transaction_id: data.checkout.order.id,
    //       currency: data.checkout.currencyCode,
    //       value: data.checkout.totalPrice.amount,
    //       items: getItemsFromLineItems(data.checkout.lineItems),
    //     };
    //   };
    // 
    //   gtag("event", "purchase", getCheckoutCompleteData(event.data));
    // });


    // End - ProfitMetrics - Google Analytics 4 (v2)

     



    Edit Shopify Pixel Settings and Clear Text. - Step 5

  12. Click "Save."
  13. Click "Connect" and then "Connect" again.
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 30
    Add Custom Pixel to Shopify Settings with ProfitMetrics - GA4 - Step 35

All done. The Custom Pixel will now track all e-commerce events except Purchase which is handled by ProfitMetrics.