Back

This article provides details on the named exports, the fetch API that functions can use to make HTTP requests, example data, and example code.

After you have written a function, you can test it in the Test tab. Suggested test data is shown under Test Input, which you can modify as needed. In addition, you can use a function to get data from your website for testing. See Getting Test Data From Your Website.

For information on creating a function, see Managing Functions.

In this article:

Execution Environment

The functions execution environment is built on the GraalVM JS runtime and runs ECMAScript 2020 compatible code. If an error occurs, the error message is written to the log file. Functions can also write messages to the log.

Functions have the following limitations:

  • Functions cannot use third-party libraries.
  • Functions have 10 seconds execution time.
    If a function exceeds this time, the following error occurs:

Exception 504 - Invocation timeout limit exceeded.

  • Functions have 32 MB of memory.
    If a function attempts to use more than 32 MB, the following error occurs:

Exception 400 BAD REQUEST - OutOfMemoryError: memory limit 32 mb is exceeded.

Named Exports

The Tealium module exports five named exports for functions: auth, event, visitor, store, and tealium. A function imports the named exports as follows:

import { auth, visitor, event, store, tealium } from "tealium"; 

Event Object

The event object is available when a function is triggered by the event feed and contains the event data.

Property Data Type Description
event.id string Tealium Event ID.
 event.visitor_id string Tealium Visitor ID.
event.account string Tealium Account.
event.profile string Tealium Profile.
event.data { [dataKey:string]: {
    [attributeName:string]: string
    }
}
An object that contains event attribute data, such as event.data.properties.page_category or event.data.dates.signup_date.

Event Object Example

The following shows an example of event object data:

{
  "account": "your-account",
  "profile": "main",
  "event_id": "run-test-event-id",
  "visitor_id": "run-test-visitor-id",
  "data": {
    "dom": {
      "viewport_height": 766,
      "referrer": "",
      "viewport_width": 1440,
      "domain": "www.example.com",
      "title": "Home Page",
      "query_string": "q=help",
      "hash": "",
      "url": "https://www.example.com/?q=help",
      "pathname": "/"
    },
    "udo": {
      "tealium_event": "page_view",
      "ut.account": "your-account",
      "ut.visitor_id": "0176cb4f3482110a5ba4702e147b0006d005a065104f2",
      "page_name": "Home Page",
      "ut.event": "view",
      "search_keyword": "help",
      "ut.domain": "example.com",
      "tealium_profile": "main",
      "ut.version": "ut4.46.202006020705",
      "tealium_session_id": "1609910608323",
      "tealium_account": "your-account",
      "ut.profile": "main",
    },
    "firstparty_tealium_cookies": {
      "utag_main__sn": "12",
      "utag_main_dc_visit": "12",
      "utag_main_ses_id": "1609910610822",
      "utag_main_dc_region": "us-east-1",
      "utag_main__st": "1609913306118",
      "utag_main_v_id": "0176cb4f3482110a5ba4702e147b0006d005a065104f2",
      "utag_main__se": "66",
      "utag_main__ss": "0",
      "utag_main_dc_event": "60",
      "utag_main__pn": "5"
    }
  },
  "env": "prod",
  "post_time": 1537305808000
}

Event data can be accessed in a function as follows:

const data = {};
    // DOM variables are stored in event.dom
    data.current_url = event?.dom?.url;
// Standard UDO event variables are stored in event.data.udo data.session_id = event?.data?.udo?.tealium_session_id;
// First Party cookies are stored in event.firstparty_tealium_cookies data.trace_id = event?.firstparty_tealium_cookies?.trace_id;
// Meta variables are stored in event.meta data.meta_description = event?.meta?.description; data.tealium_event = event?.data?.udo?.tealium_event; data.tealium_account = event?.data?.udo?.tealium_account; data.tealium_profile = event?.data?.udo?.tealium_profile;

Visitor Object

The visitor object is available when a function is triggered by the audience feed and contains the visitor data.

Property Data Type Description
visitor.metrics Record<string, number> Visitor metrics.
visitor.dates Record<string, number> Visitor dates.
visitor.audiences_joined_at Record<string, number> Timestamp when the visitor joined audiences.
visitor.properties Record<string, any> Visitor properties.
visitor.properties.account string Tealium Account.
visitor,properties.profile string Tealium Profile.
visitor.properties.visitor_id string Tealium Visitor ID.
visitor.audiences string[] List of joined audiences.
visitor.badges: string[] string[] List of badges.
visitor.creation_ts number Visitor creation timestamp.
visitor.current_visit Record<string, any> Current visit object.
visitor.current_visit.metrics Record<string, number> Current visit metrics.
visitor.current_visit.dates Record<string, number> Current visit dates.
visitor.current_visit.properties Record<string, any> Current visit properties.
visitor.current_visit.flags Record<string, any> Current visit flags.
visitor.current_visit.property_sets Record<string, any> Current visit property sets.
visitor.current_visit.creation_ts number Current visit creation timestamp.
visitor.current_visit.total_event_count number Current visit total event count.
visitor.current_visit.events_compressed boolean Current visit events compressed.

