Thanks for previewing Google's new tag platform documentation! This site is in public beta. (Feedback)

Server-side tagging APIs

This document outlines the APIs for server-side tagging.


addEventCallback

Registers a callback function that will be invoked at the end of an event. The callback will be invoked when all the tags for the event have executed. The callback is passed two values: the id of the container that invokes the function and an object that contains information about the event.

When this API is used in a tag, it is associated to the current event. When this API is used in a client, it must be bound to a specific event using the runContainer API's bindToEvent function. See the example for more details.

Syntax

const addEventCallback = require('addEventCallback');

addEventCallback((containerId, eventData) => {
  // Take some action based on the event data.
});

Parameters

Parameter Type Description
callback function The function to invoke at the end of the event.

The eventData object contains the following data:

Key Name Type Description
tags Array An array of tag data objects. Every tag that fired during the event will have an entry in this array. The tag data object contains the tag's ID (id), its execution status (status), and its execution time (executionTime). The tag data will also include additional tag metadata that was configured on the tag.

Example

In a client:

const addEventCallback = require('addEventCallback');
const claimRequest = require('claimRequest');
const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const logToConsole = require('logToConsole');
const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

claimRequest();

const events = extractEventsFromMpv1();
let eventsCompleted = 0;
events.forEach((evt, i) => {
  runContainer(evt, /* onComplete= */ (bindToEvent) => {
    bindToEvent(addEventCallback)((containerId, eventData) => {
      logToConsole('Event Number: ' + i);
      eventData.tags.forEach((tag) => {
        logToConsole('Tag ID: ' + tag.id);
        logToConsole('Tag Status: ' + tag.status);
        logToConsole('Tag Execution Time: ' + tag.executionTime);
      });
    });
    if (events.length === ++eventsCompleted) {
      returnResponse();
    }
  });
});

In a tag:

const addEventCallback = require('addEventCallback');

addEventCallback((containerId, eventData) => {
  // This will be called at the end of the current event.
});

Associated permissions

read_event_metadata


callLater

Schedules a call to a function to occur asynchronously. The function will be called after the current code returns. This is equivalent to setTimeout(<function>, 0).

Example

const callLater = require('callLater');
const logToConsole = require('logToConsole');

callLater(() => {
  logToConsole('Logged asynchronously');
});

Syntax

callLater(function)

Parameters

Parameter Type Description
function function The function to call.

Associated permissions

None.


claimRequest

Use this API in a client to claim the request. Once a request is claimed, the container does not run additional clients.

This API throws an exception if called in a tag or variable. This API throws an exception if called after the client returns (e.g. if called in an async callback such as in callLater or the runContainer onComplete function).

A client should claim the request using this API before calling the runContainer API.

Example

const claimRequest = require('claimRequest');

claimRequest();

Syntax

claimRequest();

Associated permissions

None.


computeEffectiveTldPlusOne

Returns the effective top-level domain + 1 (eTLD+1) of the given domain or URL. The eTLD+1 is computed by evaluating the domain against the Public Suffix List rules. The eTLD+1 is typically the highest-level domain on which you can set a cookie.

If the argument is null or undefined, then the argument value is returned unaltered. Otherwise the argument is coerced to a string. If the argument is not a valid domain or URL, then a blank string is returned. If the server is unable to fetch the public suffix list, then the argument value is returned unaltered.

Example

const computeEffectiveTldPlusOne = require('computeEffectiveTldPlusOne');

// Returns 'example.co.uk'
computeEffectiveTldPlusOne('analytics.example.co.uk');

// Returns 'example.co.uk'
computeEffectiveTldPlusOne('https://analytics.example.co.uk/path');

Syntax

computeEffectiveTldPlusOne(domainOrUrl);

Parameters

Parameter Type Description
domainOrUrl string A domain or URL on which to compute the eTLD+1.

Associated permissions

None.


decodeUri

Decodes any encoded characters in the provided URI. Returns a string that represents the decoded URI. Returns undefined when provided with invalid input.

Example

const decodeUri = require('decodeUri');

const decodedUrl = decodeUri(data.encodedUrl);
if (decodedUrl) {
  // ...
}

Syntax

decodeUri(encoded_uri);

Parameters

Parameter Type Description
encoded_uri string A URI that has been encoded by encodeUri() or by other means.

Associated permissions

None.


decodeUriComponent

Decodes any encoded characters in the provided URI component. Returns a string that represents the decoded URI component. Returns undefined when given invalid input.

Example

const decodeUriComponent = require('decodeUriComponent');

const decodedQuery = decodeUriComponent(data.query);
if (decodedQuery) {
  // ...
}

Syntax

decodeUriComponent(encoded_uri_component);

Parameters

Parameter Type Description
encoded_uri_component string A URI component that has been encoded by encodeUriComponent() or by other means.

Associated permissions

None.


encodeUri

Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI.

Example

const encodeUri = require('encodeUri');
const sendHttpGet = require('sendHttpGet');

sendHttpGet('https://www.example.com/' + encodeUri(pathInput));

Syntax

encodeUri(uri);

Parameters

Parameter Type Description
uri string A complete URI.

Associated permissions

None.


encodeUriComponent

Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI.

Example

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');

sendHttpGet('https://www.example.com/?' + encodeUriComponent(queryInput));

Syntax

encodeUriComponent(str);

Parameters

Parameter Type Description
str string A component of a URI.

Associated permissions

None.


extractEventsFromMpv1

Translates an incoming Measurement Protocol V1 request into a list of events in Unified Schema format. Returns the list of extracted events. Throws an error if the request is not in the correct format.

