Version:

Load JavaScript SDK

Understand the different SDK load options.

You can load the JavaScript SDK using the load API method to track and send events from your website to RudderStack.

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, [loadOptions]);

Loading options

You can use the loadOptions object in the above load call to define various options while loading the SDK. It includes the following optional parameters:

ParameterTypeDescription
logLevelStringValues include LOG, INFO, DEBUG, WARN, ERROR, and NONE.

Default value: ERROR
integrationsIntegrationOptsSends event data to the selective destinations.
configUrlStringThe control plane endpoint serving your destination configurations.

Default value: https://api.rudderstack.com.
Note that the SDK automatically appends /sourceConfig at the end if it is missing, for example, <configURL>/sourceConfig.
getSourceConfigFunctionReturns custom configuration data to use instead of making a request to the control plane.
queueOptsQueueOptsContains the options to control the behavior of the persistence queue that buffers the events before sending them to the data plane.
loadIntegrationBooleanDetermines whether to load the native destination SDKs. Supported for Amplitude and Google Analytics destinations only. If set to false, the SDK assumes that the destination SDK is already loaded on your site and proceeds to initialize and forward data to it.

Default value: true
sessionsSessionOptsCaptures the details specific to session tracking.
destSDKBaseURLStringURL used by the SDK to load its integration SDKs.

Default value: The CDN path or automatically determined based on core SDK URL.
useBeaconBooleanDetermines whether the SDK sends event payloads via the Beacon transport mechanism.

Default value: false.
beaconQueueOptionsBeaconQueueOptsControls the behavior of the queue that buffers events before sending them through the Beacon utility in batches. The SDK lets you configure these batching options.
consentManagementObjectSee Consent manager integration for more information.
anonymousIdOptionsObjectAutomatically captures the anonymous ID from a source and sets it as RudderStack’s anonymousId.
lockIntegrationsVersionBooleanDetermines if the SDK should use the same version of the integration SDKs from CDN as the core SDK. This is particularly useful for NPM installations where a specific version of the core SDK is used.

Default value: false, meaning the SDK uses the latest versions of the integration SDKs from the CDN. You can override this parameter by using the destSDKBaseURL option.
lockPluginsVersionBooleanDetermines if the SDK should use the same version of the plugins from CDN as the core SDK. This is particularly useful for NPM installations where users want to be shielded from any unexpected breaking changes introduced by any latest CDN releases.

Default value: false, meaning the SDK uses the latest version of the plugins from the CDN. You can override this parameter by using the pluginsSDKBaseURL option.
polyfillIfRequiredBooleanLoads the polyfills for unsupported features in older browsers.

Default value: true.
onLoadedFunctionCallback function that executes after the SDK loads and before the device mode destination SDKs are loaded.
uaChTrackLevelStringConfigures the level of information captured in the context object. The SDK fetches this information using the user-agent client hints API.
sendAdblockPageBooleanEnables the SDK to detect if the current page is ad-blocked and send an automatic page event. See Detect Ad-blocked Pages for more information.

Default value: false.
sendAdblockPageOptionsObjectIf sendAdblockPage is set to true, the SDK makes an implicit page call about the ad-blocked pages. You can then use this option to specify destinations to which you want to forward this page call. See Detect Ad-blocked Pages for more information.
useGlobalIntegrationsConfigInEventsBooleanLets you automatically use the integrations object specified in the load API at the individual event level.

Default value: false
sameDomainCookiesOnlyBooleanDetermines whether the SDK should read cookies from the exact domain it is set at.

Default value: false

If this load option is set to true, then the cookies set from the site’s top-level domain are not accessible by the sub-domains and vice versa.
pluginsSDKBaseURLStringBase URL path used by SDK to load the plugins.

Default value: Standard CDN path or automatically determined from the core SDK location.
destinationsQueueOptionsObjectSee destinationsQueueOptions for more information.
pluginsString arrayList of plugins you want the SDK to load.

See Plugins for more information.