Example Visitor Object Data

The following is an example of visitor object data:

{
  "metrics": {
    "Metric 1": 1,
    "Metric 2": 2
  },
  "dates": {
    "Date 1": 1603373790000,
    "Date 2": 1603373522000,
  },
  "properties": {
    "profile": "username",
    "visitor_id": "017560818b67001bc185a07f1cd703078003405000b7e",
    "account": "user-account",
  },
  "audiences": [
    "Audience 1",
    "Audience 2"
  ],
  "badges": [
    "Badge 1",
    "Badge 2"
  ],
  "creation_ts": 1603373522000,
  "current_visit": {
    "metrics": {
      "Metric 1": 1.3,
      "Metric 2": 6,
    },
    "dates": {
      "Date 1": 1603373868000,
      "Date 2": 1603373790000,
    },
    "properties": {
      "Property 1": "Chrome",
      "Property 2": "https://URL-for-website ",
    },
    "flags": {
      "Flag 1": true,
      "Flag 2": false
    },
    "property_sets": {
      "Property Set 1": [
        "Mac desktop"
      ],
      "Property Set 2": [
        "Chrome"
      ]
    },
    "creation_ts": 1603373790000,
    "total_event_count": 2,
    "events_compressed": false
  },
  "audiences_joined_at": {
    "Audience 1": 1603363523014,
    "Audience 2": 1603363523014
  }
}

Auth Object: auth.get()

The auth.get() method returns a string that contains a unique auto-generated ID for the authentication token. When a function makes an HTTP request using this token ID, it is automatically replaced with the token before the request is sent.

Parameter Data Type Description
tokenKey string Specifies the token to get, which is the name entered when the authentication provider was added. 

Tealium Object: sendCollectEvent()

The sendCollectEvent() method sends an event to Tealium Collect HTTP API and returns a string.

The Response interface of the Tealium Collect HTTP API represents the response to a request. The response model is the same as for fetch API, except that the URL is not available in the result of the Tealium Collect HTTP API.

Parameter Data Type Description
event EventsClientEventObject An event object to send to Tealium Collect HTTP API.
account string Optional. If specified, replaces the value of event.tealium_account.
profile string Optional. If specified, replaces the value of event.tealium_profile.
dataSourceId string Optional. If specified, replaces the value of event.tealium_datasource.

Store Object: store.get()

The store.get() method fetches a global parameter value by its key.

Parameter Data Type Description
globalParameterKey string Specifies the global parameter to get.

Test Payloads

You can obtain real test data for functions from the data collected for your website. Before you begin, make sure you have done the following:

  • Configured Tealium IQ to collect data from a website or other source.
  • Configured data sources, event feeds, and audiences.
  • Verified that the event feed or audience contains the correct data to trigger the function.

There are two methods for obtaining test data from your website, as follows:

  • From the Console Log
  • Using Trace

Getting Test Data From a Log File

This section provides instructions for the following steps to get test data from a log file:

  • Create a function to write data to the log.
  • Copy the data from the log file to the Test tab.

Create a Function to Write Data to the Log File

Follow these steps to write event and visitor data to the log file:

  1. Create a new function, then delete the example code and enter the following code, which writes the event and visitor data to the console log.
    import { event, visitor } from "tealium";
    console.log('Event object:' + JSON.stringify(event));
    console.log('Visitor object:' +JSON.stringify(visitor));
  2. Click the Configuration tab, and set Status to ON.
  3. Click Done, then click Save/Publish.
    Wait briefly for the changes to apply.

Copy and Format Log File Data

  1. Go to your website and do the actions required to trigger the function.
    Wait 1 to 2 minutes to allow the data to be collected.
  2. In the Functions Overview, click the function that you created to write data to the log.
  3. Click the Logs tab, then open a log entry to see the JSON object.
  4. Copy the JSON code and format it in any JSON formatting tool.
  5. Click the Test tab, and paste the formatted JSON code into the Test Input editor.
  6. Click Save As, enter a name for the test input in the pop-up, and click Save As.

Getting Test Data Using Trace

  1. In the code editor, create any JavaScript code. For example:
    console.log("Hello World!");
  2. Click the Configuration tab and set the Status to ON, then click Done.
  3. Save and publish.
  4. Start the Trace tool.  For more information, see Trace.
  5. On your website, do the actions required to trigger the function.
  6. In the Trace tool, click the Action Processed notification, then locate the event or visitor object under "payload", and copy the object.
  7. Go to the Test tab, delete the current code, and paste the event or visitor object into the Test Input editor.
  8. Click Save As, enter a name for the test input in the pop-up, and click Save As.

Trace can also be used if you need to test functions that have been published to your site. The trace log includes information for functions.

Sending an Event to Tealium Collect

The following example shows how to send an event to the Tealium Collect HTTP API. The response interface of the Tealium Collect HTTP API represents the response to a request. The response model is the same as for the fetch API, except that the URL is not accessible in the result from the collect client.

