#GTMTips: Create a custom Universal Analytics client for server-side tagging – News Couple
ANALYTICS

#GTMTips: Create a custom Universal Analytics client for server-side tagging


You can benefit Server-side labeling in Google Tag Manager to create your custom Universal Analytics Agent.

This proxy comes in the form of a file Client Custom template, which takes a file /collect It requests it and sends it to Google Analytics. While doing this, you are also returning _ga cookie in a Set-Cookie header , which prevents Safari’s Intelligent Tracking Prevention from setting it to only expire for 7 days.

You may also be interested in reading Google’s solution for migrating from JavaScript cookies to those specified in HTTP headers.

I also made a video similar Although it is a bit more advanced than this written tutorial.

note! The video contains one important omission. When creating a file Client Make sure to update the Send HTTP Requests permission to include Allow Google Domains. Otherwise creating a proxy for analytics.js doesn’t work.

If the video doesn’t work, you can watch it here.


X


Simmer . Newsletter

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

Tip 117: Build a Universal Analytics Client

For things to work, you need two things:

  • Server-side labeling setup is fully functional.
  • A client running in a server container (we’ll build this now).
  • The Universal Analytics tag in the server container (I’ll direct this as well).
  • Modifications to everyone Activate Universal Analytics tags in a web container (yes, I’ll help you with that too).

will use Universal Analytics regular tags in the web container, but you will set their transport URL field to point to the server endpoint. These tags will only be used to send data to the server container rather than directly to Google Analytics.

Example of a transfer URL

the following, everyone The Universal Analytics tags in the web container will need the following modification in the fields to be set (it is recommended to use the Google Analytics settings variable).

cookie

This field prevents Universal Analytics JavaScript from updating a file _ga biscuit. Want to do this because the whole purpose of Set-Cookie The header we will configure in the server container is to prevent the web browser from setting _ga Cookie with javascript. Safari prevents all cookies set by JavaScript from having an expiration longer than 7 days.

Remember, this field must be set everyone Universal Analytics tags. Even a single tag without this will rewrite the cookie when activated, thus eliminating any benefit you derive from the custom client.

Finally, the agent himself.

customer building

To build the proxy, you need a file customer template, built into the server container. In the server container user interface, browse to templates and click to create file Client Model.

New customer model

On the first tab, give the template a name and a short description. If you want, you can also add an icon image.

For this specific model, you can skip a file fields tab. We don’t need the customer to support any customization.

in a cipher, copy and paste the following:

const claimRequest = require('claimRequest');
const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const getCookie = require('getCookieValues');
const getRemoteAddress = require('getRemoteAddress');
const getRequestHeader = require('getRequestHeader');
const isRequestMpv1 = require('isRequestMpv1');
const returnResponse = require('returnResponse');
const runContainer = require('runContainer');
const setCookie = require('setCookie');
const setPixelResponse = require('setPixelResponse');
const setResponseHeader = require('setResponseHeader');

// Get User-Agent and IP from incoming request
const ua = getRequestHeader('user-agent');
const ip = getRemoteAddress();

// Check if request is Measurement Protocol
if (isRequestMpv1()) {
  // Claim the request
  claimRequest();
  
  const events = extractEventsFromMpv1();
  const max = events.length - 1;
  events.forEach((event, i) => {
    // Unless the event had IP and user-agent overrides, manually
    // override them with the IP and user-agent from the request
    // That way the GA collect call will appear to have originated
    // from the user's browser / device.
    if(!event.ip_override && ip) event.ip_override = ip;
    if(!event.user_agent && ua) event.user_agent = ua;
    
    // Pass the event to a virtual container
    runContainer(event, () => 
      
      if (i === max) 
        
        // Rewrite the _ga cookie to avoid Safari expiration.
        const ga = getCookie('_ga');
        if (ga && ga.length) 
          setCookie('_ga', ga[0], 
            domain: 'auto',
            'max-age': 63072000,
            path: '/',
            secure: true,
            sameSite: 'lax'
          );
        
        setPixelResponse();
        
        // Make sure no CORS errors pop up with the response
        const origin = getRequestHeader('Origin');
		if (origin) 
          setResponseHeader('Access-Control-Allow-Origin', origin);
          setResponseHeader('Access-Control-Allow-Credentials', 'true');
        
        returnResponse();
      
    );
  });
}

