Commanders Act X
Platform XDocumentationWelcome to Success
  • Welcome !
  • Platform updates
    • Announcements
    • Documentation updates
    • Release notes
  • Getting started
    • How the platform works
      • Glossary
        • Condensed platform concepts
    • Platform interface
      • Prod and Testing environments
      • Productivity tools
        • Commander's AI
    • Integrating your data
      • GTM Tutorial
      • OneTag Tutorial
      • Migration guides to the Platform X
        • Migrate from SSv1 to SSv2
          • Send data to serverside v2
            • Purchase event example (ssv1 to ssv2)
        • Migrate from old mobile sdk
  • Features
    • Sources
      • Sources Overview
      • Sources Catalog
        • Web
          • Web container
            • User guides for browser-side platform
              • Container
                • Hosting
                • Creation and modification
                • Generation
                • Testing
                • Deployment and roll back
                • Deletion
                • Statistics
                • Modification history
                • Javascript block
                • Branches
                • Plugin Commanders Act Assistant
              • Tags
                • Add tags
                • Configure tags
                • Rules
                  • Basic actions
                  • Triggers
                  • Perimeters & constraints
              • Data layer and data types
                • External variables
                • Internal variables
                • Event variables
                • Data storage
              • Deduplication
                • Setup guide
                • Setup example
                • Deduplication reports
              • TagPerformance
                • Setup guide
                • Report analysis
                • Troubleshooting
            • Setup guides for developers
              • Web container setup
              • Datalayer setup
              • Browser-side events setup
              • AMP
              • Angular
              • AngularJS
              • React
              • SPA implementation guide
              • VueJS
              • IOT & TV Apps
            • Best Practices
              • FAQ
              • Common Container Strategies
              • Common Trigger Strategies
              • Performance Optimization
              • tC.* attributes and methods
              • APIs
                • Onsite API
              • TMS & Consent banners IDs
          • Javascript SDK
            • Next.js serverside rendering
          • Pixel Tracking API
          • Google Tag Manager (GTM)
          • Shopify
        • Mobile APP
          • Android
          • iOS
          • Flutter
          • React native
        • Advertising
          • Bing Ads (cost import)
          • Facebook Ads (cost import)
          • Criteo (cost import)
          • Realytics
        • Import CRM users
          • API users
          • Users file importer
        • Import conversions
          • API Conversions and Product catalog
          • Conversions files importer
        • Product catalog
          • Product catalog files importer (FTP)
        • Server
          • HTTP tracking API source
            • (deprecated) HTTP tracking API source 1.0
          • Node.JS
          • Python
          • PHP
      • Source Live Event Inspector
      • Source data quality
    • Destinations
      • Destinations overview
        • Automatic Audience replay
      • Destinations catalog
        • AbTasty
        • Actito
        • Adform
        • Adobe
          • Adobe Analytics
          • Adobe Campaign
        • AdRoll
        • Adition
        • Adventori
        • Affilae
        • Alphalyr Marketing Studio
        • Amazon
          • Amazon Ads Conversions API
          • Amazon S3
        • Attraqt
        • Awin
        • Batch Audience
        • Branch Events
        • Button
        • Campaign Analysis Legacy
        • Commission Junction
        • Criteo
          • Criteo - Events
          • Criteo (audiences)
          • Criteo (offline conversions)
        • Data Activation Legacy
        • Dataventure
        • Destination Logs Exporter (closed beta)
        • Dialog-Mail
        • Dynamic Yield
        • Easyence
        • Effinity
        • Eloqua
        • Emarsys
        • Email export
        • Equativ Audience
        • Experian
        • Facebook
          • Facebook Conversions API
            • Facebook CAPI through GTM
            • Performance tab (Event Match Quality)
          • Facebook Custom Audiences
          • Facebook Lead Ads
        • FTP
        • Gamned
        • Google
          • Google Analytics 4
            • Google Analytics 4 - Proxy Mode
          • Google BigQuery
          • Google Conversion Adjustments
          • Google Customer Match
          • Google Display & Video 360
          • Google Enhanced Conversions
          • Google Enhanced Conversions for Leads
          • Google Floodlight Mobile App Conversion
          • Google Search Ads 360 Enhanced Conversions
          • Google Store Sales Direct
        • IBM
        • Inxmail
        • IntelliAd
        • Jellyfish
        • Kameleoon
          • Kameleoon Audience
          • Kameleoon Events
        • Kelkoo
        • Kwanko
        • LinkedIn Conversions API
        • Liveramp
        • Magento
        • Marin Software
        • Mapp
        • Matomo
        • MediaMath
        • Microsoft Advertising Universal Event Tracking
        • Mindlytix
        • Moebel
        • Nextdoor Conversion API
        • OXID
        • Optimizely
        • Outbrain
        • Partnerize
        • Piano Analytics
          • Piano Analytics Collection API
          • Piano Analytics Enrichment API
        • Pinterest
        • Piwik PRO
        • Prediggo
        • Qlik
        • Quantcast
        • Quora Ads Conversion API
        • Rakuten
          • Rakuten Audience
          • Rakuten Events
        • Realytics
        • Reddit Conversions API
        • Responsys
        • RhythmOne
        • Rich Relevance
        • RTB House Audience
        • Salesforce
          • Salesforce Audience Studio
          • Salesforce Marketing Cloud
          • Salesforce Commerce Cloud
        • SAP Commerce Cloud
        • Selligent
        • Skai
        • Smart Adserver
        • SmartFocus
        • Snapchat Conversions API
        • Splio
        • Syte
        • Tableau Online
        • Taboola
          • Taboola Audience
          • Taboola Events
        • Target2sell
        • Temelio
        • Teradata
        • The Trade Desk
          • The Trade Desk Conversions API
          • The Trade Desk Audience
        • TikTok
          • TikTok Events API
          • TikTok Offline Events
        • TimeOne
        • Tradedoubler
        • TradeTracker
        • X (Twitter) Conversion API
        • Xandr
        • Webhook
        • Webtrends
        • ZBO Media
        • Zeta
      • Destination builder
        • Javascript destination builder
          • Tutorial - How to build a server destination with the JS sandbox
          • Serverside javascript helpers
      • Destination filters
      • Mapping and Properties transformation
      • Event delivery
      • Destination event inspector
      • Dry mode (lab)
    • Enrichments
      • Augmented User Attributes
        • Business case
      • Events enrichment
      • Storage Settings
    • Data Quality
      • Event Specification
      • Sources data quality
      • Data cleansing
        • Supported transformation functions - Data cleansing
          • Format a date
    • Identity resolution
      • Migrate from Fuse v1 to Fuse v2
    • Customers
      • Segment
        • Segment overlap
        • Segment stats
    • Explore
      • Campaign analysis
        • Attribution
        • Control Group (Closed Beta )
      • User analysis
        • Dashboards
      • Consent Analysis
    • Consent management
      • Responsability of actors
      • Setup Guides
        • Tag Manager
          • Commanders Act TMS
          • Google Tag Manager (GTM)
          • Google Tag Manager (GTM) - Consent Mode
          • Google Consent Mode in Commanders Act CMP
          • Adobe Launch
        • Websites (Hardcoded)
        • FR : Suppression des cookies lors du retrait du consentement
        • Mobile apps
          • iOS
            • ATT - App Tracking Transparency (iOS 14.5+)
          • Android
      • User Guides
        • Categories & Tags
          • Manage Categories
          • Manage Vendors
          • Assign Categories
        • Privacy Banners
          • Banner Templates
            • Accessibility Template
          • Manage Banner
          • Deploy Banner
          • Copy Banner
        • Consent Analysis
        • Exports
        • Settings
      • Extensions
        • Cookie Scanner
        • Piggybacking
        • Tag Firewall
      • Marketing Preferences Center (additional module)
      • Knowledge Base
        • Consent Object
        • Consent cookies exemption
          • Implementation guide for exempted consent statistics FR market
        • Consent Cookie
        • IAB TCF V2.2 Release details
          • IAB TCF v2.2 CMP requirements
          • IAB TCF v2.2 Migration guide Web
          • IAB TCF v2.2 Migration guide App
        • IAB TCF V2.2 Consent
        • IAB TCF V2.2 and Google FAQ
        • Google ACM requires IAB TCF
        • CCPA & Global Privacy control
      • Rest Data API
        • GET/PUT Consents / preferences
      • OnSite API
        • Getting Started
        • consent.get
        • consent.update
        • consent.revoke
        • consent.onUpdate
        • consent.onReady
        • consentBanner.show
        • consentBanner.hide
        • consentCenter.show
        • consentCenter.hide
      • Platform API
        • Get statistics
  • Use cases
    • Data activation
      • Engage new customers
        • Welcome banner for new customers
        • Real-time promotion for hesitant customers
        • Discount banner for installing the application
        • Personalized ads
        • Engage similar audience (lookalike)
      • Increase loyalty
        • Drive to favourite store
        • Increase Customer Lifetime Value with a loyalty program
        • Notification about order delay
      • Increase revenue
        • Abandoned cart
        • Products recommendations
        • Complementary product offer
      • Retain customers
        • Identify a churn risk with RFM segmentation
        • Identify customers’ preferred channel
        • Contact with the customer support
      • Advocacy
        • Incentive to share customers' experience and rating
        • Sponsorship Program
        • Social Media Hashtag
    • Website performance
    • Consent banners A/B testing
    • Customer analysis
    • Campaigns performance analysis
  • Developers
    • Tracking & Integrations
      • Tracking
        • About events
          • E-commerce/retail events
          • Web event specificity
          • Mobile App event specificity
        • Events reference
          • Common events
          • E-commerce events
          • Video events
          • Campaign Tracking events
        • Properties reference
          • Global properties
          • Video properties
          • Permanent properties
        • Data API
          • HTTP API
          • Segment API
          • User API
          • Product catalog and conversion API
      • Server IP Whitelisting
    • Config API
    • Changelogs
      • Measure.js changelog
      • Web container generator
    • Content Security Policy
  • CONFIGURE
    • Data Management
      • Events collection
      • Data retention duration
      • Data Governance
    • Administration
      • User management
      • Domain Management
        • WAF Proxy (CloudFlare,...)
        • A record
        • CNAME record
        • On-Premise Proxy
        • Cookie CAID
        • First party hosting
      • Single Sign-On
      • Two-factor authentication (2FA)
      • Copy Management
    • Cookies
      • Cookie 1st
      • Cookie sync partners
      • First domain tracking (Phoenix)
    • Disclaimer