Example

import {event, tealium} from 'tealium';

var newEvent = {‘key’: ‘value’};

tealium.sendCollectEvent(newEvent, 'newAccount', 'newProfile', 'datasourceId')
    .then(response => {
        if (!response.ok) {
            throw new Error(`Network response was not ok. Status code: ${response.status}.`);
        }

        console.log('Status code:', response.status);
        return response.text();
    })
    .then(data => console.log('Result:', data))
    .catch(error => console.error('Error:', error.message));

Using the fetch() API to Make HTTP Requests

The fetch API is available for functions to make HTTP requests, as shown in the following example. For more information, see Fetch.

fetch('https://restcountries.eu/rest/v2/name/usa')
  .then(response => {
    if (!response.ok) {
      throw new Error(`Network response was not ok. Status code: ${response.status}.`);
    }
    return response.json();
  })
  .then(data => console.log('Capital:', data[0].capital))
  .catch(error => console.log('Error:', error.message));

The following example shows fetching a resource from the network, returning a promise that is fulfilled when the response is available.

const fetchResponsePromise = fetch(resource [, init])

The Request interface of the Fetch API represents a resource request and is defined as follows:

const myRequest = new Request(input[, init]);

Functions can use the Headers interface of the Fetch API to perform various actions on HTTP request and response headers. Headers() is defined as follows:

const myHeaders = new Headers(init);

The Response interface of the Fetch API represents the response to a request and is defined as follows:

const myResponse = new Response(body, init);

The following browser-specific functionality is not supported:

  • cache
  • credentials
  • referrer
  • referrerPolicy
  • signal
  • keepalive
  • redirect
  • mode

Using URLSearchParams Methods

The URLSearchParams interface defines utility methods to work with the query string of a URL. This example shows using URLSearchParams to build a query string for a URL.

function jsonToURLSearchParams(data) {
const params = new URLSearchParams();

buildURLSearchParams(params, data);

return params;
}

function buildURLSearchParams(params, data, parentKey) { if (data && typeof data === 'object' && !(data instanceof Date)) { Object.keys(data).forEach(key => { buildURLSearchParams(params, data[key], parentKey ? `${parentKey}[${key}]` : key); }); } else { const value = data == null ? '' : data; params.append(parentKey, value); } }

Using the JavaScript Console API

Use the JavaScript console functions to write messages and errors to the log.

console.log() , console.info(), and console.debug() log messages go to the info output stream. console.warn() and console.error() log messages go to the error output stream.

The console object provides other methods that are supported by functions. For more information, refer to any JavaScript specification for the console object. The following additional console methods are supported:

  • assert()
  • count()
  • countReset()
  • group()
  • groupEnd()
  • time()
  • timeEnd()
  • timeLog()

Console API Output

The output from most console functions is shown in the Messages section of the Logs display. For example:

Messages:

Function Start

Output from console.warn() and console.error() is shown in the Errors section, below the Messages output, as follows:

Errors:

Warning - page not found Error - variable not defined

console.assert()

If a function is triggered on EventStream and console.assert() is called as follows:

console.assert(visitor, "visitor not defined");
The visitor object is only defined when the trigger is AudienceStream, so the assertion is false and the output is as follows:
Assertion failed: visitor not defined

console.group() and console.groupEnd()

console.group() and console.groupEnd() can be used to format related messages in the log. console.log() messages that follow console.group() are indented in the log. The indentation ends after console.groupEnd() is called.

If the function code contains the following:

console.group("Event info:");
console.log("Account: ", event.account);
console.log("Visitor ID: ", event.visitor_id);
console.groupEnd();

The output is as follows:

Event info:
  Account:  Acme Mfg
  Visitor ID:  017407a1d9e50019633c3cea732703079011607100bd6

console.time() and console.timeLog()

When a function calls console.time(), there is no output. The time that console.time() was called with that string is noted. When console.timeLog() is called with the same string, "Current Time: " in this example, the output is the specified string followed by the time elapsed since console.time() was called:

Current Time: : 1ms

After a function calls console.timeEnd() , console.timeLog() cannot be called until console.time() is called again.

console.count() and console.countReset()

Each time console.count() is called with the same string, the count is incremented. The output of console.count() is the string followed by the count. If console.count("Current count: "); is called twice, the output is as follows:

Current count: : 1
Current count: : 2

console.countReset() resets the count for the specified string to zero.

Using Crypto.js

Crypto-ES.js is a library of encryption algorithms available for use in functions. Crypto-ES provides hashing, encoding, and cipher algorithms.  For more information, see Crypto-ES.

The following example shows how to encrypt and decrypt text:

import CryptoES from 'crypto-es';

var encrypted = CryptoES.AES.encrypt("Message", "Secret Passphrase");
console.log(encrypted);
var decrypted = CryptoES.AES.decrypt(encrypted, "Secret Passphrase");
console.log(CryptoES.enc.Utf8.stringify(decrypted));

Additional Information

Public