Back

Event and visitor functions are invoked after the event or visitor is processed. You can use event and visitor functions to retrieve data from other systems, augment Tealium data, or send data to other endpoints. 

This article provides details on the named exports provided for event and visitor functions, as well as information on sending an event to Tealium Collect and using the fetch API to make HTTP requests.

For information on adding authentication for an event or visitor function, see Adding an Authentication to a Function.

In this article:

Named Exports

The Tealium module exports five named exports for event and visitor 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 object An object that contains event attribute data, such as event.data.udo.page_category or event.data.udo.order_id.

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.metrics_sets Tally<string, number>  
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.property_sets Set<string, any>  
visitor.audiences string[] List of joined audiences.
visitor.badges string[] List of badges.
visitor.creation_ts number Visitor creation timestamp.
visitor.flags Map<string, Boolean>  
visitor.current_visit Record<string, any> Current visit object.
visitor.current_visit.metrics Record<string, number> Current visit metrics.
visitor.current_visit.metrics_sets Tally<string, number>  
visitor.current_visit.dates Record<string, number> Current visit dates.
visitor.current_visit.properties Record<string, any> Current visit properties.
visitor.current_visit.flags Map<string, Boolean> Current visit flags.
visitor.current_visit.property_sets Set<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()

Functions require authentication to access some service providers, such as Facebook or Google. For more information, see Adding an Authentication to a Function. When you add an authentication, an access token is returned.

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 object contains key/value pairs that specify variables or constants that can be used in multiple functions. A function can retrieve a value for a key by calling the store.get() method and passing the key as the parameter. For more information on adding and editing global variables, see Managing Functions.

Parameter Data Type Description
globalParameterKey string Specifies the key of the global variable to get.

For example, if you create a global variable with a key named date, a function would retrieve the value for date as follows:

 store.get('date')

Getting an Attribute Name or Attribute Value by Attribute ID

Attribute names can be changed, which can cause problems when code references attributes by name. To avoid problems with attribute names changing, you can reference attributes by ID. Event and visitor objects have a getAttributeNameById() method that you can use to get an attribute name based on its ID. You can also get the value of an attribute using the getAttributeValueById() method. The following example shows how this works.

If you enter the following in the code editor, when you enter the opening parenthesis, a list of attributes and associated IDs is displayed:

code-completion-attr-name.png

You can enter part of the attribute name to filter the list. When you select an attribute, its ID is added to your code after the parenthesis. The list of attributes works the same way for getAttributeValueById().

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 to Build a URL Query String

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

Additional Information

Public