Default value: Array of all the plugins names.
polyfillURLStringURL to load polyfills from, not necessarily from the default polyfills service.

Default value: https://polyfill-fastly.io/v3/polyfill.min.js with dynamic calculation of missing features from the browser.

Example: Suppose your browser is missing the following features required by the SDK:
  • Array.includes
  • String.startsWith
  • Promise
Then the polyfill URL will look like this (not exactly):
https://polyfill-fastly.io/v3/polyfill.min.js?features=Array.prototype.includes%2CString.prototype.startsWith%2CPromise.
storageObjectConfigures different storage-related features like, encryption, migration, etc.

See Storage for more information.
consentManagementObjectLets you specify the consent management preferences.
externalAnonymousIdCookieNameStringName of the cookie for the SDK to fetch the anonymous ID and use it as RudderStack’s anonymousId.

See externalAnonymousIdCookieName for more information.
warning

The following load API options are deprecated in the latest JavaScript SDK in favour of the storage.cookie option:

The following snippet highlights some basic and commonly configured load options. Note that it does not include all the load options.

{
  logLevel: 'DEBUG',
  integrations: {
    All: true,
    "Google Analytics 4": false
  },
  queueOptions: {
    maxItems: 200,
    maxAttempts: 15
  },
  useBeacon: true,
  beaconQueueOptions: {
    maxItems: 50,
    flushInterval: 60000 // 1 minute
  },
  consentManagement: {
    enabled: true,
    provider: 'oneTrust'
  },
  onLoaded: () => {
    console.log('RudderStack JavaScript SDK loaded successfully')
  },
  uaChTrackLevel: "full",
  sendAdblockPage: true
}

The following sections contain the detailed definitions and usage of some of the above parameters:

Integration options

You can use this parameter to filter your event data to selective destinations in the following scenarios:

  • Filter destinations while loading the JavaScript SDK.
  • Sending events to specific destinations at the event level.

The structure of the integrations object is shown:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  integrations: {
    All: boolean, // default true
    <Destination1>: boolean, // specify destination like Google Analytics, Amplitude etc.
    <Destination2>: boolean, // specify destination like Google Analytics, Amplitude etc.
    ...
  }
});

The following table describes the above (optional) parameters in detail:

ParameterTypeDescription
AllBooleanAll destinations to which the event data must be sent. The default value is true. If set to false, RudderStack will not send the event data to any destination.
<Destination>BooleanSpecific destination to which the event data must be sent/not, depending on its Boolean value.

You must specify the actual destination name (as listed in the RudderStack dashboard) in the <Destination> parameter and not the name you have assigned to the destination. For example, the below sample snippet sends the event data only to Google Analytics and Intercom destinations:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
    integrations: {
        All: false,
        "Google Analytics": true,
        "Intercom": true
    }
});

Get source configuration

The getSourceConfig function returns a custom configuration that can be used in place of your open source control plane’s dashboard configuration:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  getSourceConfig: function() {
    return {
      // custom configuration
    };
  },
  // other load options
});

Queue options

The queueOpts object contains the options to control the behavior of the persistence queue that buffers the events before sending them to RudderStack. Its structure is defined as follows:

{
  maxRetryDelay: 360000,
  minRetryDelay: 1000,
  backoffFactor: 2,
  backoffJitter: 0,
  maxAttempts: 10,
  maxItems: 100,
  batch: {
    enabled: true,
    maxItems: 100,
    maxSize: 512 * 1024, // 512 KB
    flushInterval: 60000 // In ms
  },
}

The following table describes the above integer type (optional) parameters in detail:

ParameterDescriptionDefault value
maxRetryDelayUpper limit on the maximum delay (in ms) between each retries of an event.360000
minRetryDelayMinimum wait time (in ms) between each retries of an event.1000
backoffFactorExponential base.2
backoffJitterJitter to be applied to the delay.0
maxAttemptsMaximum number of attempts to send the event to the RudderStack backend (data plane).10
maxItemsMaximum number of events buffered in the persistent storage for processing.100
batchOptions for batched requests.BatchOpts
Batch request options
ParameterDescriptionDefault value
enabledDetermines whether to enable batching.false
maxItemsMaximum number of events in a batch.100
maxSizeMaximum batch payload size (in bytes).512 KB (Also the maximum configurable value)
flushIntervalMinimum interval (in ms) between two batch requests.60000
info