Example

const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const isRequestMpv1 = require('isRequestMpv1');

if (isRequestMpv1()) {
  const events = extractEventsFromMpv1();
  for (let i = 0; i < events.length; ++i) {
    const event = events[i];
    // Process event.
  }
}

Syntax

extractEventsFromMpv1();

Associated permissions

Requires read_request permission. The permission must be configured to permit access to at least:

  • body
  • query parameters

extractEventsFromMpv2

Translates an incoming Measurement Protocol V2 request into a list of events in Unified Schema format. Returns the list of extracted events. Throws an error if the request is not in the correct format.

Example

const extractEventsFromMpv2 = require('extractEventsFromMpv2');
const isRequestMpv2 = require('isRequestMpv2');

if (isRequestMpv2()) {
  const events = extractEventsFromMpv2();
  for (let i = 0; i < events.length; ++i) {
    const event = events[i];
    // Process event.
  }
}

Syntax

extractEventsFromMpv2();

Associated permissions

Requires read_request permission. The permission must be configured to permit access to at least:

  • body
  • query parameters

fromBase64

Decodes a base64-encoded string. Returns undefined if the input is invalid.

Syntax

fromBase64(base64EncodedString);

Parameters

Parameter Type Description
base64EncodedString string Base64 encoded string.

Example

const fromBase64 = require('fromBase64');

const greeting = fromBase64('aGVsbG8=');
if (greeting === 'hello') {
  // ...
}

Associated permissions

None.


generateRandom

Returns a random number (integer) within the given range.

Example

const generateRandom = require('generateRandom');

const randomValue = generateRandom(0, 10000000);

Syntax

generateRandom(min, max);

Parameters

Parameter Type Description
min number Minimum potential value of the returned integer (inclusive).
max number Maximum potential value of the returned integer (inclusive).

Associated permissions

None.


getAllEventData

Returns a copy of the event data.

Syntax

getAllEventData();

Associated permissions

read_event_data


getClientName

Returns a string that contains the name of the current client.

Syntax

getClientName();

Associated permissions

read_container_data


getContainerVersion

Returns an object containing data about the current container. The returned object will have the following fields:

{
  containerId: string,
  debugMode: boolean,
  environmentName: string,
  environmentMode: boolean,
  previewMode: boolean,
  version: string,
}

Example

const getContainerVersion = require('getContainerVersion');

const containerVersion = getContainerVersion();
const containerId = containerVersion['containerId'];
const isDebug = containerVersion['debugMode'];

Syntax

getContainerVersion();

Associated permissions

read_container_data


getCookieValues

Returns an array containing the values of all cookies with the given name.

Example

const getCookieValues = require('getCookieValues');

const lastVisit = getCookieValues('lastVisit')[0];
if (lastVisit) {
  // ...
}

Syntax

getCookieValues(name[, noDecode]);

Parameters

Parameter Type Description
name string Name of the cookie.
noDecode boolean If true, the cookie values will not be decoded before being returned. Defaults to false.

Associated permissions

get_cookies


getEventData

Returns a copy of the value at the given path in the event data. Returns undefined if there is no event data or if there is no value at the given path.

Example

const getEventData = require('getEventData');

const campaignId = getEventData('campaign.id');
const itemId = getEventData('items.0.id');
const referrer = getEventData('page_referrer');

Parameters

Parameter Type Description
keyPath any The path of the key, where path components are separated by dots. The path components can be keys in an object or indices in an array. If keyPath is not a string, it is coerced into a string.

Syntax

getEventData(keyPath);

Associated permissions

read_event_data


getGoogleScript

Retrieves a resource from a predetermined set of Google scripts, and invokes the provided callback with the script and associated caching metadata.

The metadata object will contain the following caching metadata based on the resource response headers; each field will only be present if the corresponding header is present in the resource response.

{
  'cache-control': string,
  'expires': string,
  'last-modified': string,
}

Example

const getGoogleScript = require('getGoogleScript');

getGoogleScript('ANALYTICS', (script, metadata) => {
  // Operate on script and metadata here.
});

Syntax

getGoogleScript(script, callback[, options]);

Parameters

Parameter Type Description
script string The name of the script. Supported scripts are 'ANALYTICS', 'GTAG', and 'GTM'.

The 'ANALYTICS' option fetches the Google Analytics script from https://www.google-analytics.com/analytics.js.

The 'GTAG' option fetches the global site tag (gtag.js) script from https://www.googletagmanager.com/gtag/js.

The 'GTM' option fetches the Google Tag Manager script from https://www.googletagmanager.com/gtm.js.
callback function A callback that will be invoked with the script and its metadata, or undefined and an empty metadata object if the request fails or times out.
options object Optional request options. See below for supported options.

Options

Option Type Description
id string Applicable to 'GTAG' with the gtag measurement ID and 'GTM' with the web container ID (ex. GTM-XXXX).
debug any If truthy, requests and returns the debug version of the measurement script.
timeout number The request timeout in milliseconds; non-positive values are ignored. If the request times out, the callback will be invoked with undefined for the script value and {} for the metadata object.

Unrecognized option keys are ignored.

Associated permissions

Requires send_http permission. The permission must be configured to permit access to at least:

  • Allow Google Domains

getRemoteAddress

Returns a string representation of the IP address where the request originated, e.g. 12.345.67.890 for IPv4 or 2001:0db8:85a3:0:0:8a2e:0370:7334 for IPv6, by reading request headers such as Forwarded and X-Forwarded-For. Note: this API makes a best-effort attempt to discover the originating IP, but it cannot guarantee that the result is accurate.

