Skip to main content

Initialize and configure the web trackers

Initialize the tracker by calling the newTracker function. It takes three arguments:

  1. The tracker namespace
  2. The Collector endpoint
  3. An optional configuration object containing other settings

Here is a simple example of how to initialise a tracker, setting a few configuration options:

javascript
// The tracker namespace is 'sp' in this example
snowplow('newTracker', 'sp', '{{collector_url_here}}', {
appId: 'my-app-id',
appVersion: '0.1.0',
cookieSameSite: 'Lax', // Recommended
contexts: {
session: true
}
});

The tracker will send events to the Collector URL you specify by replacing {{collector_url_here}}. The final argument is the configuration object. Here it's used to set the app ID and enable the session entity for each event. Each event the tracker sends will have an app_id field set to my-app-id.

If your code calls newTracker multiple times with the same namespace, only the first call is taken into account.

For Single Page Apps

Initialize one tracker per initial page load.

The following table shows all the configuration parameters. These are all optional: you aren't required to provide any configuration object at all.

PropertyDescriptionDefault (if applicable)Type
appIdSet the application ID.string
appVersionSet the application version.string
platformSet the application platform.webstring enum
cookieDomainSet the cookie domain.Current domainstring
discoverRootDomainAutomatic discovery and setting of the root domain, to facilitate tracking over multiple subdomains.trueboolean
cookieNameSet the cookie name prefix._sp_string
cookieSameSiteSet the cookie SameSite attribute.Laxstring enum
cookieSecureSet the cookie Secure attribute.trueboolean
encodeBase64Enable Base64 encoding for self-describing event and entity data.true for GET, false for POSTboolean
respectDoNotTrackRespect the browser Do Not Track setting.falseboolean
eventMethodSend events by GET or POST.poststring enum
bufferSizeNumber of events to buffer before sending.1int
maxPostBytesMaximum size in bytes for POST requests.40000int
maxGetBytesMaximum size for GET request URLs.int
postPathCustom collector POST path./com.snowplowanalytics.snowplow/tp2string
crossDomainLinkerFunction to determine which links to decorate for cross-domain tracking.function
useExtendedCrossDomainLinkerUse extended format for cross-domain linker with additional user/session data.falseboolean or object
cookieLifetimeSet the cookie lifetime in seconds.63072000 (2 years)int
sessionCookieTimeoutSet the session timeout in seconds.1800 (30 minutes)int
stateStorageStrategyHow to store tracker state.cookieAndLocalStoragestring enum
maxLocalStorageQueueSizeMaximum events to queue in local storage when they are failing to send.1000int
resetActivityTrackingOnPageViewReset page ping timers when a page view is tracked.trueboolean
connectionTimeoutRequest timeout in milliseconds.5000int
anonymousTrackingEnable anonymous tracking (do not track user identifiers).falseboolean or object
customHeadersCustom headers to add to POST requests.object
credentialsWhether to send credentials (cookies) with requests.includestring enum
contextsConfigure context entities to add to all events.{ webPage: true }object
pluginsPlugins to extend tracker functionality.[]BrowserPlugin[]
retryStatusCodesHTTP status codes to retry requests on.int[]
dontRetryStatusCodesHTTP status codes to never retry.[400, 401, 403, 410, 422]int[]
retryFailedRequestsRetry failed requests (timeouts, network errors).trueboolean
onSessionUpdateCallbackCallback executed when the session identifier updates.function
onRequestSuccessCallback executed when a request succeeds (2xx status).function
onRequestFailureCallback executed when a request fails (non-2xx status).function
preservePageViewIdForUrlControl when a new page view ID is generated based on URL changes.falseboolean or string enum
customFetchOverride the default fetch function with a custom implementation.function
eventStoreCustom EventStore implementation for storing events before sending.object
keepaliveAllow requests to outlive the webpage. Enables requests to complete even if the page is closed.falseboolean
synchronousCookieWriteWrite cookies synchronously (blocks main thread).falseboolean

Here is a longer code example in which every tracker configuration parameter is set:

javascript
snowplow('newTracker', 'sp', '{{collector_url_here}}', {
appId: 'my-app-id',
appVersion: '0.1.0',
platform: 'web',
cookieDomain: null,
discoverRootDomain: true,
cookieName: '_sp_',
cookieSameSite: 'Lax', // Recommended
cookieSecure: true,
encodeBase64: true,
respectDoNotTrack: false,
eventMethod: 'post',
bufferSize: 1,
maxPostBytes: 40000,
maxGetBytes: 1000, // available in v3.4+
postPath: '/custom/path', // Collector must be configured
crossDomainLinker: function (linkElement) {
return (linkElement.href === 'http://acme.de' || linkElement.id === 'crossDomainLink');
},
useExtendedCrossDomainLinker: {
userId: true,
},
cookieLifetime: 63072000,
sessionCookieTimeout: 1800,
stateStorageStrategy: 'cookieAndLocalStorage',
maxLocalStorageQueueSize: 1000,
resetActivityTrackingOnPageView: true,
connectionTimeout: 5000,
anonymousTracking: false,
// anonymousTracking: { withSessionTracking: true },
// anonymousTracking: { withSessionTracking: true, withServerAnonymisation: true },
customHeaders: {}, // Use with caution. Available from v3.2.0+
credentials: 'include', // Available from v4+
contexts: {
webPage: true, // Default
session: false, // Adds client session context entity to events, off by default. Available in v3.5+.
browser: false, // Adds browser context entity to events, off by default. Available in v3.9+.
performanceNavigationTiming: true, // Adds performance navigation timing entity. Available in v4.0.2+
performanceTiming: true,
gaCookies: true,
// gaCookies: { ga4: true, ua: false, ga4MeasurementId: "", cookiePrefix: "_ga_" }, // Optional
geolocation: false,
clientHints: true,
// clientHints: { includeHighEntropy: true }, // Optional
},
retryStatusCodes: [],
dontRetryStatusCodes: [],
retryFailedRequests: true,
onSessionUpdateCallback: function(clientSession) { }, // Allows the addition of a callback, whenever a new session is generated. Available in v3.11+.
onRequestSuccess: function(data) => { }, // Available in v3.18.1+
onRequestFailure: function(data) => { }, // Available in v3.18.1+
preservePageViewIdForUrl: false,
keepalive: false, // Introduced in v4
customFetch: undefined, // Introduced in v4
eventStore: undefined, // Introduced in v4
synchronousCookieWrite: false,
});

You can further extend the tracker functionality by installing plugins. Read more about them here.