Note that:

  • queueOptions.batch is an optional object, meaning batching is disabled by default.
  • The SDK makes a batch request when either of the following criteria is met:
    • maxItems in a batch is reached.
    • maxSize of the batch is reached.
    • Time period of flushInterval ms has elapsed since the last batch request.

Session options

The SessionOpts object contains the options related to the SDK’s automatic session tracking behavior. Refer to the Session Tracking guide for more information. Its structure is defined as follows:

ParameterDescriptionDefault value
autoTrackDetermines if the SDK should automatically track the user sessions.true
timeoutThe maximum inactivity period (in ms) before the session expires.1800000 (30 minutes)

Consent management options

Once a user provides the consent, you can load the JavaScript SDK and enable the OneTrust integration via the consentManagement object:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  consentManagement: {
    enabled: true,
    provider: "oneTrust"
  },
  // other options
});

Anonymous ID options

You can use the anonymousIdOptions object to automatically capture the anonymous ID from a source and set it as RudderStack’s anonymousId.

For example, if you are migrating from a particular source and want to retain its anonymous ID, you can enable the anonymousIdOptions to set the source’s anonymous ID as the anonymousId in RudderStack.

The structure of anonymousIdOptions is defined as follows:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  anonymousIdOptions: {
    autoCapture: {
      enabled: true,
      source: "segment"
    }
  }
});

The following table describes the above (required) parameters in detail:

ParameterTypeDescription
enabledBooleanDetermines if the anonymous ID should be auto-captured.
sourceStringDetermines the external source of anonymous ID. The only allowed value is segment.
info
If the RudderStack anonymousId is already set in your browser, anonymousIdOptions will not take effect.
info
You can call the reset API to clear the persisted anonymous ID and force the SDK to generate a new ID when the next tracking API is called (irrespective of whether anonymousIdOptions is enabled or disabled). However, if the anonymousIdOptions object is enabled and the SDK is loaded again (as a result of webpage reload, navigate to a different webpage, etc.), the setAnonymousId call will trigger automatically and the specified source’s anonymous ID will again be set as the RudderStack anonymousId.

Configure information present in context

You can use the uaChTrackLevel option to configure the information a user should get in the context object regarding the client hints. The JavaScript SDK fetches this information using the user-agent client hints API. It can take the below values:

  • none: Specifies that uaChTrackLevel field is absent in the context object.
  • default: Specifies that uaChTrackLevel field is present in the context object and contains an object similar to the one below:
{
  "brands": [{
    "brand": "Chromium",
    "version": "110"
  }, {
    "brand": "Not A(Brand",
    "version": "24"
  }, {
    "brand": "Google Chrome",
    "version": "110"
  }],
  "mobile": false,
  "platform": "macOS"
}
  • full: Specifies that uaChTrackLevel field is present in the context object and contains an object similar to the one below:
{
  "architecture": "arm",
  "bitness": "64",
  "brands": [{
    "brand": "Chromium",
    "version": "110"
  }, {
    "brand": "Not A(Brand",
    "version": "24"
  }, {
    "brand": "Google Chrome",
    "version": "110"
  }],
  "fullVersionList": [{
    "brand": "Chromium",
    "version": "110.0.5481.77"
  }, {
    "brand": "Not A(Brand",
    "version": "24.0.0.0"
  }, {
    "brand": "Google Chrome",
    "version": "110.0.5481.77"
  }],
  "mobile": false,
  "model": "",
  "platform": "macOS",
  "platformVersion": "13.1.0",
  "uaFullVersion": "110.0.5481.77",
  "wow64": false
}

The onLoaded callback function

