Custom GTM Loader For Server-side Tagging

by datatabloid_difmmk

Last updated: October 18, 2021. Peview now works with proxied containers even if the container ID is overridden.

Server-side tagging already has a nice built-in client for proxying Google Tag Manager containers through your own first party domain, but it’s not perfect.

The main problem is that you can’t separate access by origin, so requests for allowlisted container IDs can come from anywhere, and you can’t freely choose the path the container ID takes. is loaded.

To address these issues, I am happy to reveal that I wrote New client template for the Server container, named GTM loader.

GTM loader

The main features of this template are:

  • You are free to choose which request path the client will respond to.leave it as default /gtm.jsor you can choose something more imaginative like /green-dragons.
  • Always load a container with a specific ID, regardless of what the container contains. ?id= Request parameters.
  • Only allow requests from specific origins.

Read on for more information.


X


shimmer newsletter

Subscribe to our Simmer newsletter to receive the latest news and content from Simo Ahava right in your email inbox!

get the template

As Community template gallery has not yet distributed the client template, so you must manually import the template file.

First, get the raw template.tpl Get the files from the GitHub repository by: this link the page template.tpl on your computer.

then your server container, go to template and click new in the client template box

New client template

in the overflow menu in the upper right corner of the screen import.

Import template

find template.tpl Download the file from the container, wait for the editor to update with the GTM loader template, then keep Save your template.

save template

create a new client

head to client In the container, click new Create a new client.

new client

From the list of available clients, GTM loader client.

You are now ready to customize your new client!

configure the client

Below is what the client looks like with all the available fields displayed.

editable client

request path

Set this to your path (include the leading slash).You can also leave the default /gtm.js if you wish.

The client listens for requests to this path. Perfect match is done, the client claims the request and works its wonders.

For example, if you set your path to /google_tag_manager.js As in the screenshot above, a request to https:///google_tag_manager.js?id=GTM-ABCDEFG Load a Google Tag Manager container using its ID GTM-ABCDEFG unless you also have Overriding the container ID Settings were checked (more on this below).

Please remember that Perfect match! The request must use a path that exactly matches the settings configured in this client.

Overriding the container ID

important! By overriding the container ID, preview The container loads, but the browser has to make additional requests www.googletagmanager.com. If your site has a Content Security Policy, https://www.googletagmanager.com You still need to add it for preview mode to work properly.

With this setting on, you can add any valid Google Tag Manager container ID to the respective field.

This setting no matter what is in ?id= parameterwhich returns the container with the configured id.

You can actually drop it by checking this setting. ?id= The container with the configured id is loaded in all cases, so it gets the parameters completely from the request.

allowed origins

In this field you can add a comma separated list origin Only requests from will be honored.

For example, if you add https://www.teamsimmer.com,https://www.simoahava.com field, only requests from those two origins can get the container.

please remember Yuan is a scheme (http Also https)plus :// Plus hostname plus port. So basically everything up to the request path.

You can also add * In this case, the client requests the request regardless of where the request originated.

If you need to manually provide the origin (for example, when working with embedded resources or testing), you can add it. &origin=<origin> to the request URL.For example, to load the container even when I’m not on https://www.simoahava.com this[Allowed Origins]Once set in the field, you can reference it like this:

https:///google_tag_manager.js?id=GTM-ABCDEFG&origin=https://www.simoahava.com

Usage

A template-created client listens for requests dispatched to the request path defined in the client configuration.

Validate your request

When such a request is received, the client does two checks:

  1. that is Overriding the container ID The settings are checked and a valid GTM container ID is configured or a valid GTM container ID is id Query parameters for the request?
  2. is the value of allowed origins Wildcard (*) OR the request is coming from an allowed origin or has an allowed origin as the value of OR origin Query parameters for the request?
// If the incoming request matches the request configured in the Client
if (requestPath === data.requestPath) {
  
  // If the request is for a valid GTM container ID
  if (!containerId.match('^GTM-.+$')) return;
  
  // If the request comes from a valid origin
  if (!validateOrigin()) return;
  
  ...
}

if both resolve truethe request is requested.

Fetch the preview container

