How to set `ga_session_id` with google tag manager (gtm)?


by vinnie , in category: SEO Tools , 7 months ago

How to set `ga_session_id` with google tag manager (gtm)?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by alvera_smith , 7 months ago


To set ga_session_id with Google Tag Manager (GTM), you can create a custom JavaScript variable that retrieves the session ID and then use that variable in your tags.

Here are the steps to set it up:

  1. Log in to your Google Tag Manager account and access the relevant container.
  2. Go to the "Variables" section in the left-hand menu.
  3. Create a new variable by clicking on the "New" button.
  4. Choose the variable type as "Custom JavaScript".
  5. In the JavaScript code box, enter the following code:
function() {
  // Generate a new session ID if one doesn't exist
  if (!sessionStorage.getItem('ga_session_id')) {
    var sessionID = Math.random().toString(36).substr(2, 16);
    sessionStorage.setItem('ga_session_id', sessionID);
  return sessionStorage.getItem('ga_session_id');

  1. Save the variable by clicking on "Save" in the upper right corner.
  2. Go to the "Tags" section in the left-hand menu and select the tag where you want to use the ga_session_id variable.
  3. Edit the tag and go to the "Fields to Set" (or similar) option.
  4. Create a new field (e.g., session_id) and set the value to {{YourVariableName}}, where YourVariableName is the name you gave to the JavaScript variable in step 5.
  5. Save the tag.
  6. Submit and publish your changes to make them live on your website.

Now, whenever the tag fires, it will include the ga_session_id value generated by the custom JavaScript variable. Make sure to test your implementation to ensure the variable is being set correctly.