Syntax

getRemoteAddress();

Associated permissions

Requires read_request permission. The permission must be configured to permit access to at least:

  • Headers Forwarded and X-Forwarded-For
  • Remote IP Address

getRequestBody

Returns the request body as a string, if present, or undefined otherwise.

Syntax

getRequestBody();

Associated permissions

read_request


getRequestHeader

Returns the value of the named request header as a string, if present, or undefined otherwise. If the header is repeated, the returned values are joined together with ', '.

Example

const getRequestHeader = require('getRequestHeader');

const host = getRequestHeader('host');

Syntax

getRequestHeader(headerName);

Parameters

Parameter Type Description
headerName string The header name. This value is case-insensitive.

Associated permissions

read_request


getRequestMethod

Returns the request method, e.g. 'GET' or 'POST', as a string.

Example

const getRequestMethod = require('getRequestMethod');

if (getRequestMethod() === 'POST') {
  // Handle the POST request here.
}

Syntax

getRequestMethod();

Associated permissions

None.


getRequestPath

Returns the request path without the query string. For example, if the URL is '/foo?id=123', this returns '/foo'. Automatically strips the Server container URL prefix from the path. For example, if Server container URL is https://example.com/analytics and the request path is '/analytics/foo', this returns '/foo'.

Example

const getRequestPath = require('getRequestPath');

const requestPath = getRequestPath();
if (requestPath === '/') {
  // Handle a request for the root path.
}

Syntax

getRequestPath();

Associated permissions

read_request


getRequestQueryParameter

Returns the decoded value of the named query string parameter as a string, or undefined if the parameter is not present. If the parameter is repeated in the query string, the first value that appears in the query string will be returned.

Example

const getRequestQueryParameter = require('getRequestQueryParameter');

const query = getRequestQueryParameter('query');
if (query) {
  // Process query here.
}

Syntax

getRequestQueryParameter(name);

Parameters

Parameter Type Description
name string The query parameter name.

Associated permissions

read_request


getRequestQueryParameters

Returns the incoming HTTP request's query parameters as an object that maps query parameter names to the corresponding value or values. The parameter names and values are decoded.

Example

const getRequestQueryParameters = require('getRequestQueryParameters');

const queryParameters = getRequestQueryParameters();
if (queryParameters['search']) {
  // Handle the search query here.
  const maxResults = queryParameters['max_results'];
}

Syntax

getRequestQueryParameters();

Associated permissions

read_request


getRequestQueryString

Returns the request query as a string, without the leading question mark, or an empty string if the request URL does not include a query string.

Example

const getRequestQueryString = require('getRequestQueryString');

const queryString = getRequestQueryString();
if (queryString !== '') {
  // Handle the query string.
}

Syntax

getRequestQueryString();

Associated permissions

read_request


getTimestamp

Deprecated. Prefer getTimestampMillis.

Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now().

Syntax

getTimestamp();

Associated permissions

None.


getTimestampMillis

Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now().

Syntax

getTimestampMillis();

Associated permissions

None.


getType

Returns a string describing the given value's type.

Input Type Returned Value
string 'string'
number 'number'
boolean 'boolean'
null 'null'
undefined 'undefined'
Array 'array'
Object 'object'
Function 'function'

Example

const getType = require('getType');

const type = getType(value);
if (type === 'string') {
  // Handle string input.
} else if (type === 'number') {
  // Handle numeric input.
} else {
  logToConsole('Unsupported input type: ', type);
}

Syntax

getType(value);

Parameters

Parameter Type Description
value any Input value.

Associated permissions

None.


isRequestMpv1

Returns true if the incoming request is a Measurement Protocol V1 request, or false otherwise.

Example

const isRequestMpv1 = require('isRequestMpv1');

if (isRequestMpv1()) {
  // Handle Measurement Protocol V1 request.
  const events = extractEventsFromMpv1();
}

Syntax

isRequestMpv1();

Associated permissions

None.


isRequestMpv2

Returns true if the incoming request is a Measurement Protocol V2 request, or false otherwise.

Example

const isRequestMpv2 = require('isRequestMpv2');

if (isRequestMpv2()) {
  // Handle Measurement Protocol V2 request.
  const events = extractEventsFromMpv2();
}

Syntax

isRequestMpv2();

Associated permissions

None.


logToConsole

Logs its argument(s) to the console.

These logs are visible within Logs Explorer in the Google Cloud Console. From Logs Explorer run the query logName =~ "stdout" to see log entries created by this API.

Example

const logToConsole = require('logToConsole');

const that = 123;
const those = { ... };
logToConsole('that is: ', that, ' and those is: ', those);

Syntax

logToConsole(argument1[, argument2, ...]);

Parameters

The API takes one or more arguments, each of which is converted to a string, if necessary, and logged to the console.

Associated permissions

logging


makeInteger

Converts the given value to a number (integer).

Syntax

makeInteger(value);

Parameters

Parameter Type Description
value any type The value to convert.

Associated permissions

None.


makeNumber

Converts the given value to a number.

Syntax

makeNumber(value);

Parameters

Parameter Type Description
value any type The value to convert.

Associated permissions

None.


makeString

Returns the given value as a string.

Syntax

makeString(value);

Parameters

Parameter Type Description
value any type The value to convert.

Associated permissions

None.


makeTableMap

Converts a simple table object with two columns to a Map. This is used to change a SIMPLE_TABLE template field with two columns into a more manageable format.

For example, this function could convert a table object:

[
  {'key': 'k1', 'value': 'v1'},
  {'key': 'k2', 'value': 'v2'}
]