Powered by GitBook
On this page
  • decodeURI
  • decodeUriComponent
  • encodeUri
  • encodeUriComponent
  • fromBase64
  • generateRandom
  • getAllEventData
  • getCookieValues
  • getEventData
  • getRemoteAddress
  • getTimestamp
  • getTimestampMillis
  • getType
  • logToConsole
  • makeInteger
  • makeNumber
  • makeString
  • parseUrl
  • sha256
  • sha256Sync
  • toBase64
  • JSON
  • Math
  • sendHttpGet
  • sendHttpRequest
  • md5Sync
  • templateDataStorage

Was this helpful?

Edit on GitHub
Export as PDF
  1. Features
  2. Destinations
  3. Destination builder
  4. Javascript destination builder

Serverside javascript helpers

This article describes the server-side destination APIs.

decodeURI

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

Syntax

decodeUri(encoded_uri);

Example

const decodeUri = require('decodeUri');

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

encoded_uri

string

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.

Syntax

decodeUriComponent(encoded_uri_component);

Example

const decodeUriComponent = require('decodeUriComponent');

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

encoded_uri_component

string

encodeUri

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

Syntax

encodeUri(uri);

Example

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

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

uri

string

A complete URI.

encodeUriComponent

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

Syntax

encodeUriComponent(str);

