You can load the JavaScript SDK using the load API method to track and send events from your website to RudderStack. It can be defined as:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, [loadOptions]);
Replace WRITE_KEY and DATA_PLANE_URL in the above snippet with the actual values.

Loading options

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

{
logLevel: "DEBUG" | "INFO" | "WARN",
integrations: IntegrationOpts,
configUrl: string, // defaults to https://api.rudderlabs.com
queueOptions: QueueOpts,
loadIntegration: boolean, // defaults to true.
sessions: SessionOpts,
secureCookie: boolean, // defaults to false.
destSDKBaseURL: string, // defaults to https://cdn.rudderlabs.com/v1.1/js-integrations
useBeacon: boolean, // defaults to false.
beaconQueueOptions: BeaconQueueOpts,
cookieConsentManager: cookieConsentManager,
anonymousIdOptions: AnonymousIdOptions,
setCookieDomain: string, // defaults to current domain.
sameSiteCookie: "Strict" | "Lax" | "None" // defaults to Lax.
}

The detailed description of these parameters is as follows:

ParameterTypeDescription
logLevelStringValues include DEBUG, INFO, and WARN.
integrationsIntegrationOptsSends event data to the selective destinations.
configUrlStringThe Control Plane endpoint serving your destination configurations. Default value is https://api.rudderlabs.com. Note that sourceConfig is automatically appended to this endpoint in the format https://api.rudderlabs.com/<source_config_url>/sourceConfig
queueOptsQueueOptsContains the options to control the behavior of the persistence queue that buffers the events before sending them to the data plane.
loadIntegrationBooleanDetermines whether the destination SDKs are fetched by the SDK or not. Default value is True. Supported for Amplitude and Google Analytics.
sessionsSessionOptsCaptures the details specific to session tracking.
secureCookieBooleanDetermines whether the SDK sends the cookie to the storage backend via HTTPS. Default value is False.
destSDKBaseURLStringPath used by the SDK to load the integrations. Default value is https://cdn.rudderlabs.com/v1.1/js-integrations. Reference.
useBeaconBooleanDetermines whether the SDK sends event payloads via Beacon. Default value is False.
beaconQueueOptionsBeaconQueueOptsInternal queue to hold the data and send it through the Beacon utility in batches.
cookieConsentManagerObjectRefer to the Consent manager integration section.
anonymousIdOptionsObjectAutomatically captures the anonymous ID from a source and sets it as RudderStack’s anonymousId.
setCookieDomainStringSets the cookie domain. SDK captures and uses the current domain as the default value. Refer to the Data Storage guide for more information.
sameSiteCookieStringSets the SameSite attribute of a cookie. Default value is Lax.

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

IntegrationOpts

You can use this parameter to send the event data only to the selective destinations. Its structure is defined as follows:

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
}
});

QueueOpts

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,
maxAttempts: 10,
maxItems: 100,
}

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

ParameterDescriptionDefault value
maxRetryDelayUpper limit on the maximum delay for an event (in ms).360000
minRetryDelayMinimum delay expected before sending an event (in ms).1000
backoffFactorExponential base.2
maxAttemptsMaximum number of attempts to send the event to the destination.10
maxItemsMaximum number of events kept in the storage.100

SessionOpts

The SessionOpts object contains the options related to the SDK's automatic session tracking behavior. Its structure is defined as follows:

ParameterDescriptionDefault value
autoTrackDetermines if the SDK should automatically track the user sessions.true
timeoutThe maximum inactivity period before the session expires.1800000 ms (30 minutes)
For more information on using the SessionOpts object, refer to the Session Tracking guide.

cookieConsentManager

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

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
cookieConsentManager: {
oneTrust: {
enabled: true
}
}
});

anonymousIdOptions

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.
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 specified source's anonymous ID will again be set as the RudderStack anonymousId.

Loading 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 > ,
});
Replace WRITE_KEY and DATA_PLANE_URL in the above snippet with the actual values.

Verifying if the SDK has loaded correctly

You can verify if the JavaScript SDK has loaded correctly by opening the JavaScript console in your browser:

  • Safari: Ctrl+Alt+I (Windows) or Command+Option+I (Mac) and go to the Console tab.
  • Chrome: Ctrl+Shift+J (Windows) or Command+Option+J (Mac).
  • Firefox: Ctrl+Shift+K (Windows) or Command+Option+K (Mac) and select the Console tab.
  • Internet Explorer: Press F12 and go to the Console tab.

Run the rudderanalytics command in the console. If it returns the following code snippet, it means that the analytics.js file has loaded successfully:

{Integrations: Object, _integrations: Object, _readied: true, _timeout: 300, _user: n_}

If it gives an undefined error, you need to verify the SDK installation.

Allowlist destination domain

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

A content security policy adds an extra layer of protection from any type of cross-site scripting, clickjacking, and data injection attacks.

You can refer to the Getting started section of the specific destination's documentation to obtain the domain that might need to be allowlisted.

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.

Contact us

For more information on the topics covered on this page, email us or start a conversation in our Slack community.

On this page