TrustData
Tracking

JavaScript SDK

Install and configure the TrustData JavaScript SDK.

Installation

Standard installation

Add this snippet before the closing </head> tag:

<script>
(function(w,d,s,u,n){
  w[n]=w[n]||[];
  w[n].push(['init','ATTRIBUTION_ID',{sendPageView:true}]);
  var f=d.getElementsByTagName(s)[0],j=d.createElement(s);
  j.async=1;j.src=u;f.parentNode.insertBefore(j,f);
})(window,document,'script','https://t.trustdata.tech/t.js','trustdata');
</script>

Replace ATTRIBUTION_ID with your attribution ID from the dashboard.

Separate script tag

You can load the script and call init in two tags instead. The script sets window.trustdata when it loads, so the second tag runs once the first has finished:

<script src="https://t.trustdata.tech/t.js"></script>
<script>
  trustdata.init('ATTRIBUTION_ID');
</script>

If your attribution ID serves tracking from your own domain, the installation code in TrustData also adds apiHost to the init call. Copy the code from Installation code on the attribution ID page instead of writing it by hand.

Configuration options

trustdata.init('ATTRIBUTION_ID', {
  // Send a pageview event on initialization
  sendPageView: true,

  // Initial consent state
  consent: {
    analytics: false,
    advertising: false,
    preferences: false,
    sale_of_data: false
  },

  // Event server endpoint (default: TrustData cloud)
  apiHost: 'https://t.trustdata.tech',

  // Params added to every event (see setDefaults)
  defaultProps: { site_type: 'com' }
});

Configuration reference

OptionTypeDefaultDescription
sendPageViewbooleantrueSend pageview on init
consentobjectall falseInitial consent state (4 levels)
apiHoststringhttps://t.trustdata.techEvent server endpoint
apiPathstring/api/eventsPath the SDK posts events to on apiHost
defaultPropsobjectnoneParams added to every event. Same as calling setDefaults
To stop payment gateways, SSO providers, or your own domains from showing up as referrers, add them in the dashboard: Settings → Attribution IDs → select the attribution ID → Filtering tab → Referral exclusion. The older ignoreDomains SDK option has no effect.

API methods

Every method can be called in two ways:

// Command-queue form: works at any time, even before t.js has loaded
trustdata.push(['event', 'button_click', { button_id: 'signup' }]);

// Direct form: works once t.js has loaded
trustdata.event('button_click', { button_id: 'signup' });

Use the push form for code that can run before the SDK loads, such as an inline script on an order confirmation page. Calls queued before load run as soon as the SDK is ready.

trustdata.event(name, props)

Track custom events:

trustdata.event('button_click', {
  button_id: 'signup',
  page: '/pricing'
});

trustdata.event('add_to_cart', {
  id: 'SKU123',
  value: 49.99
});

trustdata.setDefaults(props)

Add params to every event, including the ones the SDK sends by itself such as page_leave and user_engagement:

trustdata.setDefaults({ site_type: 'com', user_type: 'Visitor' });

// The event's own value wins over the default
trustdata.event('purchase', { user_type: 'Customer' });

Each call merges into the earlier defaults at the top level, and a later value replaces an earlier one. A nested object replaces the earlier object. It is not merged. The SDK reads the defaults when it builds each event, so a call after init reaches the next event.

When the same field is set in more than one place, the first of these wins:

  1. The SDK's own fields: event_name, attribution_id, visitor_id, user_id, consent, lib, lib_version, lib_modules and first_visit.
  2. The props you pass to event().
  3. The defaults.

A default cannot set event_time, page_location, page_referrer or page_title. It also cannot set the fields the SDK sends only with consent: user_data, fbp, the device fields (raw_user_agent, screen_resolution, viewport_size, timezone, browser_language, webdriver) and the adblock fields.

Defaults are sent whether or not the visitor consents. Never put personal data in them.

trustdata.consent(options, opts)

Update consent state:

// Grant all consent
trustdata.consent({
  analytics: true,
  advertising: true
});

// Revoke advertising consent
trustdata.consent({
  analytics: true,
  advertising: false
});

Pass { interaction: true } as the second argument when the call comes from a real choice the visitor just made in your consent banner. Leave it out when you replay the stored consent state on page load. TrustData uses this flag to tell a genuine refusal apart from a visitor who hasn't decided yet, which drives the consent rate in the dashboard.

// In your CMP's "consent changed" callback
trustdata.consent({ analytics: true, advertising: false }, { interaction: true });

Withdrawing analytics consent clears the stored visitor ID and user ID.

Consent is part of the SDK state, not of an event. The SDK builds the consent object on every event from the state you set with consent() or the consent init option. A consent value passed to event() is discarded, as are visitor_id and user_id.

trustdata.setUserId(id)

Associate events with a known user:

// After user logs in
trustdata.setUserId('user_123');

The user ID persists across sessions. TrustData uses it for cross-device attribution.

trustdata.getVisitorId()

Get the current visitor's ID:

const visitorId = trustdata.getVisitorId();
console.log(visitorId); // "3f2b8c1e-5d4a-4f6b-9c2d-7e8f9a0b1c2d"

