4

I have front-end GA4 implementation and want to send transactions data (and some custom events) from the server via MP. With recomendations of Google to

include session_id as a param, so that measurement protocol events appear in session-based reporting

is it better to get session_id from gtag.js or generate random session_id?

Michael
  • 41
  • 1
  • 2

3 Answers3

3

According to Measurement Protocol (Google Analytics 4)/Sending events using random value for 'session_id' parameter will start new session.

According to Measurement Protocol (Google Analytics 4)/Changelog 'session_id' is required to get server-side events in session-based reports.

Solution:

'Session Id' is stored in cookies and seems it's a timestamp of session start date. To get 'Session Id' at server side using PHP:

/**
 * Gets GA Session Id (GA4 only) from cookies.
 *
 * @var string $measurement_id
 *   GA4 Measurement Id (Property Id). E.g., 'G-1YS1VWHG3V'.
 *
 * @return int
 *   Returns GA4 Session Id or NULL if cookie wasn't found.
 */
function _get_browser_session_id($measurement_id) {
  // Cookie name example: '_ga_1YS1VWHG3V'.
  $cookie_name = '_ga_' . str_replace('G-', '', $measurement_id);
  if (isset($_COOKIE[$cookie_name])) {
    // Cookie value example: 'GS1.1.1659710029.4.1.1659710504.0'.
    // Session Id:                  ^^^^^^^^^^.
    $parts = explode('.', $_COOKIE[$cookie_name]);
    return $parts[2];
  }
}
VladSavitsky
  • 523
  • 5
  • 13
  • so, is it true that we have to manually get session id from cookie value and google do not provide javascript API to getting it? – Dan Feb 14 '23 at 10:22
  • I'm not sure google provide API to get Session Id. but I didn't find it. – VladSavitsky Feb 15 '23 at 17:31
  • Thank you. I also have tried to find it but have not found any. I chose this cookie parsing approach. – Dan Feb 16 '23 at 01:08
1

I think I found the solution here https://www.optimizesmart.com/what-is-measurement-protocol-in-google-analytics-4-ga4/#11-10-session-id-

There 2 params in the request to GA:

  1. "cid" - it's "GA client_id"
  2. "sid" - this is session_id and you need to save it in your DB near "cid" param and then send it using measurement protocol along with client_id
1

In order for GA4 to be able to attribute the event to the original session, you should provide the session_id. It can be retrieved through gtag:

gtag('get', 'G-XXXXXXXX', 'session_id', (sessionId) => {
  console.log(sessionId);
});

Resources:

Ahmed Elazazy
  • 454
  • 4
  • 10