into a Map:

{
  'k1': 'v1',
  'k2': 'v2'
}

Returns an Object: The converted Map of key-value pairs have been added to it, or null otherwise.

Syntax

makeTableMap(tableObj, keyColumnName, valueColumnName);

Parameters

Parameter Type Description
tableObj List The table object to convert. It's a list of maps where each Map represents a row in the table. Each property name in a row object is the column name, and the property value is the column value in the row.
keyColumnName string Name of the column whose values will become keys in the converted Map.
valueColumnName string Name of the column whose values will become values in the converted Map.

Associated permissions

None.


parseUrl

Returns an object that contains all of a given URL's component parts, similar to the URL object.

This API will return undefined for any malformed URL. For properly formatted URLs, fields not present in the URL string will have a value of an empty string, or in the case of searchParams, an empty object.

The returned object will have the following fields:

{
  href: string,
  origin: string,
  protocol: string,
  username: string,
  password: string,
  host: string,
  hostname: string,
  port: string,
  pathname: string,
  search: string,
  searchParams: Object<string, (string|Array)>,
  hash: string,
}

Example

const parseUrl = require('parseUrl');

const urlObject = parseUrl('https://abc:xyz@example.com:8080/foo?param=val%2Cue#bar');

Syntax

parseUrl(url);

Parameters

Parameter Type Description
url string The full url that will be parsed.

Associated permissions

None.


returnResponse

Flushes the response that was previously set by other templates using the APIs that modify the response, including setCookie, setPixelResponse, setResponseBody, setResponseHeader, and setResponseStatus. Defaults to an HTTP status code 200, empty body, and no headers.

It is recommended that this API be used from a client template.

Syntax

returnResponse();

Example

See the runContainer example.

Associated permissions

return_response


runContainer

Runs the container logic (variables, triggers, tags) in the scope of an event. If this API is called during container execution, the container is run again.

The onComplete and onStart callbacks receive a function called bindToEvent. Use bindToEvent to run an API in the context of the event. See the addEventCallback example for more details.

It is recommended that this API be used from a client template.

Example

const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

// Runs the container with a simple pageview event and then returns a response.
runContainer({'event_name': 'pageview'}, () => returnResponse());

Syntax

runContainer(event, onComplete, onStart);

Parameters

Parameter Type Description
event object The event parameters.
onComplete function A callback that is invoked after all the tags finish firing.
onStart function A callback that is invoked immediately, before the tags start firing.

Associated permissions

run_container


sendEventToGoogleAnalytics

Sends a single event in Unified Schema format to Google Analytics.

Example

const sendEventToGoogleAnalytics = require('sendEventToGoogleAnalytics');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');

// Sends an event to Google Analytics and returns failure if the request did not
// succeed. Additionally, if the request resulted in a redirect request, the
// code nominates a redirect response to be returned.
sendEventToGoogleAnalytics(event, (response) => {
  if (!response.success) {
    setResponseStatus(500);
    data.gtmOnFailure();
    return;
  }

  if (response.location) {
    setResponseHeader('location', response.location);
    setResponseStatus(302);
  } else {
    setResponseStatus(200);
  }
  data.gtmOnSuccess();
});

Syntax

sendEventToGoogleAnalytics(event, callback);

Parameters

Parameter Type Description
event object The event in Unified Schema format.
callback function An optional callback to invoke when the hit to GA is completed. It will be invoked with an object with a success and location field.

The success field is set to true if response code is either 200 or 302, and false otherwise. If the response had a location header, the location field is set to the header value.

Associated permissions

Requires send_http permission. The permission must be configured to permit access to at least:

  • Allow Google Domains

sendHttpGet

Makes an HTTP GET request to the specified URL, and invokes a callback with the response once the request completes or times out.

Example

const sendHttpGet = require('sendHttpGet');
const setResponseBody = require('setResponseBody');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');

// Sends a GET request and nominates response
// based on the response from the GET request.
sendHttpGet('https://example.com/collect', (statusCode, headers, body) => {
  setResponseBody(body);
  setResponseHeader('cache-control', headers['cache-control']);
  setResponseStatus(statusCode);
}, {headers: {key: 'value'}, timeout: 500});

Syntax

sendHttpGet(url[, callback[, options]]);

Parameters

Parameter Type Description
url string The request URL.
callback function An optional callback to invoke upon request completion, error, or timeout.

It is invoked with the response status code, the response headers, and the response body (or undefined if there was no response body).
If the request failed (e.g. invalid URL, no route to host, SSL negotiation failure, etc.), the callback will be invoked with a response status code of zero, no headers, and an undefined body.
If the 'timeout' option was set and the request timed out, the callback will be invoked with a response status code of -1, no headers, and an undefined body.
options object Optional request options. The supported options are headers and timeout. Unknown option keys are ignored. (See Options, below.)

Options

  • headers: Additional request headers represented as an object.
  • timeout: The timeout, in milliseconds, before the request is aborted.

Associated permissions

send_http


sendHttpRequest

Makes an HTTP request to the specified URL, and invokes a callback with the response once the request completes or times out.

Example

const sendHttpRequest = require('sendHttpRequest');
const setResponseBody = require('setResponseBody');
const setResponseHeader = require('setResponseHeader');
const setResponseStatus = require('setResponseStatus');

const postBody = 'interaction=click&campaign=promotion&medium=email';
// Sends a POST request and nominates response based on the response to the POST
// request.
sendHttpRequest('https://example.com/collect', (statusCode, headers, body) => {
  setResponseStatus(statusCode);
  setResponseBody(body);
  setResponseHeader('cache-control', headers['cache-control']);
}, {headers: {key: 'value'}, method: 'POST', timeout: 500}, postBody);

