Google Analytics Destination

MorphL makes it easy to send predictions to Google Analytics.

A common use case is predicting your website's visitors behaviour using Google Analytics data, for example predicting when a visitor will add a product to the shopping cart.

This tutorial uses the Google Analytics admin panel and other tools to:

  • Create a custom dimension
  • Generate a token for authenticating to the MorphL API
  • Create a script for retrieving predictions and save them in your custom dimension


Google Analytics data source

This integration requires that your models use the Google Analytics data source.

(Recommended) Google Tag Manager

Google Tag Manager features close integration with Google Analytics. See the Deploy Google Analytics with Tag Manager doc for instructions.

Integrating predictions in a website or web app

Once predictions are available through the MorphL API, they can be consumed in a website or web application. The steps for integrating with the API are:

Generate authentication token

Using the API key and API secret created in the MorphL Dashboard, call the /authorize endpoint to generate an access token.

As a requirement for protecting the API credentials, the authentication request must be implemented in the backend.

Add custom dimension in Google Analytics

For tracking predictions associated with a Client ID, we use a custom dimension. This must be created from the Google Analytics admin panel:

Custom Dimension Prediction

Create script for retrieving predictions

The predictions are retrieved from the MorphL API by sending the client id as a parameter. The client id is retrieved from the _ga cookie, which is set by the Google Analytics tracking script.

Please see below a script that calls the MorphL API to retrieve predictions for the Shopping Stage Completeness ML model and processes the response:

function MorphlPredictions() {
    var JSObject = this;

    this.apiUrl =
    this.accessToken = "<jwt_token>";
    this.cookieName = "morphl_shoppingstage";
    this.gaCustomDimension = "<dimensionX>";

    * Initialize API call
    this.init = function() {
        // Check if we already have a prediction in the browser cookie
        var predictedShoppingStage = JSObject.getCookie(
        if (predictedShoppingStage !== "") {

        // Make call to get prediction from the API

    * Get a browser cookie
    * @param  string cname = The cookie name
    * @return  string = The cookie value or an empty string ("") if the cookie doesn't exist
    this.getCookie = function(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(";");
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == " ") {
                c = c.substring(1);
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
        return "";

    * Set a browser cookie
    * @param  string cname = The cookie name
    * @param  string cvalue = The cookie value
    * @param  string exhours = The expiration interval, in hours
    this.setCookie = function(cname, cvalue, exhours) {
        var d = new Date();
        d.setTime(d.getTime() + Number(exhours) * 60 * 60 * 1000);
        var expires = "expires=" + d.toUTCString();
        document.cookie =
            cname +
            "=" +
            encodeURIComponent(cvalue) +
            ";" +
            expires +
            ";path=/; secure";

    * Get the client id from the Google Analytics cookie.
    this.getGoogleAnalyticsClientId = function() {
        var gaCookie = JSObject.getCookie("_ga");

        if (gaCookie === "") {
            return null;

        // Parse the _ga cookie value to the right format.
        var lastElements = gaCookie.split(".").slice(-2);

        if (lastElements.length == 2) {
            return 'GA' + lastElements.join(".");

        return null;
    * Interogate Morphl API and get the value of the prediction for the client ID.
    this.getAPIPrediction = function() {
        // Set up our HTTP request
        var xhr = new XMLHttpRequest();

        // Setup our listener to process completed requests
        xhr.onload = function() {
            // Set a default value for the shopping stage
            var shoppingStage = "n/a";

            // Process response data
            if (xhr.status == 200 || xhr.status == 404) {
                // This will run when the request is successful
                var morphlRes = JSON.parse(xhr.response);

                // Validate the response received from the API
                // Check if the client id has a valid prediction
                if (
                    morphlRes &&
                    morphlRes.status &&
                    Number(morphlRes.status) == 1 &&
                    typeof morphlRes.shopping_stage === "number"
                ) {
                    // Get the shopping stage with the highest probability
                    var nextShoppingStage = Number(

                    shoppingStage =
                        nextShoppingStage >= 0.5
                            ? "add_to_cart"
                            : "all_visits";

                // Set a cookie with the Morphl prediction value
                JSObject.setCookie(JSObject.cookieName, shoppingStage, 2);

                // Set the custom dimension with the prediction value
                ga("set", JSObject.gaCustomDimension, shoppingStage);

                // Send custom event
                ga("send", "event", {
                    eventCategory: "morphlPrediction",
                    eventAction: "setPrediction"

        var clientId = JSObject.getGoogleAnalyticsClientId();

        if (clientId !== null) {

            // Create and send the GET request
            // The first argument is the post type (GET, POST, PUT, DELETE, etc.)
            // The second argument is the endpoint URL
                String(JSObject.apiUrl) +
                    "?client_id=" +
            xhr.setRequestHeader("Authorization", JSObject.accessToken);

var morphlPredictions = new MorphlPredictions();


The anatomy of the sample script is as follows:

  • It assumes your activated ML models use Google Analytics as a data source. For more details, see the Google Analytics data source guide.
  • It doesn't include authentication and assumes that a valid access token was already generated. This token should be set in the accessToken property.
  • The value of the prediction is saved in the custom dimension created at Step 2 and in a cookie, identified by the cookieName property.


The script parameters are:

  • <account> represents your unique account number, which can be retrieved from the MorphL Dashboard.
  • <jwt_token> is the JWT returned by the /authorize endpoint.
  • <dimensionX> is the Google Analytics custom dimension that will store the prediction value. Ex. Replace <dimensionX> with dimension3 (angular brackets are not required).

Add script from GTM or website source

The script can be loaded in a website using Google Tag Manager or it can be added as a custom script directly in the source of your website. Follow this guide to include it from GTM.

(Further development) Personalize user experience based on prediction values

After the above script has been added to your website, you can use the prediction values and personalize your users' experience - for example displaying different call-to-action pop-ups and messages depending on their probability to add a product to the shopping cart or their predicted LTV.

(Optional) Segment users in the Google Analytics dashboard

Once the custom dimension has been defined and the predictions script has been added, users can be segmented in the Google Analytics dashboard.

Creating a segment in Google Analytics

In the below image, you can see an example of creating a custom segment for users with a probability greater than 50% (0.5). For the Shopping Stage Completeness ML model, this probability represents how likely is a user to add a product to the shopping cart, start checkout or finalize a transaction.

Since we want these probabilities to have a Session scope, we can't use a custom metric (custom metrics can have only product or hit scope). The custom dimension uses a string format, so we must add multiple conditions to target all the values greater than 0.5.


Advanced targeting when using multiple ML models

In addition to being used individually, MorphL models can be combined for more advanced segmentation and targeting:

Combined heatmap

The above diagram outlines segments delimited by two models: Shopping Stage Completeness and Cart Abandonment. In this example:

  • Hot means users that have a high probability of starting the add to cart > checkout process and a low probability of cart abandonment.
  • Promising means users that have a high probability of starting the add to cart > checkout process and a high probability of cart abandonment.

For example, you can choose to target Promising users with discounts, free shipping, gifts, etc. by remarketing them or sending them personalized email notifications.

In Google Analytics, the above segments are defined as:

HOT users segment

HOT users segment

Promising users segment

Promising users segment

Another example would be creating personalized discount offers. By using the CLTV model, you are able to predict the value of a user's future orders and adjust a discount or voucher value accordingly. This prediction can be used in conjunction with the Shopping Stage Completeness value, for example by targeting mid-tier users who haven't yet made the purchase decision.

Please see the destinations catalog for more examples of using predictions.