Connect data to a google analytics session in javascript - javascript

On Google Analytics, in Javascript, is there a way to tie certain behavior to which session ID a user is on?
For example, every time the user changes GA sessions, we want to show the user a different version of the site.
It seems that GA doesn't really offer up the session ID.
We are tracking site versions via Google Analytics custom events. So if there's a way to see which custom events have previously been called for this session, that would also solve the problem.
Something like this would be ideal:
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
However, that is only for the clientId, not for the session ID.

GA UA (analytics.js) doesn't surface session ids. GA UA calculates/generates them later on because of how complex the rules for them are.
GA4 (gtag.js) does generate a session id and stores it on the front-end since the rules for sessions are now way simpler. It stores it in a cookie that starts from _ga and then has your tracking code in it. Here is how it looks here, on this page on SO:
Finally, here is how you get the value from gtag (it's cleaner than parsing the cookie):
gtag('get', 'G-WCZ03SZFCQ', 'session_id', (field) => console.log(field))
If you want to read more on gtag api, here's the documentation.
Note that it wants a callback to get the field:
Not sure why Google decided to make the get function async just to get a cookie. Probably they just decided to follow the same pattern and some items to require async for some reason.

Google Analytics does not provide a way to access the session ID directly. However, you can use the clientId to tie certain behavior to a user's session.
The clientId is a unique identifier that is generated by GA for each user. It is stored in the browser's cookies, and is used to identify a user across multiple sessions.
You can use the ga function to access the clientId as you mentioned in your example:
ga(function(tracker) {
var clientId = tracker.get('clientId');
// use the clientId to tie certain behavior to a user's session
});
You can also use custom events to track different versions of the site, as you mentioned. You can then use the clientId to see which custom events have previously been called for a user's session.
It's worth noting that if you're using GA cookies with the same domain across different subdomains, you'll have to use the linker plugin to properly track the client ID across those subdomains.
ga('create', 'GA_MEASUREMENT_ID', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['domain1.com', 'domain2.com']);
In summary, while GA does not offer a direct way to access the session ID, you can use the clientId and custom events to tie certain behavior to a user's session and track different version of the site.

Related

How to create Custom Dimension & get Unique PageView with GA4?

We're not sure if this is the right place for us to obtain the answers of such. We've contacted the Firebase Support Team but did not get the answers that we want except a few links to the online documentation that we've mostly been through before. After further clarifying our requests, we've not been receiving any response from them for 5 days; therefore we might as well try our luck here.
1. How to create a Custom Dimension in GA4?
As we understand, GA4 are all events now, including the Hit in Universal Analytics (UA), but how can we map from our UA custom dimensions to the GA4 model as shown below?
When we tried to create the AccCode custom dimension in GA4, we have no idea what to enter under the Event parameter dropdown list as it also cannot be dropped down whatsoever:
May I know how can we proceed from here and what should we enter for the Event parameter value?
2. How to get Unique PageView (UPV) in Firebase GA4 API?
In UA or GA v3, this is how we get our Page View and Unique PageView:
return jwt.authorize()
.then((response) => {
return google.analytics('v3').data.ga.get({
'auth': jwt,
'ids': 'ga:' + gaConfig.ViewerID,
'start-date': validatedDateRange.strStartDate,
'end-date': validatedDateRange.strEndDate,
'metrics': 'ga:pageviews,ga:uniquepageviews',
"dimensions": gaConfig.AccCodeDimension,
'filters': ${gaConfig.PageUrlDimension}!#googleusercontent.com;${gaConfig.PageUrlDimension}!#blogspot.com${!accCode ? "" : ";" + gaConfig.AccCodeDimension + "==" + accCode}`,
'sort': `${gaConfig.AccCodeDimension},-ga:pageviews,-ga:uniquepageviews`
}).then((gaQuery) => {
// Do something here
});
Below is the sample code that we found from the Firebase GA4 documentation:
import firebase from "firebase/app";
import "firebase/analytics";
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Analytics and get a reference to the service
const analytics = firebase.analytics();
analytics.logEvent('select_content', {
content_type: 'image',
content_id: 'P12453',
items: [{ name: 'Kittens' }]
});
But the above sample code seems to be far from giving us an idea on how to achieve the same result as did in GA v3. It's more like logging of event data, potentially for our custom dimensions as what we did in the UA's tracking code. Examples for data pulling don't seem to be available in the documentation here. We need an equivalent example on how we can achieve the same result with Firebase GA4 API so that we can quickly migrate over to GA4 before July 2023.
We hope that someone here can help us to resolve the above two issues as quickly as possible because they involve changing the core engine of our app, which requires vast amount of development time and testing while the clock is ticking. Thank you so much in advance!
After so much of the studies and R&D, we realized that for what we're trying to achieve has nothing to do Firebase at all -- we can purely focus on GA and its latest API, which is still on Beta while some are on Alpha. But for the custom dimension creation, below is the answer:
Creating Custom Dimensions in GA4
As per the question described, the custom dimension creation process can be very confusing, especially to the UA users due to the change of data model and concepts. But what you need to know is that, you need to finalize your event parameters before mapping them over to the custom dimensions on GA console because the event parameter cannot be edited once the custom dimension is created on GA console:
So what you need to do is to extend your existing UA tracking code as shown below before creating your custom dimensions on GA console:
gtag('event','page_view', { // the page_view event is for web
"acc_code": "{{{AccCode}}}", // acc_code is your event parameter
"acc_name": "{{{AccName}}}", // This is another event parameter
"viewer_id": "{{{ViewerID}}}",
"viewer_title": "{{{ViewerTitle}}}",
"viewer_url": "{{{gaUrl}}}"
});
gtag('config', 'G-XXXXXXXX'); // This is your GA4 MEASUREMENT_ID
Data Query in GA4
For data query in GA4 that is equivalent to the given example in the question, please refer to the GA4 Data API here.
What about the Unique Pageview metric?
According to the GA documentation here, looks like Unique Pageview is no longer available in GA4:
I'm not sure if this is still subject to change, but you may need to write your own code, perhaps using sessionStorage or session cookies to track your own unique pageviews per user session for every page viewed.

Google Analytics - Different users on same public computer have same User ID metric

I have an app where we track user id's from session and pass to custom metric in Google Analytics.
What we're seeing is that if you log out, and log back in as a different user, both users will use the latest user id within google analytics.
Is it possible to "clear" this common link between each session so that each sign in starts it's own session in GA?
Here's the same thread topic on ga forum: https://support.google.com/analytics/thread/96259041?hl=en
You have to set the clientId when you create the tracker. i.e.:
ga('create', 'UA-XXXX-Y', {
'clientId': '<my custom clientid>'
});
You will have to find a way to get it new on next time and pass it to the snippet above (or via GTM). For example, you can write it in a cookie that is deleted when you close the browser, in this way for the entire duration of the navigation it will be maintained and the next time you open the browser you have another one created and you will use that, and so on.

How to reliably get session id generated by Google Analytics?

Using the latest analytics.js code (as of today) is there a way through their JS API I can get the session id?
If you're talking about the client ID, you can get that as follows:
ga(function(tracker) {
var clientId = tracker.get('clientId');
console.log(clientId);
});
Here's where that's stated in the documentation:
https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getting_the_client_id_from_the_cookie
Keep in mind that the client ID is (usually) stored in a cookie, so if the user clears their cookies, they'll be assigned a new client ID that may not match the one you have.
You can read the cookie created by Google but:
It's a privately (by google) chosen variable name/format and could change at any time, thus breaking your code
It appears to break their TOS if you store that information
https://webmasters.stackexchange.com/questions/51866/can-you-track-one-users-session-with-google-analytics-by-using-the-utma-cooki
Linking Google Analytics event logs to unique session ID
http://www.analytics-ninja.com/blog/2011/08/how-google-analytics-calculates-visits.html
Be aware! Some ad-blockers like uBlock Origin replaces GA script with its own polyfill.
This means that you can't correctly check is it real GA script are loaded on your page.
Also uBlock's polyfill changes GA API, so when you using ga(function(tracker){}) callback will never called!
So don't relay on callback and never wait for its calling
The better way is to manually store custom clientId in cookie and tell this clientId to GA
https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference?hl=en#clientId

Set Google Analytics User ID after creating the tracker

The Google Analytics User ID documentation page shows that you set the User ID when you create the tracker. I have a javascript only project with sign-in after page load, is there any way to set the User ID after login? Something like ga("set", "userid", "UNIQUEID")
On the field reference page it says you can only set user-id in the create function. Are we able to call create again with the user-id? Will that create a new tracker, or override the old one?
EDIT: The beta version of User ID tracking showed that you could specify the userid after creating the tracker using ga('set', '&uid', {{ USER_ID }}); and that would try to unify the session from before the userid was set with the one after. That seems to be very different than what the docs current specify. Is there any way to do this with the current method?
This one works
ga('set', '&uid', '<dynamic user id here>');
The documentation seems to indicate that, with analytics.js, you should do the following:
// Alternatively, you may set the user ID via the `set` method.
ga('set', 'userId', 'as8eknlll');
I'm not sure how this differs from the current answer (which uses &uid), but this solution is working for us.
You should set userId beofre sending event to Google Analytics. I couldn't manage to send userId after sending events pageview and ecommerce:send.
It appears from Justin Cutroni's blog that he's saying that data stitching (in your case matching the userid prior to login to the userid post-login) is not currently offered in Google Analytics.
http://cutroni.com/blog/2014/04/10/understanding-cross-device-measurement-and-the-user-id/
See specifically this sentence: "Google Analytics will not go back in time and stitch every single session from a given user together."
If you are using Google Tag Manager you can set the User ID by added '&uid' as a field to your Google Analytics Setting variable:

Analytics Tracking of a dynamic page

I am using Google analytics and wish to differentiate between two different cases on the home page, specifically depending on the user being logged in or logged out (similar to facebook).
It was suggested to use a different URL for each page, but I am loathe to do at it involves modifying the website structure and involves needless redirects and complexity.
Is there a way to modify the Google analytics to track this (eg so paths through the site are tracked differently for each case)? I have read about tracking events but I don't think this is correct.
Write out a <meta> tag on the server side if the user is logged in, then check in the js for it and change what is being tracked in the _trackPageview() call?
this may make it look like another webpage but I use this as an onclick event so I don't see why it could be used here some how;
pageTracker._trackPageview('/unauthorised-homepage-viewer');
alternatively use the _setCustomVar method
You could alternatively use custom variables. You'll find the documentation in the Google Analytics help site.
Edit: See especially example 2 under the "Example Use Cases":
For example, if your website offer
users the ability to login, you can
use a custom variable scoped to the
session level for user login status.
In that way, you can segment visits by
those from logged in members versus
anonymous visitors.
pageTracker._setCustomVar(
1, // This custom var is set to slot #1
"User Type", // The name of the custom varaible
"Member", // Sets the value of "User Type" to "Member" or
"Visitor" depending on status
2 // Sets the scope to session-level );
pageTracker._trackPageview();
Google analytics allows you to see content by url, the default in overview, or by title.
You can change dynamically the title of the page.

Categories