Syntax

sendHttpRequest(url[, callback[, options[, body]]]);

Parameters

Parameter Type Description
url string The request URL.
callback function An optional callback to invoke upon request completion, error, or timeout.

It is invoked with the response status code, the response headers, and the response body (or undefined if there was no response body).
If the request failed (e.g. invalid URL, no route to host, SSL negotiation failure, etc.), the callback will be invoked with a response status code of zero, no headers, and an undefined body.
If the 'timeout' option was set and the request timed out, the callback will be invoked with a response status code of -1, no headers, and an undefined body.
options object Optional request options. The supported options are\: headers, method, and timeout. Unknown option keys are ignored. (See Options, below.)
body string Optional request body.

Options

  • headers: Additional request headers.
  • method: The request method, defaults to 'GET'.
  • timeout: The timeout, in milliseconds, before the request is aborted.

Associated permissions

send_http


sendPixelFromBrowser

Sends a command to the browser to load the provided URL as an <img> tag. This command protocol is supported in the Google Analytics: GA4 Configuration and Google Analytics: GA Event web tags. You must enable the Send to server container option in the configuration tag. See the instructions for more details.

This API returns false if the incoming request does not support the command protocol, or if the response has already been flushed. Otherwise this API returns true.

Example:

const sendPixelFromBrowser = require('sendPixelFromBrowser');

sendPixelFromBrowser('https://example.com/?id=123');

Syntax

sendPixelFromBrowser(url)

Parameters

Parameter Type Description
url string The url to send to the browser.

Associated permissions

send_pixel_from_browser


setCookie

Sets or deletes a cookie with the specified options.

To delete a cookie, one must set a cookie with the same path and domain that the cookie was created with, and assign it an expires value that is in the past, e.g. "Thu, 01 Jan 1970 00:00:00 GMT".

Note that returnResponse must be called for the response to be sent back to the client.

Example

const setCookie = require('setCookie');

// Sets an httpOnly cookie with a max-age of 3600.
setCookie('cookieName', 'cookieValue', {'max-age': 3600, httpOnly: true});

Syntax

setCookie(name, value[, options[, noEncode]]);

Parameters

Parameter Type Description
name string The cookie name. The name is case-insensitive.
value string The cookie value.
options object Optional cookie attributes:domain, expires, fallbackDomain,httpOnly, max- age, path, secure, andsameSite. (See Options, below.)
noEncode boolean If true, the cookie value will not be encoded. Defaults to false.

Options

  • domain: The host to which the cookie will be sent. If set to the special value 'auto', then the host will be automatically computed using the following strategy:

    • eTLD+1 of Forwarded header, if present.
    • eTLD+1 of X-Forwarded-Host header, if present.
    • eTLD+1 of Host header.
  • expires: The maximum lifetime of the cookie. This must a UTC-formatted date string, e.g. "Sat, 26 Oct 1985 08:21:00 GMT". If both expires and max-age are set, max-age has precedence.

  • httpOnly: Forbids JavaScript from accessing the cookie if true.

  • max-age: Number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both expires and max-age are set, max-age has precedence.

  • path: A path that must exist in the requested URL, or the browser won't send the Cookie header.

  • secure: If set to true, the cookie is only sent to the server when a request is made from an https: endpoint.

  • sameSite: Asserts that a cookie must not be sent with cross-origin requests. Must be 'strict', 'lax', or 'none'.

Associated permissions

set_cookie


setPixelResponse

Sets response body to a 1x1 GIF, sets the Content-Type header to 'image/gif', sets caching headers such that user agents will not cache the response, and sets the response status to 200.

Note that returnResponse must be called for the response to be sent back to the client.

Syntax

setPixelResponse();

Associated permissions

Requires access_response permission. The permission must be configured to permit access to at least:

  • headers - Must permit the following keys
    • content-type
    • cache-control
    • expires
    • pragma
  • body
  • status

setResponseBody

Sets the response body to the argument.

Note that returnResponse must be called for the response to be sent back to the client.

Syntax

setResponseBody(body[, encoding]);

Parameters

Parameter Type Description
body string The value to set as the response body.
encoding string The character encoding of the response body (defaults to 'utf8'). Supported values include 'ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'latin1', 'binary', and 'hex'.

Associated permissions

Requires access_response permission. The permission must be configured to permit access to at least:

  • body

setResponseHeader

Sets a header in the response that will be returned. If a header with this name (case-insensitive) was previously set by this API, the latter call will overwrite or clear the value set by the prior caller.

Note that returnResponse must be called for the response to be sent back to the client.

Syntax

setResponseHeader(name, value);

Parameters

Parameter Type Description
name string The header name. HTTP header names are case-insensitive, so the header name will be lowercased.
value string undefined The header value. If null or undefined, this clears the named header from the response that will be returned.

Associated permissions

Requires access_response permission. The permission must be configured to permit access to at least:

  • headers

setResponseStatus

Sets the HTTP status code of the response that will be returned.

Note that returnResponse must be called for the response to be sent back to the client.

Syntax

setResponseStatus(statusCode);

Parameters

Parameter Type Description
statusCode number The HTTP status code to be returned.

Associated permissions

Requires access_response permission. The permission must be configured to permit access to at least:

  • status

sha256

Calculates the SHA-256 digest of the input and invokes a callback with the digest encoded in base64, unless the options object specifies a different output encoding.

This API signature and behavior matches the sha256 API for web containers; however, Custom Templates in server containers should use the sha256Sync API for simpler code.