Example

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

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

str

string

A component of a URI.

fromBase64

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

Syntax

fromBase64(base64EncodedString);

Example

const fromBase64 = require('fromBase64');

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

base64EncodedString

string

Base64 encoded string.

generateRandom

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

Syntax

generateRandom(min, max);

Example

const generateRandom = require('generateRandom');

const randomValue = generateRandom(0, 10000000);
Parameter
Type
Description

min

number

Minimum potential value of the returned integer (inclusive).

max

number

Maximum potential value of the returned integer (inclusive).

getAllEventData

Returns a copy of the event data.

Syntax

getAllEventData();

Usage Example

const getAllEventData= require('getAllEventData');
const eventModel = getAllEventData();
//build body request from event properties 
const body = {
    crm_id:eventModel.user.id,
    currency:eventModel.currency
};

Data example:

If you send this web event:

cact('trigger', 'search', {
  "search_term": "blue t-shirt",
  "user": {
    "id": "12345",
    "email": "anakin.skywalker@domain.com",
    "consent_categories": ["1","3"]
  }
);

Then the getAllEventData() function will return this object:

{
   "event_name": "search",
   "search_term": "blue t-shirt",
   "user": {
      "id": "12345",
      "email": "anakin.skywalker@domain.com",
      "consent_categories": ["1","3"]
   },
   "url": "https://www.mywebsite.com/path1/path2/", //Automatically added if missing
   "path": "/path1/path2/", //Automatically added
   "referrer": "https:///www.google.fr", //Automatically added
   "title": "My page title", //Automatically added if missing
   "context": {
      "event_id": "202110130000000000", //Automatically added
      "generatorVersion": "10.0", //Automatically added
      "containerVersion": "3.1", //Automatically added
      "event_timestamp": "1639044446636", //Automatically added
      "page": { //Automatically added
         "title": "Search page", //Automatically added
         "url": "https://shop.com/search?q=...", //Automatically added
         "lang": "en", //Automatically added
         "referrer": "https:///www.google.fr", //Automatically added
         "viewport": { //Automatically added
            "width": 320, //Automatically added
            "height": 568 //Automatically added
         }
      },
      "device": { //Automatically added
         "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",//Automatically added
         "ip": "102.3.4.56",//Automatically copied from the request header
         "lang": "fr",//Automatically added
         "cookie": "_fbp=123; _fbc=456; _ga=789",//Automatically added
         "timezone": "Europe/Paris"//Automatically added
      }
   }
}

getCookieValues

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

Syntax

getCookieValues(name[, noDecode]);

Example

const getCookieValues = require('getCookieValues');
const facebook_fbp = getCookieValues('fbp')[0];
if (facebook_fbp ) {  // ...}

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.

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.

Syntax

getEventData(keyPath);

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.

getRemoteAddress

Returns a string representation of the IP address where the request originated, e.g. 62.123.65.780 for IPv4 or 2001:0db8:85a3:0:0:8a2e:0370:1234 for IPv6

Syntax

getRemoteAddress();

getTimestamp

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

Syntax

getTimestamp();

getTimestampMillis

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

Syntax

getTimestampMillis();

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'

Syntax

getType(value);

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

Parameters

Parameter
Type
Description

value

any

Input value.

logToConsole

Logs its argument(s) to the console.

These logs are visible within Destination Builder's console.

Example

const logToConsole = require('logToConsole');

const product_color= "red";
const product_price= 10;
logToConsole('color is: ', product_color, ' and price is: ', product_price);

Syntax

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

Parameters

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

makeInteger

Converts the given value to a number (integer).

Syntax

makeInteger(value);

Parameters

Parameter
Type
Description

value

any type

The value to convert.

makeNumber

Converts the given value to a number.

Syntax

makeNumber(value);

Parameters

Parameter
Type
Description

value

any type

The value to convert.

makeString

Returns the given value as a string.

Syntax

makeString(value);

Parameters

Parameter
Type
Description

value

any type

The value to convert.

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,
}

Syntax

parseUrl(url);

Example

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

Parameters

Parameter
Type
Description

url

string

The full url that will be parsed.

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.

Syntax

sha256(input, onSuccess, options = undefined);

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

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.

sha256Sync

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

Syntax

sha256Sync(input, options = undefined);

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

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.

toBase64

Encodes a string as base64.

Syntax

toBase64(input);

Example

const toBase64 = require('toBase64');const base64Hello = toBase64('hello');

Parameters

Parameter
Type
Description

input

string

String to encode.

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 (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 (ex. the object has a cycle), the method will return undefined.

Syntax

JSON.parse(yourString);
JSON.stringify(yourObject);

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

Math

An object providing Math functions.

Syntax

const Math = require('Math');
// Retrieve the absolute value.
const absolute = Math.abs(-5);
// Round the input down to the nearest integer.
const roundedDown = Math.floor(4.6);
// Round the input up to the nearest integer.
const roundedUp = Math.ceil(2.1);
// Round the input to the nearest integer.
const rounded = Math.round(4.2);
// Return the largest argument.
const biggest = Math.max(1, 4);
// Return the smallest argument.
const smallest = Math.min(4, 5);
// Return the first argument raised to the power of the second argument.
const powerful = Math.pow(4, 2);
// Return the square root of the argument.
const unsquared = Math.sqrt(81);

Parameters

Math function parameters are converted to numbers.

sendHttpGet

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

Syntax

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

Example

const sendHttpGet = require('sendHttpGet');
// Sends a GET request and nominates response// based on the response from the GET 
sendHttpGet('https://example.com/collect', function(statusCode, headers, body) {
    if (statusCode != 200) {yourCallbackFunction();}
}, {
    headers: {key: 'value'},
    timeout: 500
});

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, timeout. Advanced options can be added in extraOptions

Options

  • headers: Additional request headers represented as an object.

  • timeout: The timeout, in milliseconds, before the request is aborted.

  • extraOptions: Advanced options (ex: {strictSSL:true})

sendHttpRequest

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

Syntax

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

Example

const sendHttpRequest = require('sendHttpRequest');
const body = {
    user_type:'vip',
    account:'123'
};
// Sends a POST request 
sendHttpRequest('https://example.com/collect', function(statusCode, headers, body) {
    //your callback code...
}, {
    headers: {
        token: '123456789'
    },
    method: 'POST',
    timeout: 1000
},  JSON.stringify(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. Advanced options can be added in extraOptions.

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.

  • extraOptions: Advanced options (ex: {strictSSL:true})

md5Sync

Calculates and returns the md5 digest of the input.

Syntax

md5Sync(input);

Example

const md5Sync= require('md5Sync');
const email = {};
email.md5 = md5Sync(user.user_email);
sendHttpGet('https://example.com/collect?e5=' + email.md5);

templateDataStorage

The templateDataStorage helper allows temporary storage and retrieval of data, such as API tokens, during script execution. It is particularly useful for caching reusable data to reduce redundant API calls. Data stored in templateDataStorage persists on the server running the template. Since templates execute on multiple servers, and each server may have multiple instances, stored data is not guaranteed to be accessible for all subsequent template execution.

Syntax

templateDataStorage.setItemCopy(key, value);
templateDataStorage.getItemCopy(key);
templateDataStorage.removeItemCopy(key);

Example: Managing API Tokens

const sendHttpRequest = require('sendHttpRequest');
const templateDataStorage = require('templateDataStorage');

const tokenKey = 'apiToken';

function fetchNewToken(callback) {
  sendHttpRequest('https://example.com/api/token', function (status, _, body) {
    if (status === 200) {
      const { accessToken, expiresIn } = JSON.parse(body);
      const tokenData = { token: accessToken, expiry: Date.now() + expiresIn * 1000 };
      templateDataStorage.setItemCopy(tokenKey, tokenData);
      callback(accessToken);
    } else {
      callback(null);
    }
  }, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: 'id', clientSecret: 'secret' }) });
}

function sendEvent(eventData) {
  const cachedToken = templateDataStorage.getItemCopy(tokenKey);
  const token = cachedToken && cachedToken.expiry > Date.now() ? cachedToken.token : null;

  sendHttpRequest('https://example.com/api/events', function (status) {
    if (status === 401) {
      fetchNewToken(function (newToken) {
        if (newToken) {
          sendHttpRequest('https://example.com/api/events', () => {}, { method: 'POST', headers: { Authorization: `Bearer ${newToken}` }, body: JSON.stringify(eventData) });
        }
      });
    }
  }, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: JSON.stringify(eventData) });
}

sendEvent({ eventName: 'purchase', value: 100 });
Method
Description

setItemCopy(key, value)

Stores a value under the specified key. Overwrites the value if the key already exists.

getItemCopy(key)

Retrieves the value associated with the specified key. Returns undefined if the key does not exist.

removeItemCopy(key)

Deletes the value associated with the specified key.

Parameter
Type
Description

key

string

The unique identifier for the data to be stored/retrieved.

value

any

The data to be stored (for setItemCopy).

PreviousTutorial - How to build a server destination with the JS sandboxNextDestination filters

Last updated 4 months ago

Was this helpful?

A URI that has been encoded by or by other means.

A URI component that has been encoded by or by other means.

Notice that the event data may contains more properties that what you sent initially because of system properties that are added automatically on and .

Deprecated. Prefer .

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

getTimestampMillis
sha256
sha256Sync
encodeUri()
encodeUriComponent()
web events
app sdk events