The onLoaded callback function takes the rudderanalytics instance as an argument and executes after the JavaScript SDK loads and before the native device-mode destination SDKs are loaded.

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  onLoaded: function(rudderanalytics) {
    console.log("All set!");
  }
});

Use globally-defined integration options at event level

You can use this option to use the integrations object of the load method at the event level when it is not present at the event level.

For example, if the integrations object is defined in the load method and the useGlobalIntegrationsConfigInEvents option is set to true:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  integrations: {
    All: true,
    "Google Analytics": false,
    ...
  },
  useGlobalIntegrationsConfigInEvents: true,
  // other load options
});

Case 1: integrations option is present at the event level:

rudderanalytics.track(
  "Order Completed", {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345
  }, {
    integrations: {
      All: true,
      Amplitude: false
    },
  },
  () => {
    console.log("track call");
  }
);

In this case, the JavaScript SDK uses the integrations option from the track event.

Case 2: integrations option is not present at the event level:

rudderanalytics.track(
  "Order Completed", {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345
  }, {},
  () => {
    console.log("track call");
  }
);

In this case, the SDK uses the integrations option from the load method.

Destination queue options

The destinationsQueueOptions object controls the behavior of the in-memory queue that buffers events before sending them to the device mode destinations. Its structure is defined as follows:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  destinationsQueueOptions: {
    maxItems: 100
  }
});
ParameterTypeDescription
maxItemsIntegerMaximum number of events the device mode destinations (in-memory) queue can store while the destinations are still loading.

Default value: 100

Set external anonymous ID cookie name

You can use this option to specify the cookie name in cases where the user has set a cookie for the SDK to fetch the external anonymous ID and use it further as the RudderStack’s anonymousId.

If you provide a cookie name that does not exist, the SDK either uses the existing anonymousId or generates a new one.

Note that the external anonymousId is fetched only once while loading the SDK and any changes to the anonymousId cookie mid-session is not reflected in the events. To modify the anonymousId stored by RudderStack in such cases, use the setAnonymousId method.

Plugins

Plugins are JavaScript SDK features that you can optionally load on demand.

NameDescription
BeaconQueueUses the browser’s Beacon utility to send a batch of events to the data plane instead of a single event per request.

See Sending events using Beacon for more information.
DeviceModeDestinationsLoads the device mode destinations supported by RudderStack.
ErrorReportingReports SDK errors to RudderStack.
ExternalAnonymousIdLets you migrate the external anonymous user IDs to RudderStack’s anonymousId.

See anonymousIdOptions for more information.
GoogleLinkerProvides anonymousId from Google AMP Linker URL query parameters.
NativeDestinationQueueStores incoming events in a queue and sends them to the device mode destinations.
StorageEncryptionLegacyExisting (SDK version v1.1 or below) approach to encrypt/decrypt data before storing the data.
StorageEncryptionLightweight alternative to encrypt/decrypt data before storing the data.
StorageMigratorAssists the SDK in migrating the legacy encrypted persisted data.
XhrQueueStores incoming events in a local storage retry queue and sends them to the data plane via XMLHttpRequest.
OneTrustConsentManagerIntegrates the OneTrust consent manager.

See OneTrust consent management for web for more information.
KetchConsentManagerIntegrates the Ketch consent manager.

See Ketch consent management for web for more information.
BugsnagIntegrates Bugsnag as an error reporting provider.

If you wish to use only a subset of the SDK features, you can explicitly specify the plugins in the plugins option while loading the SDK.

For example, if you do not want the external anonymous ID, Google Linker and error reporting features, you can provide an array of plugin names excluding those plugins. A sample snippet highlighting how to set the plugins load option in this scenario:

plugins: ["BeaconQueue", 
          "DeviceModeDestinations", 
          "NativeDestinationQueue",
          "StorageEncryptionLegacy",
          "StorageEncryption",
          "StorageMigrator",
          "XhrQueue",
          "OneTrustConsentManager",
          "KetchConsentManager"
         ]
warning
If you set the plugins option and exclude certain plugins from the list (for example, OneTrustConsentManager), setting the associated options while loading the SDK (for example, consentManagement.provider to oneTrust) will have no effect.

