Search code examples
parsinggoogle-analyticsmeasurement-protocolgoogle-analytics-4

How to parse GA4 Measurement Protocol (collect?v=2) POST request URLs?


Objective

Problem

  • Main problem, as far as I can see, is when multiple GA4 hits are sent close to each other, GA4 batches and sends them together.
  • I am struggling to understand how to go parse GA4 hits which carry data for multiple events.
  • I was able to do the same exercise for other providers including GA3 for which documentation is brilliant.
  • I was unable to find anything useful reading the GA4 Measurement Protocol Reference.
  • This problem causes the data displayed to be incomplete / incorrect.

Solution

    • Standalone GA4 hits are POST requests with query string parameters.
    • Batched GA4 hits are POST requests with query string parameters and payload.
    • Splitting payload text by one or more whitespace characters will return an array of strings where each string represents the data associated with a batched GA4 event.
      • Example: postDataText.split(/\s+/)