Once the APIs are loaded, the client pulls the source IP address and user agent string with this:

const ua = getRequestHeader('user-agent');
const ip = getRemoteAddress();

After that, file isRequestMpv1 The API is used to automatically check if an incoming HTTP request is a Measurement Protocol (v1 ie Universal Analytics) request. If so, then the customer Claims The request, thus preventing other customers from processing it.

The rest of the client takes care of iterating through all the events in the request, automatically parsing them into the requested event plot (using extractEventsFromMpv1 API), and run the container with all events in the batch.

There is usually only one event per batch.

if (!event.ip_override && ip) event.ip_override = ip;
if (!event.user_agent && ua) event.user_agent = ua;

The above two lines of code have a very important function. Taking the user The IP address and User-Agent string and pass them to the event data object so that the Universal Analytics tag can then add it to the request outgoing to Google. If you don’t set it, the IP address and User-Agent string will be set to those in the server container itself, which is very unhelpful.

Once all events have been handled by the container, the following block of code is run:

const ga = getCookie('_ga');
if (ga && ga.length) 
  setCookie('_ga', ga[0], 
    domain: 'auto',
    'max-age': 63072000,
    path: '/',
    secure: true,
    sameSite: 'lax'
  );

This part of the code checks the incoming HTTP request for a cookie named _ga. If it finds a cookie, it rewrites the cookie with the . extension Set-Cookie header file, thus turning it into an HTTP cookie and helping to resolve expiration issues with Safari’s ITP.

setPixelResponse() It automatically initializes the response back to the request source to resemble a 1×1 GIF with cache busting headers. finally, returnResponse() Indicates that the customer has completed his work and can respond to the source of the initial request.

Set permissions

While in the form editor, visit Permissions tab.

Permissions tab

Set the permissions as follows:

  • up to response: Which
  • Reads cookie value(s): _ga
  • read request: Which
  • Set cookie: set as in the picture above.

Once you are done with the permissions, you can Memorizes template and exit the template editor.

Create the client, trigger, and tag

After that, go to Client and click new Button to create a new customer.

Choose your new customer template from the list of available customer types. Next, set a file priority to a high value. It is important that this value be higher than any thing else The Universal Analytics client you may have in the container.

New client settings

Give the customer a descriptive name (you’ll need this soon), then save This client.

Then go to Tags UI and click new button to create a new tag.

Choose Google Analytics: Universal Analytics as a tag type. There is no need to configure this tag in any way.

Under Catalysts, tap the player area to select a trigger.

Universal Analytics

In the overlay, click the blue button + Button in the upper right corner to create a new launcher.

Trigger configuration

Set the trigger to look like above. It only needs one condition. The name you’re checking is the name you just gave the new customer.

If you don’t see customer name In the list of available variables, it means that you have not enabled it as a file built-in variable distance. Choose Choose a built-in variable From the dropdown menu, choose Client Name from the overlay that appears.

Once done, save the trigger. Then save the tag.

you have now Client, The Effects, and the logo card.

You are ready to fully test the setup!

Preview and test

tap on preview button in the server container. A new tab should open with the server container preview panel.

in your web container, similarly click preview button.

Now you should have both your web container and server container in preview mode.

Then, browse to your site and do something to launch one of the Universal Analytics tags I designed for server-side assembly. Once the tag is activated, check the preview panel in the server container. You should see something like this:

page_view in preview

If you see it, and there are no errors in the Errors tab, it should work!

You can make further correction by selecting a file Universal Analytics Tag itself and then click outgoing HTTP requests can. This opens the order details to Google Analytics.

Outgoing HTTP request

Check the real-time report in the Google Analytics view (You You have Create a separate site for server-side tagging results, right?), and make sure the data is flowing.

Finally, check your browser’s cookies. The _ga The cookie must have a value Believe set to true and value same site set to Lax. If that’s what you see, the cookie rewriting worked!

SameSite and secure cookie

summary

There’s a lot of new stuff here, so I wouldn’t be surprised if it’s hard to set up. However, if you follow this guide seriously, and make sure that there are no fraudulent tags to be launched without it cookieUpdateThe customer must do his job well.

If you run into problems, let me know in the comments and we can take a look together.

Server-side tagging is the new paradigm of Google tagging solutions. I can see a lot of amazing things you can do with it in the future, but now you can also use it to incrementally improve the quality of your data with solutions like this one.



Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button