If you do not specify the plugins option while loading the JavaScript SDK, then RudderStack considers all plugins mentioned in the above table by default.

info

Once the list of plugins is determined, the SDK automatically loads a subset of them based on your load options, browser capabilities, and source configuration.

For example, if you set consentManagement.provider to ketch, then the SDK will not load OneTrustConsentManager plugin by default.

Lazyloading plugins

For older browsers and users intentionally using the legacy Javascript SDK, RudderStack bundles the plugins with the core SDK. However, for modern browsers, the SDK lazy loads the plugins as multiple small chunks. These chunks are very small in size and loaded with the website parallelly.

The SDK’s bundling tool uses a package that supports Module Federation to bundle each feature into separate code chunks that can have interdependency among themselves. These chunks act as containers and can expose and consume code between them, creating a single, unified application. These chunks or plugins are then uploaded into CDN.

Depending on the load options, browser capabilities, and source configuration, RudderStack fetches these plugins from the remote location at runtime when the SDK loads.

Storage

You can use the storage load option to configure different storage-specific features like encryption and migration.

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  storage: {
    encryption: {
      version: "v3" / "legacy"
    },
    migrate: true / false,
    cookie: {
      maxage: 31536000 * 1000, // 1 year
      path: "/",
      domain: "example.com",
      samesite: "Lax",
      secure: true / false
    }
  }
});
ParameterTypeDescription
encryptionObjectConfigures the encryption type for persisted user data. It consists of a version parameter that accepts two values - v3 and legacy.

The SDK uses Base64 encryption if you set version to v3 and AES encryption for legacy.

Default value: v3
migrateBooleanMigrates persisted legacy encrypted data if set to true.

Default value: true
cookieObjectContains the configurable options for the cookie.

See Cookie settings for more information.
warning

If you set version to legacy, then you must also load the StorageEncryptionLegacy plugin. For v3, you must load the StorageEncryption plugin.

Similarly, if you do not set migrate to false, then you must also load the StorageMigrator plugin.

Note that:

  • If you access the SDK persisted data directly from the cookie or local storage, you must update the custom decryption logic.
  • All sites under the same top-level domain must use the same encryption version. For example, if xyz.test.com uses the latest JavaScript SDK and abc.test.com uses a legacy SDK version (v1.1 or below), then you should set the storage load option as follows:
rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  storage: {
    encryption: {
      version: "legacy"
    }
  },
  // other load options
});
  • Migrating all your subdomain sites to use SDK v3 is recommended.

The cookie object contains the configurable options for your cookie. All parameters in this object are optional.

warning
The configuration provided in these cookie options overrides any other cookie settings.
ParameterTypeDescription
maxageNumberMaximum duration (in ms) that the cookie lives.

Default value: 1 year
pathStringPath of the page where the cookie is accessible.

Default value: /
domainStringSets the cookie domain.

Default value: The SDK captures and uses the current domain as the default value.
samesiteStringSets the SameSite attribute of the cookie.

Default value: Lax
secureBooleanDetermines if the SDK should send the cookie to the storage backend via HTTPS.

Default value: false

Configure persistent data storage

While loading the JavaScript SDK, you can specify the information to store (userId, anonymousId, session information, etc.) and whether to store it in your browser’s cookies, local storage, in-memory storage, or not store it at all (fully anonymous tracking).

See Configure Persistent Data Storage guide for more information.

You can integrate the JavaScript SDK with leading consent management solutions like OneTrust and Ketch or set up a custom consent management solution.

In addition, you can also configure the pre-consent behavior - either tracking users as fully anonymous, tracking only their sessions, or tracking with anonymousId as their identifier. This minimizes any data loss related to attribution, acquisition, and the overall user journey.

Use the consentManagement load option to set your consent management preferences while loading the SDK, as shown:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  consentManagement: {
    enabled: true,
    provider: 'oneTrust' // `ketch`
  }
});

Load SDK for self-hosted control plane