Example

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');
const sha256 = require('sha256');

sha256('inputString', (digest) => {
  sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digest));
});

sha256('inputString', (digest) => {
  sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digest));
}, {outputEncoding: 'hex'});

Syntax

sha256(input, onSuccess, options = undefined);

Parameters

Parameter Type Description
input string The string to hash.
onSuccess function Called with the resulting digest, encoded in base64, unless the options object specifies a different output encoding.
options object Optional options object to specify the output encoding. If specified, the object should contain the key outputEncoding with value as one of base64 or hex.

Associated permissions

None.


sha256Sync

Calculates and returns the SHA-256 digest of the input, encoded in base64, unless the options object specifies a different output encoding.

Example

const encodeUriComponent = require('encodeUriComponent');
const sendHttpGet = require('sendHttpGet');
const sha256Sync = require('sha256Sync');

const digestBase64 = sha256Sync('inputString');
const digestHex = sha256Sync('inputString', {outputEncoding: 'hex'});
sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digestBase64));
sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digestHex));

Syntax

sha256Sync(input, options = undefined);

Parameters

Parameter Type Description
input string The string to hash.
options object Optional options object to specify the output encoding. If specified, the object should contain the key outputEncoding with value as one of base64 or hex.

Associated permissions

None.


templateDataStorage

Returns an object with methods for accessing template data storage. Template data storage allows data to be shared across executions of a single template. Data stored in template data storage persists on the server running the container. In most cases there are multiple servers running the container, so storing data in template data storage does not guarantee that every subsequent request will have access to the data.

The "data" in the name "templateDataStorage" refers to the fact that only plain, non-function data types may be stored using this API. Any functions or references to functions passed to the API will be stored as null instead.

Syntax

const templateDataStorage = require('templateDataStorage');

// Returns a copy of the value stored for the given key, or null if nothing
// is stored with that key.
templateDataStorage.getItemCopy(key);

// Stores a copy of the value for the given key (or removes the data stored
// for the given key if the input value is null).
templateDataStorage.setItemCopy(key, value);

// Removes the value stored for the given key, if present.
templateDataStorage.removeItem(key);

// Deletes all values stored for the current template.
templateDataStorage.clear();

Example

const sendHttpGet = require('sendHttpGet');
const setResponseBody = require('setResponseBody');
const templateDataStorage = require('templateDataStorage');

// Check to see if the item is in the cache.
const cachedBody = templateDataStorage.getItemCopy(data.key);
if (cachedBody) {
  setResponseBody(cachedBody);
  data.gtmOnSuccess();
  return;
}

sendHttpGet(data.url, (statusCode, headers, body) => {
  if (status >= 200 && status < 300) {
    setResponseBody(body);
    templateDataStorage.setItemCopy(data.key, body);
    data.gtmOnSuccess();
  } else {
    data.gtmOnFailure();
  }
  setResponseStatus(statusCode);
});

Associated permissions

access_template_storage


toBase64

Encodes a string as base64.

Syntax

toBase64(input);

Parameters

Parameter Type Description
input string String to encode.

Example

const toBase64 = require('toBase64');

const base64Hello = toBase64('hello');

Associated permissions

None.


BigQuery

Returns an object that provides BigQuery functions.

The BigQuery.insert function allows writing data into a BigQuery table.

Syntax

BigQuery.insert(connectionInfo, rows, options, onSuccess, onFailure);

Parameters

Parameter Type Description
connectionInfo object Defines information required to connect to a BigQuery table. There is one optional parameter and two required parameters:
  • projectId - Optional Google Cloud Platform project ID. If omitted, the projectId is retrieved from the environment variable GOOGLE_CLOUD_PROJECT as long as the access_bigquery permission setting for the project ID is set to * or GOOGLE_CLOUD_PROJECT. If the server container is running on Google Cloud, GOOGLE_CLOUD_PROJECT will already be set to the Google Cloud project's ID.
  • datasetId - BigQuery Dataset ID.
  • tableId - BigQuery Table ID.
rows Array The rows to insert into the table.
options object Optional request options. The supported options are: ignoreUnknownValues and skipInvalidRows. Unknown option keys are ignored. (See Options, below.)
onSuccess function An optional callback to invoke upon a successful insertion. The callback is called with no arguments.
onFailure function An optional callback to invoke upon error. Called with a list of objects containing the error reason and possibly a row object if an error occurs. It's possible for a part of the request to be completed successfully, while other parts are not. The onFailure is called in this case with a list of errors for each row with a row object to help distinguish which rows were inserted (See Error Examples below). See BigQuery's documentation on error messages for more information.

Options

Parameter Type Description
ignoreUnknownValues boolean If set to true, then accept rows that contain values that do not match the schema. The unknown values are ignored. Defaults to false.
skipInvalidRows boolean If set to true, then insert all valid rows of a request, even if invalid rows exist. Defaults to false.

Error Examples

A module not found error means that your server container is likely running an older version of our image that had not included the BigQuery module yet. Please redeploy your server container with the same settings using our deployment script. The module will be automatically included once the operation finishes.

A non-insertion error typically has one error object with a reason key:

[{reason: 'invalid'}]

An insertion error can contain multiple error objects with an errors array and a row object. The following is an example of an error response from inserting two rows where only one row has an error:

[
  {
    "errors": [
      {
        "reason":"invalid"
      }
    ],
    "row": {
      "string_col":"otherString",
      "number_col":-3,
      "bool_col":3
    }
  },
  {
    "errors": [
      {
        "reason":"stopped"
      }
    ],
    "row": {
      "string_col":"stringValue",
      "number_col":5,
      "bool_col:false
    }
  }
]

