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:
Parameter
Type
Description
logLevel
String
Values include LOG, INFO, DEBUG, WARN, ERROR, and NONE.
The 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.
Contains the options to control the behavior of the persistence queue that buffers the events before sending them to the data plane.
loadIntegration
Boolean
Determines 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.
Controls 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.
Determines 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.
lockPluginsVersion
Boolean
Determines 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.
polyfillIfRequired
Boolean
Loads the polyfills for unsupported features in older browsers.
Configures the level of information captured in the context object. The SDK fetches this information using the user-agent client hints API.
sendAdblockPage
Boolean
Enables 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.
sendAdblockPageOptions
Object
If 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.
URL 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.
storage
Object
Configures different storage-related features like, encryption, migration, etc.
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,//or object
<Destination2>:boolean// or object
...}});
The following table describes the above (optional) parameters in detail:
Parameter
Type
Description
All
Boolean
Global filtering status for all the destinations. The default value is true.
If set to false, RudderStack filters all the destinations unless you override this setting with destination-specific parameters. For example:
{ All: false, Amplitude: true }
The above snippet causes the SDK to filter all destinations except Amplitude.
<Destination>
Boolean / Object
Specific destination to filter. It overrides the All parameter value.
If the type is object, the SDK automatically assumes this parameter as true. You can use this field for sending destination-specific custom configuration/data to the integration module in cloud and device modes.
The destination name in the integrations object should match the name exactly as displayed in the RudderStack dashboard, as shown:
It should not be the name that you have assigned while setting up the destination in RudderStack.
The below sample snippet sends the event data only to the Amplitude and Intercom destinations:
The below snippet highlights a case where an object is sent instead of a Boolean. In this case, RudderStack sends an identify event to Mailjet to remove the user named Alex Keener from the list ID 13314el9Z:
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:
Parameter
Description
Default value
maxRetryDelay
Upper limit on the maximum delay (in ms) between each retries of an event.
360000
minRetryDelay
Minimum wait time (in ms) between each retries of an event.
1000
backoffFactor
Exponential base.
2
backoffJitter
Jitter to be applied to the delay.
0
maxAttempts
Maximum number of attempts to send the event to the RudderStack backend (data plane).
10
maxItems
Maximum number of events buffered in the persistent storage for processing.
Minimum interval (in ms) between two batch requests.
60000
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:
Parameter
Description
Default value
autoTrack
Determines if the SDK should automatically track the user sessions.
true
timeout
The 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:
The following table describes the above (required) parameters in detail:
Parameter
Type
Description
enabled
Boolean
Determines if the anonymous ID should be auto-captured.
source
String
Determines the external source of anonymous ID. The only allowed value is segment.
Note that:
If the RudderStack anonymousId is already set in your browser, anonymousIdOptions will not take effect.
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 anonymous ID for the specific source will be set again 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:
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.
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:
Maximum 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.
Optimize timers behavior
The JavaScript SDK internally uses timers to continuously interact with the local storage. These timers acknowledge the local storage status and reclaim any stale event queues. They run at a set frequency optimizing their performance.
Generally, these timers do not impact your webpage. However, if you still feel that your webpage’s performance is degraded by any CPU or memory spikes, you can configure the value of timerScaleFactor parameter. It is an integer with the minimum and maximum values as 1 (default value) and 10 respectively. The higher the value, the slower the timers run - reducing their impact on the page, if any.
Plugins
Plugins are JavaScript SDK features that you can optionally load on demand.
Name
Description
BeaconQueue
Uses the browser’s Beacon utility to send a batch of events to the data plane instead of a single event per request.
Integrates 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:
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.
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}}});
Parameter
Type
Description
encryption
Object
Configures 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
migrate
Boolean
Migrates persisted legacy encrypted data if set to true.
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.
Cookie settings
The cookie object contains the configurable options for your cookie. All parameters in this object are optional.
The configuration provided in these cookie options overrides any other cookie settings.
Parameter
Type
Description
maxage
Number
Maximum duration (in ms) that the cookie lives.
Default value: 1 year
path
String
Path of the page where the cookie is accessible.
Default value: /
domain
String
Sets the cookie domain.
Default value: The SDK captures and uses the current domain as the default value.
samesite
String
Sets the SameSite attribute of the cookie.
Default value: Lax
secure
Boolean
Determines 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).
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:
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:
A content security policy (CSP) adds an extra layer of protection from any type of cross-site scripting, clickjacking, and data injection attacks.
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:
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).
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.
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.
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:
Parameter
Description
Default Value
maxItems
The SDK flushes the events queue when the event count meets this limit.
10
flushQueueInterval
The SDK flushes the events queue periodically at this interval (ms).
600000
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.).
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.
This site uses cookies to improve your experience while you navigate through the website. Out of
these
cookies, the cookies that are categorized as necessary are stored on your browser as they are as
essential
for the working of basic functionalities of the website. We also use third-party cookies that
help
us
analyze and understand how you use this website. These cookies will be stored in your browser
only
with
your
consent. You also have the option to opt-out of these cookies. But opting out of some of these
cookies
may
have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This
category only includes cookies that ensures basic functionalities and security
features of the website. These cookies do not store any personal information.
This site uses cookies to improve your experience. If you want to
learn more about cookies and why we use them, visit our cookie
policy. We'll assume you're ok with this, but you can opt-out if you wish Cookie Settings.