The ID is a UUID. It's null until the visitor grants analytics consent.

trustdata.setUser(data)

Set customer data for enhanced conversions. The SDK attaches these fields to the events that follow to improve match rates on ad platforms.

trustdata.setUser({
  email: '[email protected]',
  phone: '+15551234567',        // E.164 format
  first_name: 'Jane',
  last_name: 'Doe',
  address: {
    city: 'Paris',
    postal_code: '75001',
    country: 'FR'              // ISO 3166-1 alpha-2
  }
});
  • setUser() is asynchronous. The SDK hashes email and phone with SHA-256 in the browser before it stores them, so the raw values never leave the page.
  • The SDK only sends this data when the visitor has granted advertising consent. Without it, user_data is left out of the event.
  • trustdata.getUserData() returns the stored (hashed) user data, or null.

trustdata.clearUser()

Clear stored user data (e.g., on logout):

trustdata.clearUser();

trustdata.linkIdentity()

Links the anonymous pre-consent fingerprint (fp_xxx) to the new cookie-based visitor ID after a consent upgrade. This attributes touchpoints captured before consent (landing pages, ad clicks) to the eventual conversion.

The GTM template calls this automatically when analytics_storage is granted. Only call it manually if you manage consent outside GTM:

// After the user grants analytics consent
trustdata.consent({ analytics: true });
trustdata.linkIdentity(); // sends identity_link event, no-op if no ID transition

trustdata.getAdblockData() and trustdata.detectAdblock()

getAdblockData() returns the latest adblock detection result, or null. detectAdblock() runs detection again and returns a promise. Both need analytics consent: without it, the SDK doesn't probe ad endpoints.

await trustdata.detectAdblock();
console.log(trustdata.getAdblockData());

trustdata.debug(enabled)

Enable or disable debug logging:

trustdata.debug(true);  // Enable debug mode
trustdata.debug(false); // Disable debug mode

With debug on, the SDK writes lines like these to the browser console:

[TrustData] Initialized: ATTRIBUTION_ID
[TrustData] Sending: page_view {event_name: "page_view", ...}
[TrustData] Consent updated: {analytics: true, advertising: false, ...}

The Sending line shows the whole payload. It replaces user_data with [redacted].

Identity and storage

The SDK keeps a stable visitor identity so TrustData can link touchpoints to later conversions. The SDK writes the cookie and the localStorage keys below only after the visitor grants analytics consent.

KeyWhereLifetimePurpose
_trdt_vidFirst-party cookie + localStorage365 daysVisitor ID
_trdt_uidlocalStorageUntil clearedUser ID set via setUserId
_trdt_adblocklocalStorage24 hoursCached adblock detection result

The SDK also uses three sessionStorage keys. They hold no identifier and clear when the tab closes.

KeyPurpose
trdt_sdkcfg_v2Copy of the settings the SDK fetched for the attribution ID, so later pages in the tab skip the request. The SDK writes it without consent
_trdt_tag_sampled1 or 0: whether this tab was picked for tag monitoring. Written only when tag monitoring is on
trdt_replay1 or 0: whether this tab was picked for session replay. Written only when session replay is on
  • Consent gating. Before analytics consent, the SDK stores nothing. It uses a short-lived fp_ fingerprint so anonymous visits still count, then linkIdentity() links that fingerprint to the new _trdt_vid once the visitor grants consent.
  • Cross-subdomain. On a multi-level domain the SDK sets the cookie on the registrable domain (for example Domain=.example.com), so www, shop, and other subdomains share one identity. On localhost or raw IPs the SDK omits the domain attribute.
  • Server cookie. When an attribution ID serves tracking from its own domain (a CNAME tracking domain or a reverse proxy), the event server also sets an HttpOnly _trdt_vid_s cookie, and only with analytics consent. Scripts can't write it, so Safari's 7-day cap on script-set cookies doesn't apply, and it takes priority over _trdt_vid when both exist. With a CNAME domain Safari still caps the server cookie to 7 days. A reverse proxy avoids that cap. The server never sets it on the default tracking domain. See First-party tracking domain.

Single page applications (SPA)

For SPAs, track pageviews on route changes:

// React Router example
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();

  useEffect(() => {
    trustdata.event('page_view', {
      path: location.pathname
    });
  }, [location]);

  return <Routes>...</Routes>;
}
// Vue Router example
router.afterEach((to) => {
  trustdata.event('page_view', {
    path: to.path
  });
});

Integrate with your consent management platform:

// Initialize without automatic page_view
trustdata.init('ATTRIBUTION_ID', {
  sendPageView: false,
  consent: {
    analytics: false,
    advertising: false
  }
});

// After user grants consent in your banner
function onConsentGranted() {
  trustdata.consent({
    analytics: true,
    advertising: true
  }, { interaction: true });
  trustdata.linkIdentity(); // links pre-consent fingerprint to new cookie ID
  trustdata.event('page_view');
}

// If user only grants analytics consent
function onAnalyticsOnlyConsent() {
  trustdata.consent({
    analytics: true,
    advertising: false
  }, { interaction: true });
  trustdata.linkIdentity();
  trustdata.event('page_view');
}