Example

const BigQuery = require('BigQuery');

const connectionInfo = {
  'projectId': 'gcp-cloud-project-id',
  'datasetId': 'destination-dataset',
  'tableId': 'destination-table',
};

const rows = [{
  'column1': 'String1',
  'column2': 1234,
}];

const options = {
  'ignoreUnknownValues': true,
  'skipInvalidRows': false,
};

BigQuery.insert(connectionInfo, rows, options, data.gtmOnSuccess, data.gtmOnFailure);

Associated permissions

access_bigquery


JSON

Returns an object that provides JSON functions.

The parse() function parses a JSON string to construct the value or object described by the string. If the value cannot be parsed (e.g. malformed JSON), the function will return undefined. If the input value is not a string, the input will be coerced to a string.

The stringify() function converts the input into a JSON string. If the value cannot be parsed (e.g. the object has a cycle), the method will return undefined.

Example

const JSON = require('JSON');

// The JSON input string is converted to an object.
const object = JSON.parse('{"foo":"bar"}');

// The input object is converted to a JSON string.
const str = JSON.stringify({foo: 'bar'});

Syntax

JSON.parse(stringInput);
JSON.stringify(value);

Associated permissions

None.


Math

An object providing Math functions.

Syntax

const Math = require('Math');

// Retrieve the absolute value.
const absolute = Math.abs(-3);

// Round the input down to the nearest integer.
const roundedDown = Math.floor(3.6);

// Round the input up to the nearest integer.
const roundedUp = Math.ceil(2.2);

// Round the input to the nearest integer.
const rounded = Math.round(3.1);

// Return the largest argument.
const biggest = Math.max(1, 3);

// Return the smallest argument.
const smallest = Math.min(3, 5);

// Return the first argument raised to the power of the second argument.
const powerful = Math.pow(3, 1);

// Return the square root of the argument.
const unsquared = Math.sqrt(9);

Parameters

Math function parameters are converted to numbers.

Associated permissions

None.


Messages

The following APIs work together to allow passing messages between different parts of a container.


addMessageListener

Adds a function that listens for a message of a particular type. When a message of that type is sent using the sendMessage API (typically by a tag), the callback will be run synchronously. The callback is run with two parameters:

  1. messageType:string
  2. message:Object

If the callback is added in a client, the callback will receive messages across all of the events that client creates. If the callback should receive messages from only a certain event, then bind this API to the event using bindToEvent in the runContainer API's onStart function. See the example.

Syntax

const addMessageListener = require('addMessageListener');

addMessageListener('send_pixel', (messageType, message) => {
  // This will be run whenever something sends a 'send_pixel' message.
});

Parameters

Parameter Type Description
messageType string The message type to listen for. If the value is not a string, it will be coerced to a string.
callback function The callback to run when a message of the applicable message type is sent. If the callback is not a function, the API will do nothing.

Example

const addMessageListener = require('addMessageListener');
const claimRequest = require('claimRequest');
const extractEventsFromMpv1 = require('extractEventsFromMpv1');
const returnResponse = require('returnResponse');
const runContainer = require('runContainer');

claimRequest();
addMessageListener('send_pixel', (messageType, message) => {
  // This will be run whenever a tag sends a 'send_pixel' message.
});

const events = extractEventsFromMpv1();
let eventsCompleted = 0;
events.forEach((event, i) => {
  runContainer(events[i], /* onComplete= */ () => {
    if (events.length === ++eventsCompleted) {
      returnResponse();
    }
  }, /* onStart= */ (bindToEvent) => {
    if (i === 0) {
      bindToEvent(addMessageListener)('send_pixel', (messageType, message) => {
        // This will be called whenever a tag for the first event sends a
        // 'send_pixel' message.
      });
    }
  });
});

Associated permissions

Requires use_message permission. The permission must be configured to permit at least:

  • A message type with Usage of listen or listen_and_send.

hasMessageListener

Returns true if a message listener has been added for the given message type. Returns false otherwise.

Syntax

const hasMessageListener = require('hasMessageListener');

hasMessageListener('send_pixel');

Associated permissions

None.


sendMessage

Sends a message of the specified type to a registered listener. This can be used to send messages from a tag back to the client that ran the container.

Syntax

const sendMessage = require('sendMessage');

sendMessage('send_pixel', {url: 'https://analytics.example.com/collect'});

Parameters

Parameter Type Description
messageType string The message type to send. If the value is not a string, it will be coerced to a string.
message object The message to send. If the message is not an object, the API will do nothing.

Associated permissions

Requires use_message permission. The permission must be configured to permit at least:

  • A message type with Usage of listen_and_send or send.

Test APIs

These APIs work with sandboxed JavaScript tests to build tests for custom templates in Google Tag Manager. These test APIs do not need a require() statement. [Learn more about custom template tests].


assertApi

Returns a matcher object that can be used to fluently make assertions about the given API.

Syntax

assertApi(apiName)

Parameters

Parameter Type Description
apiName string The name of the api to check; same string as passed to require().

Matchers

  • Subject.wasCalled()
  • Subject.wasNotCalled()
  • Subject.wasCalledWith(...expected)
  • Subject.wasNotCalledWith(...expected)

Examples

assertApi('sendPixel').wasCalled();
assertApi('getUrl').wasNotCalled();
assertApi('makeNumber').wasCalledWith('8');
assertApi('setInWindow').wasNotCalledWith('myVar', 'theWrongValue');

