This package adds an abstraction layer on top of segment.com's JavaScript library with some useful integrations and fixes:
Data Quality 📈
- Add
pagemethod that internally usestrackbut with the correctreferrerproperty. - Send
user.idandanonymousIdon every track. - Send anonymous data to AWS to be able to check data integrity with Adobe.
Google Analytics 🔍
- Load GA4 if
googleAnalyticsMeasurementIdis provided. - Retrieve
clientIdandsessionIdautomatically from GA4 and put in Segment tracks.
Adobe Marketing Cloud Visitor Id ☁️
- Load Adobe Visitor API when needed (if flag
importAdobeVisitorIdis set totrue, otherwise you should loadVisitor APIby your own to get themcvid). - Fetch
marketingCloudVisitorIdand put in integrations object for every track. - Monkey patch
tracknative Segment method to sendmarketingCloudVisitorIdinsidecontext.integrations.
Consent Management Platform 🐾
- Automatic tracking of Consent Management Platform usage.
- Send
gdpr_privacyoncontextfor for all tracking events. Expect values:unknown,acceptedanddeclined. - Send
gdpr_privacy_advertisingoncontextfor for all tracking events. Expect values:unknown,acceptedanddeclined. -
gdpr_privacyis accepted when consents [1, 8, 10] are accepted andgdpr_privacy_advertisingis accepted when consents [3] is accepted. - Any track is sent if the user has not accepted/rejected any consent yet.
Developer Experience 👩💻
- Always send
platformproperty asweb. - Allow to configure
window.__mpi.defaultContextto send these properties on all tracks inside the context object. - Allow to configure
window.__mpi.defaultPropertiesto send these properties on all tracks.
Segment Middlewares 🖖
- Optimizely Full Stack middleware to use Segment's anonymousId as Optimizely's userId, more info here.
After adding your Segment snippet into your html, you'll need to include this package in order to be able to fire events.
analytics will be an object with the methods described here.
<script>
!(function () {
var analytics = (window.analytics = window.analytics || [])
if (!analytics.initialize)
if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.')
else {
analytics.invoked = !0
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on',
'addSourceMiddleware',
'addIntegrationMiddleware',
'setAnonymousId',
'addDestinationMiddleware'
]
analytics.factory = function (e) {
return function () {
var t = Array.prototype.slice.call(arguments)
t.unshift(e)
analytics.push(t)
return analytics
}
}
for (var e = 0; e < analytics.methods.length; e++) {
var key = analytics.methods[e]
analytics[key] = analytics.factory(key)
}
analytics.load = function (key, e) {
var t = document.createElement('script')
t.type = 'text/javascript'
t.async = !0
t.src = 'https://cdn.segment.com/analytics.js/v1/' + key + '/analytics.min.js'
var n = document.getElementsByTagName('script')[0]
n.parentNode.insertBefore(t, n)
analytics._loadOptions = e
}
analytics._writeKey = 'YOUR_WRITE_KEY'
analytics.SNIPPET_VERSION = '4.13.2'
analytics.load('YOUR_WRITE_KEY') // your write key must be set here
}
})()
</script>import analytics from '@s-ui/segment-wrapper'// First load the UMD module.
<script src="https://unpkg.com/@s-ui/segment-wrapper/umd/index.js"></script>
<script>
// Then trigger all the events you need referencing the right namespaced
// object: `window.sui.analytics`. For more info see the "Events" section below.
window.sui.analytics.identify('your user id', {});
window.sui.analytics.track('your event', {});
window.sui.analytics.reset();
</script>The following configuration parameters are required and must be set for the system to function correctly:
-
ADOBE_ORG_ID: This parameter is the Adobe Organization ID, required for integration with Adobe services. Please make sure that you replace the example value with your actual Adobe Org ID. -
TRACKING_SERVER: This specifies the tracking server URL that will be used for sending data and handling tracking requests.These parameters need to be defined in the
window._SEGMENT_WRAPPERobject as follows:
window.__SEGMENT_WRAPPER = {
ADOBE_ORG_ID: '012345678@AdobeOrg', // Mandatory!
TRACKING_SERVER: 'mycompany.test.net' // Mandatory!
}Configure both values correctly before running the application to ensure proper tracking and data integration.
You could put a special config in a the window.__mpi to change some behaviour of the wrapper. This config MUST somewhere before using the Segment Wrapper.
googleAnalyticsMeasurementId: (optional) If set, this value will be used for the Google Analytics Measurement API. It will loadgtagto get the client id.googleAnalyticsConfig: (optional) If set, this config will be passed when initializing the Google Analytics Measurement API.googleAnalyticsInitEvent: (optional) If set, an event will be sent in order to initialize all the Google Analytics data.googleAnalyticsCookiePrefix: (optional) Cookie prefix for GA4 cookies. Defaults to'segment'. Example: if set to'myprefix', will look formyprefix_ga_<CONTAINER_ID>cookies.googleAnalyticsCookieTimeout: (optional) Maximum time in milliseconds to wait for GA4 cookie creation. Defaults to5000(5 seconds). Increase this value for slower networks or devices.defaultContext: (optional) If set, properties will be merged and sent with everytrackandpagein the context object. It's the ideal place to put thesiteandverticalinfo to make sure that static info will be sent along with all the tracking.defaultProperties: (optional) If set, properties will be merged and sent with everytrackandpage.getCustomAdobeVisitorId: (optional) If set, the output of this function will be used asmarketingCloudVisitorIdin Adobe Analytics' integration. It must return a promise.importAdobeVisitorId(optional) If set andtrue, Adobe Visitor API will be fetched from Segment Wrapper instead of relying on being loaded before from Tealium or other services. Right now, by default, this isfalsebut in the next major this configuration will betrueby default. IfgetCustomAdobeVisitorIdis being used this will be ignored.tcfTrackDefaultProperties(optional) If set, this property will be merged together with the default properties set to send with every tcf track eventuniversalId: (optional) If set this value will be used for the Visitor API and other services.hashedUserEmail: (optional) If set and notuniversalIdis set this value will be used for the Visitor API and other services.userEmail: (optional) If set and notuniversalIdis available, this value will be hashed with SHA-256 and used for the Visitor API and other services.isUserTraitsEnabled: (optional) If set context traits will be populated with all user traits.userIdPrefix: (optional) If set, the user id will be prefixed with this string for identify events.
Example:
window.__mpi = {
segmentWrapper: {
googleAnalyticsMeasurementId: 'G-XXXXXXXXXX',
googleAnalyticsCookiePrefix: 'segment', // optional, defaults to 'segment'
googleAnalyticsCookieTimeout: 5000, // optional, defaults to 5000ms (5 seconds)
universalId: '7ab9ddf3281d5d5458a29e8b3ae2864',
defaultContext: {
site: 'comprocasa',
vertical: 'realestate'
},
getCustomAdobeVisitorId: () => {
const visitorId = // get your visitorId
return Promise.resolve(visitorId)
},
tcfTrackDefaultProperties: {
tcfSpecialProp: 'anyvalue'
}
}
}- window.__mpi.isFirstVisit: boolean - true if the user hasn't interacted with the tcf modal yet
Track - docs
import analytics from '@s-ui/segment-wrapper'
analytics.track('CTA Clicked')
analytics.track('Registered', {
plan: 'Pro Annual',
accountType: 'Facebook'
})Internally uses Track but changes the referrer everytime is called.
import analytics from '@s-ui/segment-wrapper'
analytics.page('Home Viewed')
analytics.page('List Viewed', {
property: 'HOUSE',
transaction: 'SELL'
})Identify - docs
import analytics from '@s-ui/segment-wrapper'
analytics.identify('97980cfea0067', {
name: 'Peter Gibbons',
email: 'peter@initech.com',
plan: 'premium',
logins: 5
})Reset - docs
import analytics from '@s-ui/segment-wrapper'
analytics.reset()Segment Wrapper is handling all about the UniversalID, an ID to identify the user across different sites by using a hashed email. If you want, you could subscribe yourself to an event in order to retrieve this info:
document.addEventListener(USER_DATA_READY_EVENT, e => {
const {universalId} = e.detail
})Also, you could check directly if the universalId is already available on the window:
const {universalId} = window.__mpi.segmentWrapperOr use both systems:
let {universalId, universalIdInitialized} = window.__mpi.segmentWrapper
if (!universalId && !universalIdInitialized) {
document.addEventListener(USER_DATA_READY_EVENT, e => {
universalId = e.detail.universalId
doSomethingWithUniversalId(universalId)
})
}
console.log(universalId)To not send the xandrId put this flag as configuration: window.__mpi.segmentWrapper.sendXandrId = false
By default, all xandrId will be sent.
You can find info about segment's middleware here
Will use segment's anonymousId as optimizely's userId
import {optimizelyUserId} from '@s-ui/segment-wrapper/lib/middlewares/source/optimizelyUserId'
window.analytics.ready(() => {
window.analytics.addSourceMiddleware(optimizelyUserId)
})Will add the site property as optimizely attribute
import {optimizelySiteAttributeMiddleware} from '@s-ui/segment-wrapper/lib/middlewares/destination/optimizelySiteAttribute'
window.analytics.ready(() => {
window.analytics.addDestinationMiddleware('Optimizely', [optimizelySiteAttributeMiddleware])
})