Accurate and comprehensive data analysis is an extremely important part of managing web resources. One of the most important tools for collecting and analyzing information is the Measurement Protocol (MP) in Google Analytics 4 (GA4).
This is a protocol for transferring statistical data from your CRM/ERP system directly to Google Analytics via HTTP requests. In this article, I'll show you how to set up Measurement Protocol, optimize data collection with it, and solve common MP-related problems.
- Basics of working with Measurement Protocol.
- How to set up event transmission via MP.
- Generating a request for GA4 according to the requirements of the MP documentation.
- An example of sending an event via MP.
- Checking the event transmission settings.
- Optimizing data transmission.
- Limitations in MP.
- Common problems when working with MP.
Basics of working with Measurement Protocol
Measurement Protocol (MP) is only an extension of the analytics infrastructure. It does not replace the automatic data collection provided by gtag.js, Google Tag Manager, and/or the Google Analytics for Firebase SDK.
However, MP is useful when you need to see and analyze actions that cannot be tracked with standard JavaScript code, such as interactions with applications, submitting forms to the server, or interacting with external devices.
Let's consider some practical uses of Measurement Protocol:
- E-commerce tracking. When a payment system or server reports a successful payment, MP sends data about the transaction to Google Analytics (GA). This includes the transaction ID, payment amount, items purchased, and other data that helps you understand your store's performance and customer behavior.
- When working with mobile applications or other platforms where it is difficult to embed JavaScript code for tracking, MP sends events such as app opens, ad clicks, or use of specific features to GA. MP therefore gives you insight into the effectiveness of the application's functionality and helps you improve the user experience.
- If the website has a form that sends data to the server without reloading the page (AJAX request), MP is able to transmit events without being tied to the client side. This means that event data, such as a newsletter subscription, is sent directly from the server to the analytics system, bypassing the user's browser.
Here’s another example: If the form is used for conversions (newsletter subscription or order placement), MP is used to send a conversion event to the analytics server after the form is successfully submitted. Such an event can contain the name of the form, the location where the form is filled, the time of submission, and other details necessary for analysis. - If you need to analyze data outside the browser, MP allows you to send information directly to the analytics system. For example, to analyze server logs or server-generated data.
Server logs are files that are automatically created and stored on the server. They record various information about events that occur on the server, such as99 web page visits, database queries, system errors, user access times, etc.
Data generated on the server includes:
- Data about transactions in the online store
- Results of server script execution
- API request processing details
- Other internal processes that take place on the server
For example, each time a purchase is made in an online store, the server processes the transaction and stores information (the purchased item, the price, the buyer’s details) in server logs. Using MP, you can send this data to an analytics system for processing, including analysis of sales and customer behavior.
Essentially, MP is compatible with Google Analytics and collects information about user interaction beyond the standard JavaScript tracking capabilities.
How to set up event transmission via Measurement Protocol?
- Create an appropriate environment. The CRM system, ERP, or server should be able to send HTTP requests. Make sure the server can interact with MP via HTTP.
- Involve a back-end developer to make the necessary code changes to store identifiers and send requests via MP. It is important to determine what data needs to be transferred and include it in the appropriate requests.
- Involve a marketer to create technical tasks for the backend developer. For example, tasks specifying important events to track and data to include in MP, how to identify users, and how to measure events.
- Customize the MP. Work with the back-end developer to configure the sending of metrics via MP. Set parameters to meet your organization's data analysis needs.
- Do a test run. Verify the accuracy of data sent through MP. Ensure the marketer and the backend developer work together to correct any errors.
Creating a request to GA according to the requirements of the Measurement Protocol documentation
A POST request is one of the most common HTTP methods used to send data to a server.
As the GA4 measurement protocol only supports POST requests, you have to send HTTP POST requests to GA4 to transmit event data.
Paste the following code into the appropriate JavaScript file or HTML code on the page:
POST /mp/collect HTTP/1.1
HOST: www.google-analytics.com
Content-Type: application/json
<payload_data>
Where <payload_data> is the body of the request, which contains the names of the parameters and their values. It is a URL-encoded string of no more than 8192 bytes.
There are a few required URL parameters in the Google Analytics interface:
- api_secret is the key to access your GA account. To create an api_secret, go to Admin – Data streams – select your stream – Measurement Protocol API secrets – Create.
- measurement_id is the identifier of the stream. This identifier is associated with the stream, and you can find it in the section Admin – Data streams – select your stream – MEASUREMENT ID.
There are also required parameters for the JSON body that is part of <payload_data>:
- client_id is a unique user identifier in GA.
- user_id is a unique user identifier on the site.
- timestamp_micros is a Unix timestamp in microseconds (not milliseconds). Events must be no more than three calendar days old.
- events is an array of parameters containing events.
To get the client_id using the Google tag API (gtag.js), use the gtag ('get') method. According to the guidelines, use the following code:
gtag('get', '<target>', 'client_id', (clientID) => {
console.log('Client ID:', clientID);
});
<target> is the GA4 account ID (e.g., G-XXXXXXXXXX) from which you want to get the client_id.
If you have a mobile application, add the following to the previous parameters:
- firebase_app_id – the application ID in Firebase used by GA4 to identify the application sending the data.
- app_instance_id – a unique application instance identifier generated by the developer to identify a specific application installation.
- transaction_id – a unique transaction identifier.
- ad_network_id – the advertising network identifier.
In addition to these required parameters, there are additional parameters for the JSON body that can improve data transfer and facilitate data analysis:
- session_id defines a unique user session and allows you to track user interaction during the activity period.
- pageview
- screenview
- event
- transaction
- item
- social indicates social interaction, e.g. likes on Facebook, retweets on X, etc.
- exception indicates information about errors that occur on the website.
- timing indicates information about different time intervals, such as page load time.
Sending an event using MP
As an example, let's use the add_to_cart event. This event records that the product has been added to the shopping cart.
Required parameters for the event array:
- currency (string variable) indicates the currency of the elements associated with the event in ISO 4217 format.
- value (decimal number) is the total amount of the order or the number of items added to the cart.
- items is an array of product parameters.
Parameters of products in the items array:
- item_id (string variable) is the unique ID for the product.
- item_name (string variable) is the name of the product.
- affiliation (string variable) is a parameter that allows you to determine the affiliation of the product with a supplier or store.
- coupon (string variable) is the name/code of the coupon associated with the product.
- discount (decimal number) is a unit of monetary discount associated with the item.
- index (positive integer) is the number or position of the product on the list.
- item_brand (string variable) is the brand of the product.
- item_category (string variable) is the category of the product.
- item_category2 (3, 4, 5) (string variable) is the subcategory of the product.
- item_list_id (string variable) is a product list ID.
- item_list_name (string variable) is the name of the list, e.g., promotions, discounts, recommended products, best deals, etc.
- item_variant (string variable) is a product variation or a unique code, with a description for additional details/parameters of the product.
- location_id (string variable) indicates the location associated with the product.
- price (decimal number) is the cost of the product.
- quantity (positive integer) is the quantity of the product.
In addition to the parameters listed above, you can include up to 25 custom parameters in the element array.
Example code for the add_to_cart event sent by the POST request:
const measurementId = `G-XXXXXXXXXX`;
const apiSecret = `<secret_value>`;
fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
method: "POST",
body: JSON.stringify({
"client_id": "client_id",
"events": [{
"name": "add_to_cart",
"params": {
"currency": "USD",
"value": 30.03,
"items": [
{
"item_id": "SKU_12345",
"item_name": "Stan and Friends Tee",
"affiliation": "Google Merchandise Store",
"coupon": "SUMMER_FUN",
"currency": "USD",
"discount": 2.22,
"index": 0,
"item_brand": "Google",
"item_category": "Apparel",
"item_category2": "Adult",
"item_category3": "Shirts",
"item_category4": "Crew",
"item_category5": "Short sleeve",
"item_list_id": "related_products",
"item_list_name": "Related Products",
"item_variant": "green",
"location_id": "ChIJIQBpAG2ahYAR_6128GcTUEo",
"price": 10.01,
"quantity": 3
}
]
}
}]
})
});
After a successful trigger, the GA4 interface will show that the customer has added a product, Stan and Friends Tee, to their shopping cart for $30.03.
For a complete list of parameters that can be included in HTTP requests and examples of sending events via Measurement Protocol, please refer to the official documentation.
Verifying event transmission settings
Once you have set up the required events, it is a good idea to verify them. To do this, follow these steps.
Sending an event from the client
For an event to be valid, it must have a client_id element that has already been used to send an event from gtag.js. You need to capture this identifier on the client side and include it in the MP call.
You can get the ID from the server logs if it is a new event. If there are no server logs yet, create the event yourself by clicking on the MP-linked button.
The event will contain the client_id in the following format: ‘ecDwKrMi5IRwxXftaSDXxCEOL5mUsWz0qpbD’.
Send an event to your asset
Once you have obtained the client_id, you need to send the event via MP. To do this, insert the following code into the appropriate JavaScript file or HTML code of the page. For example, this is what it looks like for a purchase event:
const measurementId = `<measurement_id_value>`;
const apiSecret = `<secret_value>`;
fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
method: "POST",
body: JSON.stringify({
"client_id": "XXXXXXXXXX.YYYYYYYYYY",
"events": [{
"name": "purchase",
"params": {
"currency": "USD",
"value": "7.17",
"transaction_id": "NTP-017"
}
}]
})
});
Viewing the report in real time
After successfully submitting an event, you can view it in the GA4 interface by going to Reports ‒ Realtime in the left navigation bar.
Also, look at the “Number of Events by Event Name” and “Conversions by Event Name” charts. Information about the sent event should appear in real time just a few seconds after it is sent via MP.
Using MP allows you to review events in real time without having to wait up to 48 hours. It is also not complicated to use, as all parameters for MP are available in the official Google Help.
Optimizing data transfer with the Measurement Protocol
For an efficient and accurate GA4 analysis, it is critical that the data transmitted via MP is in the correct format and structure, as well as frequency.
Format and structure of data transmitted
- Data type. Each parameter must have a clear purpose, and its value must be the appropriate data type. For example, a text parameter must be a string, and a numerical parameter must be a number.
- Transmission efficiency. Reduce any unnecessary information and send only an optimal amount of data. A large amount can overload the network and cause a delay in transmission.
- Contextual data. Contextual data should be added to better explain or describe events, such as a user ID or additional attributes that help clarify the context of the event. This facilitates further analysis and improves the interpretation of the results.
- Accuracy and relevance. You must ensure that data is sent in real time and represents the current state of resources. This is especially important for obtaining accurate analytical results. If the data is not received in real time, check for errors in the MP event transmission configuration.
Data transmission frequency
The interval for sending data using MP is determined by the needs of the business and the nature of events on the platform. However, there are general recommendations to help optimize the process.
- The recommended interval is chosen to avoid excessive load on servers and network resources:
- For projects that require high accuracy of real-time data (financial transactions or system health monitoring), the intervals are shorter: every few seconds.
- For analytical projects where the data is used to create an overall picture and does not require immediate updating, such as website traffic reports, the intervals are longer: every few minutes.
- Monitoring the efficiency of the data transmission allows you to promptly adjust the transmission intervals to meet your organization's needs.
Measurement Protocol limits
- Queries have a maximum of 25 events.
- Events have a maximum of 25 parameters and 25 user properties.
- User property names are limited to 24 characters.
- Property values should be 36 characters or less.
- Event names should be 40 characters or less, comprising alphanumeric characters and underscores only. They must also begin with a letter.
- Parameter names, including item parameters, should be 40 characters or less. They are limited to alphanumeric characters and underscores only and must begin with a letter.
- Parameter values, including item parameters, should be 100 characters maximum.
- Item parameters include up to 10 customizable parameters.
- Message body should be 130 KB maximum.
- MP event-level attribution is supported up to 63 days after the last online event, even if the conversion window exceeds 63 days. In contrast, event-level attribution for online events is supported for the entire conversion window.
- For remarketing purposes, you can associate MP events within a certain number of days of the last online event. This requires an associated cookie or device ID:
- For a website, the last event must be no more than 30 days old.
- For a mobile application, it's 42 days.
- App Measurement Protocol events sent to Google Analytics 4 do not automatically complete search audiences in Google Ads.
Time limits and recommendations
It is important to be aware of the time limits for sending data via MP. For example, Google recommends that you send data with a data transfer history no later than three days after the initial transfer.
This recommendation is based on the need to maintain relevant and accurate analytical data. It is also driven by the need to conserve resources, as the system is unable to analyze the entire array. If the event is older than three days, the system loses the ability to connect to the source of the user session.
By sending data at the correct time, you will be able to maximize the efficiency of using the Measurement Protocol and also ensure the accuracy of analytical information.
Common problems when working with MP
When working with Measurement Protocol, you may encounter implementation issues that arise for various reasons. Let's consider a few of them.
- Incorrect implementation, which causes the protocol to work incorrectly:
- Incorrect configuration of GA tags.
- Incorrect coding of the Measurement Protocol, e.g. errors in request format, incorrect use of parameters, etc.
- Data issues that affect the quality of the analysis:
- Incomplete or inaccurate data.
- Duplicated data.
- Network errors:
- Internet connection interruptions or delays in data transmission.
- Blocking of requests by firewalls.
- Server problems:
Server overload, technical problems, unavailability of the Google Analytics server. In such cases, please contact Google Analytics support.
- Changes in Google Analytics:
- Update your Analytics code to adhere to the latest version of the guidelines.
- Read the updated Google Analytics policy and make the necessary changes.
- Legal and ethical issues:
- Failure to comply with GDPR rules when collecting and processing data.
- Google Analytics limitations:
- Limitations on the number of queries.
- Limitations on the amount of data.
- Functionality limitations.
Conclusions
- Measurement Protocol (MP) is a powerful tool in Google Analytics 4 that gives developers the flexibility to track and analyze data from multiple platforms. Using MP greatly extends the capabilities of standard collection, as it allows you to track user actions that cannot be tracked using JavaScript code.
- The benefits of using MP include:
- Tracking data from any environment that supports HTTP requests.
- Tracking offline conversions, server events, and interaction with external devices.
- Data enrichment with additional parameters for better analysis.
- Real-time event tracking.
- Best practices when using MP:
- Use the required parameters and recommended formats.
- Choose the optimal sending interval and amount of data.
- Respect the recommendations and limitations of Google Analytics.
- Diagnose and troubleshoot common problems with MP.
- The protocol is not a replacement for standard Google Analytics data collection and should be used only as a supplement to enhance analytics capabilities.
Related Articles
How to Add a New Website to GA4 or GTM
Step-by-step guide: how to create accounts in GA4 and GTM and link them to your website
Boost Your Click-Through Rate: The SEO Advantage of Sitelinks
Evolution of sitelinks, their advantages, and how to add them
How to Deal with Overload at Work – Tips and Effective Tools to Use
In this article, I’m going to give you some life-enhancing tips to help you cope with an overload of work and avoid burning out at the workplace