Advanced sGTM Cookie Setter

In my previous blog post, I tried to display different methods to persist session-data and create a session data model (post). One of the options discussed was setting a Cookie using your sGTM container, that contains an object with all the relevant session data, that you want to persist. Thinking about this, I’ve built a tag template for sGTM to set such a cookie without coding yourself. In this post, we’re going to take a quick look at the template and explain, how to use it.

How does the template work?
// Load template APIs
const setCookie = require('setCookie');
const getCookieValues = require('getCookieValues');
const getEventData = require('getEventData');
const JSON = require('JSON');
const logToConsole = require('logToConsole');
const parseUrl = require('parseUrl');
const parsedUrl = parseUrl(getEventData('page_location'));
const fromBase64 = require('fromBase64');
const toBase64 = require('toBase64');
const generateRandom = require('generateRandom');

// Declare constants
const randomValue = generateRandom(10000000, 99999999);
const ts = getEventData('timestamp');
const id = randomValue + "." + getEventData('timestamp');
const cookie_data = data.cookieContent;
const ex_cookie = (getCookieValues(data.cookieName)[0]) ? getCookieValues(data.cookieName)[0] : undefined;

// Declare empty object to store cookie data
let cookieContents = {};

// Set new cookie if non-existent.
if (!ex_cookie) {
  logToConsole('Set new Cookie');
  cookieContents['session_id'] = id;
  cookie_data.forEach(row => {
    if (row.value) {
      cookieContents[row.name] = row.value;
    }
  });
  if (data.firstHitTs) {
    cookieContents['first_hit_timestamp'] = ts;
  }
  if (data.lastHitTs) {
    cookieContents['lastest_hit_timestamp'] = ts;
  }
// Update existing cookie.
} else {
  if (data.toBase64) {
    cookieContents = fromBase64(ex_cookie);
  } else {
    cookieContents = ex_cookie;
  }
  cookieContents = JSON.parse(cookieContents);
  if (data.lastHitTs) {
    cookieContents['lastest_hit_timestamp'] = ts;
  }
  cookie_data.forEach(row => {
    if (row.value && row.updateData) {
      cookieContents[row.name] = row.value;
    }
  });
}

// Log Object to Debug console.
logToConsole(cookieContents);

// Set cookie
let stringValue = JSON.stringify(cookieContents);
stringValue = (data.toBase64) ? toBase64(stringValue) : stringValue;
const name = data.cookieName;
const value = stringValue;
const options = {
  domain: data.cookieDomain,
  path: '/',
  secure: true,
  sameSite: data.cookieSameSite
};
if (data.cookieExpiration > 0) options['max-age'] = data.cookieExpiration;
if (data.cookieHttpOnly) options.HttpOnly = data.cookieHttpOnly;
setCookie(name, value, options, !data.cookieEncodeValue);

data.gtmOnSuccess();

The tag template sets a cookie, with an object as its value. The values within the object can be configured in sGTMs template when setting up the tag. Next to your custom data, it automatically generates a session-id and has the ability to set a first hit timestamp as well as a latest hit timestamp. Since some session data is set by the time a session starts, while others is updated during a session, you can choose whether the data should be updated after the cookie was set for every row. To be a little less transparent towards others, you can optionally base64 encode the cookie value.

There is one important thing to be aware of, when using the template:

The cookie will be set in the incoming hits response – thus, the data within the cookie is not accessible for tags that fire on the same hit, as this template does. That is why I’d recommend sending a generic event on load upfront to every other event (e.g. page_view). This generic events instructs the sGTM container to set/update the cookie. Afterwards, you can send all other events and read the cookie values with every incoming hit.

How to set it up
  1. Import the template from my GitHub: https://github.com/ramonseradj/origin_cookie/blob/main/Origin-Cookie.tpl
  2. Create a new tag with the type “Origin Cookie” and configure it your taste
  3. Set up a Client-Side event that handles cookie setting and updates
  4. Import the variable template from my GitHub to read your cookie’s contents: https://github.com/ramonseradj/origin_cookie/blob/main/Origin-Cookie-Extractor.tpl
  5. Add the cookie’s data to your server-side tags (e.g. GA4) and check, if everything is working as expected.
A few last words

This template enables you to persist both session and user data. Always keep in mind, that privacy and data protection are more import than data collection – so take consent and your user’s privacy in consideration before using the tag blindly. As with all other solutions in the technical marketing space, it has be used responsibly.