assertThat

The assertThat API is modeled after Google's [Truth] library. It returns an object that can be used to fluently make assertions about a subject's value. An assertion failure will immediately stop the test and mark it as failed. However, a failure in one test will not affect other test cases.

Syntax

assertThat(actual, opt_message)

Parameters

Parameter Type Description
actual any The value to use in the fluent checks.
opt_message string Optional message to print if the assertion fails.

Matchers

Matcher Description
isUndefined() Asserts that the subject is undefined.
isDefined() Asserts that the subject is not undefined.
isNull() Asserts that the subject is null.
isNotNull() Asserts that the subject is not null.
isFalse() Asserts that the subject is false.
isTrue() Asserts that the subject is true.
isFalsy() Asserts that the subject is falsy. Falsy values are undefined, null, false, NaN, 0, and '' (empty string).
isTruthy() Asserts that the subject is truthy. Falsy values are undefined, null, false, NaN, 0, and '' (empty string).
isNaN() Asserts that the subject is the value NaN.
isNotNaN() Asserts that the subject is any value besides NaN.
isInfinity() Asserts that the subject is positive or negative Infinity.
isNotInfinity() Asserts that the subject is any value besides positive or negative Infinity.
isEqualTo(expected) Asserts that the subject is equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isNotEqualTo(expected) Asserts that the subject is not equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isAnyOf(...expected) Asserts that the subject is equal to one of the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isNoneOf(...expected) Asserts that the subject is not equal to any of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
isStrictlyEqualTo(expected) Asserts that the subject is strictly equal (===) to the given value.
isNotStrictlyEqualTo(expected) Asserts that the subject is not strictly equal (!==) to the given value.
isGreaterThan(expected) Asserts that the subject is greater than (>) the given value in an ordered comparison.
isGreaterThanOrEqualTo(expected) Asserts that the subject is greater than or equal to (>=) the given value in an ordered comparison.
isLessThan(expected) Asserts that the subject is less than (<) the given value in an ordered comparison.
isLessThanOrEqualTo(expected) Asserts that the subject is less than or equal to (<=) the given value in an ordered comparison.
contains(...expected) Asserts that the subject is an array or string that contains all of the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
doesNotContain(...expected) Asserts that the subject is an array or string that contains none of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
containsExactly(...expected) Asserts that the subject is an array that contains all of the given values in any order and no other values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
doesNotContainExactly(...expected) Asserts that the subject is an array that has contains a different set of values from the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively.
hasLength(expected) Asserts that the subject is an array or string with the given length. The assertion always fails if the value is not an array or string.
isEmpty() Asserts that the subject is an array or string that is empty (length = 0). The assertion always fails if the value is not an array or string.
isNotEmpty() Asserts that the subject is an array or string that is not empty (length > 0). The assertion always fails if the value is not an array or string.
isArray() Asserts that the type of the subject is an array.
isBoolean() Asserts that the type of the subject is a boolean.
isFunction() Asserts that the type of the subject is a function.
isNumber() Asserts that the type of the subject is a number.
isObject() Asserts that the type of the subject is an object.
isString() Asserts that the type of the subject is a string.

Examples

assertThat(undefined).isUndefined();
assertThat(id, 'ID must be defined').isDefined();
assertThat(null).isNull();
assertThat(undefined).isNotNull();
assertThat(true).isTrue();
assertThat(false).isFalse();
assertThat(1).isTruthy();
assertThat('').isFalsy();
assertThat(1/0).isInfinity();
assertThat(0).isNotInfinity();
assertThat(-'foo').isNaN();
assertThat(100).isNotNaN();
assertThat(sentUrl).isEqualTo('https://endpoint.example.com/?account=12345');
assertThat(category).isNotEqualTo('premium');
assertThat(5).isAnyOf(1, 2, 3, 4, 5);
assertThat(42).isNoneOf('the question', undefined, 41.9);
assertThat('value').isStrictlyEqualTo('value');
assertThat('4').isNotStrictlyEqualTo(4);
assertThat(['a', 'b', 'c']).contains('a', 'c');
assertThat(['x', 'y', 'z']).doesNotContain('f');
assertThat(['1', '2', '3']).containsExactly('3', '2', '1');
assertThat(['4', '5']).doesNotContainExactly('4');
assertThat('a string').hasLength(8);
assertThat([]).isEmpty();
assertThat('another string').isNotEmpty();

fail

Immediately fails the current test and prints the given message, if supplied.

Syntax

fail(opt_message);

Parameters

Parameter Type Description
opt_message string Optional error message text.

Example

fail('This test has failed.');

mock

The mock API allows you to override the behavior of Sandboxed APIs. The mock API is safe to use in template code, but it is non-operational when not in test mode. Mocks are reset before each test is run.

Syntax

mock(apiName, returnValue);

Parameters

Parameter Type Description
apiName string The name of the API to mock; same string as passed to require()
returnValue any The value to return for the API or a function called in place of the API. If returnValue is a function, that function is called in place of the Sandboxed API; if returnValue is anything other than a function, that value is returned in place of the Sandboxed API.

Examples

mock('encodeUri', "https://endpoint.example.com/?account=12345");
mock('sendPixel', function(url, onSuccess, onFailure) {
    onSuccess();
});

runCode

Runs the code for the template, i.e. the content of the Code tab, in the current test environment with a given input data object.

Syntax

runCode(data)

Parameters

Parameter Type Description
data object Data object to be used in the test.

Return Value

Returns the value of a variable for variable templates; returns undefined for all other template types.

Example

runCode({field1: 123, field2: 'value'});