If you are self-hosting the control plane using the Control Plane Lite utility, the load call should be made as below:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  configUrl: CONTROL_PLANE_URL,
});

Allowlist RudderStack domain

If you are using RudderStack’s CDN for the SDK content, add the following (minimum) content security policy (CSP) header configuration to load the JavaScript SDK without any errors:

info
A content security policy (CSP) adds an extra layer of protection from any type of cross-site scripting, clickjacking, and data injection attacks.
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' https: //cdn.rudderlabs.com/ https://cdn.rudderstack.com/;">

If you don’t want to allow unsafe inline and use the CDN package with its loading snippet, use nonce attribute to the script tag for the loading snippet:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'nonce-rAnd0m' https: //cdn.rudderlabs.com/ https://cdn.rudderstack.com/;">

If you use the NPM package, no inline loading snippet is required:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' https: //cdn.rudderlabs.com/ https://cdn.rudderstack.com/;">

Device mode destinations

While using the JavaScript SDK with destinations that support device mode, you might need to allowlist the domain from where the destination SDK loads in your content security policy (CSP).

See the specific destination’s documentation to obtain the domain to be allowlisted. For example, Braze.

Tracking user sessions

By default, the JavaScript SDK automatically tracks the user sessions. This means that RudderStack automatically determines the start and end of a user session depending on the inactivity time configured in the SDK (default time is 30 minutes).

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  sessions: {
    autoTrack: true,
    timeout: 10 * 60 * 1000,  // 10 min in milliseconds
  },
  ...<otherLoadOptions>
});

To disable automatic session tracking, you can set the load option autoTrack to false.

For more information on the user sessions and how to track them using the JavaScript SDK, refer to the Session Tracking guide.

Send events using Beacon

The JavaScript SDK lets you send the event payloads using the XHR (XMLHttpRequest) API (default) or Beacon browser utility.

There are two advantages of using the Beacon utility to send your event payload:

  • The events delivery request is executed even when the page unloads, leading to no loss of data.
  • The Beacon requests are optimized so that the browser waits until the CPU load is lower or until the network is free before making the actual requests, leading to better website performance.
info
The Beacon queue maintained by the browsers limits the total size of the elements present in the queue at any point and peaks at 64 KB.

See Event delivery and retry mechanism to help you decide whether to use Beacon to send your events.

Workflow

The Beacon browser utility asynchronously sends a small amount of data over HTTP to the RudderStack server. To send the SDK events using this utility, set the useBeacon field in the load() call options to true.

The SDK internally uses a queue (BeaconQueueOpts) to buffer the events and send it through the Beacon utility in batches. The queue options can be configured as shown below:

{
  maxItems: 10, 
  flushQueueInterval: 600000 // In ms
}

The following table describes the above integer type parameters in detail:

ParameterDescriptionDefault Value
maxItemsThe SDK flushes the events queue when the event count meets this limit.10
flushQueueIntervalThe SDK flushes the events queue periodically at this interval (ms).600000
info
The JavaScript SDK flushes the Beacon events queue if the total size of the payload exceeds 64 KB before even reaching the maxItems or flushQueueInterval criteria.

Event delivery and retry mechanism

This section highlights some important points which will help you choose whether to use Beacon for sending your event payloads:

  • The requests sent from the SDK using the Beacon utility only push the events to the browser’s Beacon queue. Further, it depends on the browser’s engine to send these events from the queue. Hence, RudderStack cannot guarantee if any events get discarded due to any 5xx or other network-related errors (request timed out, end resource unavailable, etc.).
warning
If event delivery and retry is an important requirement for your website, using the XHR API of the JavaScript SDK is highly recommended. RudderStack retries event delivery based on the status codes and other errors.
  • The Beacon queue maintained by the browsers limits the total size of the elements present in the queue at any point and peaks at 64 KB. Therefore, you cannot send high-frequency hits from the main thread in one go, as the Beacon queue cannot take up cycles to dequeue itself.


Questions? Contact us by email or on Slack