the request is preview container, i.e. gtm_debug, gtm_authWhen gtm_preview With query parameters, the client acts as a transparent proxy.

Forwards the request to the GTM server, leaving all headers and parameters intact, and returns the result to the request source.

const fetchPreviewContainer = () => {
  sendHttpGet(
    httpEndpoint  + 
              '&id=' + containerId + 
              '&gtm_auth=' + gtm_auth + 
              '&gtm_debug=' + gtm_debug + 
              '&gtm_preview=' + gtm_preview, 
    (statusCode, headers, body) => {
      sendResponse(body, headers, statusCode);
    }, {timeout: 1500}
  );
};

Importantly, when the preview container is fetched, the result not cachedThis is essential for convenient previewing. Otherwise, users will have to wait for the cache to expire before the updated preview container is available.

Fetch live container

When live While the container is being fetched, the process changes quite a bit.

the template uses templateDataStorage,in short APIs Designed to persist information between requests within the Server container.

When a live container request arrives, the client checks to see if a cached version of the library already exists. When If resource is less than cached time 7.5 minutes agoIn this case, the cached library (and cached headers) will be returned to the requester.

This way the client saves resources You no longer need to fetch resources from Google servers.

Why is the cache duration 7.5 minutes? half of browser cache time The GTM library itself (15 minutes). In this way, the browser cache has the final say on how long to cache resources, but unlike the browser cache, all users Server-side caching is available even if the user has never downloaded the resource before.

If the resource is not cached or the cache has expired, the container will be fetched from Google servers.

const fetchLiveContainer = () => {
  const now = getTimestampMillis();
  
  // Set timeout to 7.5 minutes
  const storageTimeout = now - cacheMaxTimeInMs;
  
  // If the cache has expired fetch library from Google servers and write response to cache
  if (!templateDataStorage.getItemCopy(storedJs) || 
      templateDataStorage.getItemCopy(storedTimeout) < storageTimeout) {
    sendHttpGet(
      httpEndpoint + '&id=' + containerId, 
      (statusCode, headers, body) => {
        if (statusCode === 200) {
          templateDataStorage.setItemCopy(storedJs, body);
          templateDataStorage.setItemCopy(storedHeaders, headers);
          templateDataStorage.setItemCopy(storedTimeout, now);
        }
        sendResponse(body, headers, statusCode);
      }, {timeout: 1500}
    );
  // Otherwise, pull the item from cache and do not make a request to Google servers
  } else {
    sendResponse(
      templateDataStorage.getItemCopy(storedJs),
      templateDataStorage.getItemCopy(storedHeaders),
      200
    );
  }
};

yes templateDataStorage It acts as an additional layer of caching here, reducing server response latency and network egress costs.

Overview

Why create such a template when the built-in web container client works just fine?

Cynics can say this is an improved way to get around ad blockers.this do Makes it easier to bypass ad blockers. googletagmanager.com not just the domain gtm.js file and GTM-... Container ID.

However, we designed the template to give you more flexibility when moving Google Tag Manager into a first party context. Being able to optimize request paths and query parameters seems like an obvious enhancement.of templateDataStorage The setup adds a layer of cost optimization.

But there’s also the twist that an ad blocker targeting Google Tag Manager might be throwing your baby out with the bath water. GTM itself is not a tracking tool and is often used for purposes completely unrelated to tracking or data collection.

That said, if we were to design an ad blocker today, it would probably block GTM as well. Because the water in your bath is likely to be very dirty and should be chucked regardless of the collateral damage it causes.

So it’s hard to strike a balance. The only things I can recommend are:

  • You should approach server-side tagging goodwill from the heart.
  • Please do your best improvement rather than encroach Transparency.
  • Become be honest and respectful to your site visitors.
  • Make sure these mechanisms are in place. documented If someone audits the data flow of your site and servers, don’t let your tags get in the way of this important work.

This way you can have some fun with server-side tagging.

You may also like

Leave a Comment

About Us

We’re a provider of Data IT News and we focus to provide best Data IT News and Tutorials for all its users, we are free and provide tutorials for free. We promise to tell you what’s new in the parts of modern life Data professional and we will share lessons to improve knowledge in data science and data analysis field.