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


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.


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' and 'GTAG'.

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

The 'GTAG' option fetches the One Google Tag script from https://www.googletagmanager.com/gtag/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' only: the gtag measurement ID.
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 Tagging server URL prefix from the path. For example, if Tagging server 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.

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.


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


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, and sameSite. (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.

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));
});

Syntax

sha256(input, onSuccess)

Parameters

Parameter Type Description
input string The string to hash.
onSuccess function Called with the resulting digest, encoded in base64.

Associated permissions

None.


sha256Sync

Calculates and returns the SHA-256 digest of the input, encoded in base64.

Example

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

const digest = sha256Sync('inputString');
sendHttpGet('https://example.com/collect?id=' + encodeUriComponent(digest));

Syntax

sha256Sync(input)

Parameters

Parameter Type Description
input string The string to hash.

Associated permissions

None.


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.


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 functions 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.