RudderStack's JavaScript SDK leverages the rudder-analytics.js library to track your customer event data from your websites and send it to your specified destinations via RudderStack.

Github Badge
JavaScript SDK v1.1 is now the default version of the JavaScript SDK. It is a lightweight, efficient, and optimized version of the RudderStack JavaScript SDK v1. For more information, refer to the following links: - Introducing RudderStack's New, High-performance JavaScript SDK- Migrating to JavaScript SDK v1.1

For the source code and implementation details, refer to the JavaScript SDK GitHub repository .

The JavaScript SDK stores persistent user data in the cookies. For more information on these cookies, refer to the Data Storage in Cookies guide.

The JavaScript SDK now supports integration with the OneTrust consent manager and lets you map OneTrust cookie/consent groups to RudderStack's consent purposes. For more information on the OneTrust integration, refer to this guide.

Installing the SDK

To quickly set up and start using the RudderStack JavaScript SDK, go through our quick start guide.

Supported APIs

The JavaScript SDK makes it very easy for you to send your event data to any destination without implementing a new API every time.

The following sections detail all the API calls supported by RudderStack for this SDK.

Load

The load method loads the rudder-analytics.js file with the source write key. It is defined as follows:

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

You need to replace the WRITE_KEY with the source write key in the RudderStack dashboard and DATA_PLANE_URL with your data plane URL.

Write key and data plane URL

To integrate and initialize the JavaScript SDK, you need the source write key and the data plane URL.

The options parameter

The options parameter in the above load call looks like the following:

{
logLevel: "DEBUG" | "INFO" | "WARN",
integrations: IntegrationOpts,
configUrl: string, // defaults to https://api.rudderlabs.com
queueOptions: QueueOpts,
loadIntegration: boolean, // defaults to true.
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
}

It includes the following details:

ParameterTypeDescription
logLevelStringOptions include DEBUG, INFO, and WARN.
integrationsIntegrationOptsRefer to the IntegrationOpts section. More information on how to use this parameter can be found here.
configUrlStringDefaults to https://api.rudderlabs.com. You need to provide the server (Control Plane) endpoint serving your destination configurations. Note that sourceConfig is automatically appended to this endpoint by the SDK.
queueOptsQueueOptsRefer to the QueueOpts section.
loadIntegrationBooleanDefaults to true. If set to false, the destination SDKs are not fetched by the SDK. This is supported for Amplitude and Google Analytics.
secureCookieBooleanDefaults to false. If set to true, the SDK sends the cookie to the storage backend via HTTPS.
destSDKBaseURLStringDefaults to https://cdn.rudderlabs.com/v1.1/js-integrations. The SDK will load the integrations from this path. You can also set your own integrations path using this field. For more information, refer to this section.
useBeaconBooleanDefaults to false. If set to true, the SDK sends the event payloads via the navigator.sendBeacon() utility.
beaconQueueOptionsBeaconQueueOptsRefer to the BeaconQueueOpts section.
cookieConsentManagerObjectRefer to the cookieConsentManager section for more information.
anonymousIdOptionsObjectRefer to the Capturing anonymousId automatically section for more information.

For more details, refer to the options parameter section.

The useBeacon option

The JavaScript SDK supports a new Boolean field, useBeacon, in the load() call options. When set to true, the SDK sends events using the navigator.sendBeacon utility.

Refer to this section for more details on using the Beacon transport mechanism.

Loading the SDK for self-hosted control plane

If you are self-hosting the control plane using the RudderStack Control Plane Lite utility, your load call will look like the following:

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

More information on how to get the CONTROL_PLANE_URL can be found here.

Loading selective destinations

RudderStack lets you send your event data to selective destinations specified by you and disable sending events to the rest of the destinations. You can specify these destinations through the load call, as shown in the following snippet:

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
integrations: { All: false, destination_name: true },
});

For more information, check the Filtering selective destinations section.

Chromecast

Google Chromecast is a device that plugs into your TV or monitor with an HDMI port, and can be used to stream content from your phone or computer.

RudderStack supports integrating the JavaScript SDK with your Cast app. Follow these instructions to build your web sender app. Then, add the JavaScript SDK to it.

Follow the Google Cast developer guide for more details.

Identify

The identify method allows you to link the users and their actions to a specific userid. You can also add additional information as traits to a user. Once the identify call is made, the SDK persists the user information and passes it to the subsequent track or page calls.

To reset the user identification, you can use the reset method.

The SDK defines the identify method as shown below:

rudderanalytics.identify(userId, [traits], [options], [callback]);

The identify method has the following parameters:

ParameterTypePresenceDescription
userIdStringOptionalThis string defines the user's ID in your database. If provided, this argument will be sent to destinations as the user ID instead of an anonymousId.
traitsDictionaryOptionalThis dictionary contains the traits or properties associated with a userId such as email, address, etc. More information on the identify traits can be found here.
optionsDictionaryOptionalThis dictionary provides information such as context, integrations, and anonymousId. Specific user traits can be provided as the context as well. Refer to the options section for more information.
callbackFunctionOptionalThis function gets executed after successful execution of the identify() method.

A sample identify call is shown below:

rudderanalytics.identify(
"userId",
{ email: "name@domain.com" },
{
page: {
path: "",
referrer: "",
search: "",
title: "",
url: ""
}
},
() => {
console.log("Sample identify call");
}
);

In the above example, information such as the userId and email along with the contextual information is captured.

If you explicitly specify the IP address in the event, RudderStack will use that address instead of capturing it in the backend. You can use this feature to anonymize your users' IP - e.g., by supplying an anonymous IP address.

anonymousId

The anonymousId is a UUID (Universally Unique Identifier) generated to uniquely identify the user.

If the anonymousId is provided by the user using the setAnonymousId method, the user-specified anonymousId overrides the one generated by the SDK.

For more information on the setAnonymousId method, refer to the Overriding the anonymousId using setAnonymousId section below.

You don't have to call identify for the anonymous visitors to your website. Such visitors are automatically assigned an anonymousId.

How RudderStack uses anonymousId

The JavaScript SDK generates a unique anonymousId, stores it in a cookie named rl_anonymous_id in the top-level domain, and attaches to every subsequent event. This helps RudderStack in identifying the unknown users from other sites that are hosted under a sub-domain. For more information on how the JavaScript SDK stores persistent user data in cookies, refer to Data Storage in Cookies.

If you identify a user with your application's unique identifier like email, database ID etc. RudderStack stores this ID in a cookie named rl_user_id and attaches to every event.

For example, if you include the RudderStack JavaScript SDK in both admin.samplewebsite.com and app.samplewebsite.com, the SDK will store the cookie in the top-level domain samplewebsite.com.

There are two options that you can use to identify anonymous users with the JavaScript SDK:

Overriding anonymousId in the options parameter

There can be scenarios where you may want to provide your own anonymousId instead of an SDK-generated ID. To do so, you can provide the anonymousId in the options parameter of the identify call, as mentioned above. This will send the value provided by you in the anonymousId key of the event.

Note that all other events will have the anonymousId from the one persisted in the cookie, except this event where you override the options.

An example of this approach is as shown in the code snippet below:

rudderanalytics.identify(
"12345",
{ email: "name@domain.com" },
{
anonymousId: "my-anonymous-id"
},
() => {
console.log("in identify call");
}
);

Overriding the anonymousId using setAnonymousId

You can also override the anonymousId for all the future events using the setAnonymousId() method.

An example of this is shown in the following snippet:

rudderanalytics.setAnonymousId("my-anonymous-id");
// All event payloads will have the anonymousId key set "my-anonymous-id".
rudderanalytics.identify("userId", { email1: "name@domain.com" }, () => {
console.log("in identify call");
});

Using AMP Analytics

You can also parse the AMP Linker ID and set the anonymousId, as shown:

rudderanalytics.setAnonymousId(
null,
"<version>*<checkSum>*<idName1>*<idValue1>*<idName2>*<idValue2>..."
);

Here, the second parameter is the AMP Linker ID format in accordance with the specified structure. For the links decorated with the RudderStack Linker parameter, the <idName1> value will be rs_amp_id.

Calling the above method will parse the Linker ID and set the anonymousId as the value of the rs_amp_id key.

Setting a blank userId

If you would like to set a blank userid, pass an empty string or " ".

Do not identify with null, as this will not allow you to pass a traits object and it will keep the current userId.

Use-case

Suppose an anonymous user is identified with a userid and then logs out of their account. You can then identify("", {isLoggedIn: false}) and the user will continue to be identified by their anonymousId for future events.

Identifying new users

To identify new users in scenarios like new logins, you can take one of the following two approaches:

Calling the identify API with a new userid

In this case, RudderStack will reset all the cookies related to the user associated with the userid and traits and update them with the new values provided by you.

The anonymousId will remain unchanged in this case. It will be the value that you set explicitly using `setAnonymousId, or the auto-generated value set by the SDK while loading.

Explicitly calling reset followed by identify

This approach has the exactly same outcome as described in the first approach.

Updating user traits

For updating the user traits, you can call identify with the same userId multiple times with the new traits. This results in all the traits associated with that user getting appended or modified. An example is shown below:

rudderanalytics.identify("userId", { email1: "name@domain.com" }, () => {
console.log("in identify call");
});
rudderanalytics.identify("userId", { email2: "name@domain.com" }, () => {
console.log("in identify call");
});

In the above example, both email1 and email2 will be sent in the payload for the second identify call.

Calling reset() will reset the earlier traits, while identifying a userId with the new traits will update it with the new values.

Page

The page call lets you record your website's page views with any additional relevant information about the viewed page.

Many destinations require the page events to be called at least once every page load.

The page() method is defined as follows:

rudderanalytics.page(category, name, [properties], [options], [callback]);

The page method has the following parameters:

ParameterTypePresenceDescription
categoryStringOptionalDefines the page category.
nameStringOptionalDefines the name of the page.
propertiesDictionaryOptionalDefines the properties of the page. These properties are auto-captured by the SDK.
optionsDictionaryOptionalProvides information such as context, integrations, anonymousId, etc. Specific user traits can also be provided as the context. Refer to the options section for more information.
callbackFunctionOptionalCalled after the successful execution of the page() method.

A sample page() call is shown below:

rudderanalytics.page(
"Cart",
"Cart Viewed",
{
path: "",
referrer: "",
search: "",
title: "",
url: ""
},
() => {
console.log("in page call");
}
);

In the above example, the SDK also captures the information such as the page category and page name along with the contextual information.

Track

The track call lets you record the customer events, i.e. the actions that they perform, along with any properties associated with those actions.

The SDK defines the track() method as follows:

rudderanalytics.track(event, [properties], [options], [callback]);

The track method has the following parameters:

ParameterTypePresenceDescription
eventStringRequiredCaptures the name of the tracked event.
propertiesDictionaryOptionalTracks the event properties.
optionsDictionaryOptionalTracks the information like the context, integrations, etc. Specific user traits can also be provided as the context. Refer to the options section for more information.
callbackFunctionOptionalCalled after the successful execution of the track call.

A sample track call is as shown:

rudderanalytics.track(
"test track event GA3",
{
revenue: 30,
currency: "USD",
user_actual_id: 12345
},
() => {
console.log("in track call");
}
);

In the above example, the method tracks the event test track event GA3 along information like the revenue, currency, and the user ID.

Alias

Many destination platforms need an explicit alias call for mapping the already identified users to a new identifier that you may want to use, to track them in the future. The alias call lets you implement this functionality.

The SDK defines the alias() method as shown:

rudderanalytics.alias(to, from, [options], [callback]);

The alias call has the following parameters:

ParameterTypePresenceDescription
toStringRequiredDenotes the new identifier of the user.
fromStringOptionalDenotes the old identifier which will be an alias for the to parameter. If not provided, the SDK will populate this as the currently identified userId, or anonymousId in case of anonymous users.
optionsDictionaryOptionalA dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the options section for more information.
callbackFunctionOptionalThis function gets executed after the successful execution of the alias() method.

A sample alias() method is shown below:

rudderanalytics.alias("test_new_id", "old_user_id", () => {
console.log("alias call");
});

Group

The group call lets you link an identified user with a group such as a company, organization, or an account. It also lets you record any custom traits associated with that group such as the name of the company, the number of employees, etc.

The group() method is defined as shown below:

rudderanalytics.group(groupId, [traits], [options], [callback]);

The group method has the following parameters:

ParameterTypePresenceDescription
groupIdStringRequiredDenotes the group identifier to which the traits are to be modified or added. RudderStack will call the destination APIs to attach the currently identified user to this group.
traitsDictionaryOptionalDenotes the group traits. RudderStack will pass these traits to the destination to enhance the group properties.
optionsDictionaryOptionalA dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the options section for more information.
callbackFunctionOptionalGets executed after the successful execution of the group() method.

A sample group() call is as shown:

rudderanalytics.group("sample_group_id", {
name: "CompanyA",
location: "USA",
});

Reset

The reset method resets the ID and traits of both the user and the group.

The following snippet shows an example of the reset() method:

rudderanalytics.reset();

You can also reset the anonymousId along with the details mentioned above by passing true to the reset() method, as shown:

rudderanalytics.reset(true);
The reset() method only clears the cookies and local storage set by RudderStack. It does not clear the information stored by the integrated destinations. To completely clear the user session, refer to the destination-specific documentation.

Parameter definitions

This section details the type definitions of the parameters used in some of the API methods described above:

options

The structure of options parameter is as shown:

{
integrations: IntegrationOpts,
anonymousId: string,
originalTimestamp: ISO 8601 date string,
<other keys>: <value> // merged with event's contextual information
}

The following table describes each of the above parameters in detail:

ParameterTypeDescription
integrationsIntegrationOptsRefer to the IntegrationOpts section. More information on how to use this parameter can be found here.
anonymousIdStringOverrides the current event's anonymousId at the top level.
originalTimestampISO 8601 Date stringOverrides the current event's originalTimestamp at the top level.
<other keys>: <value>-Merged with the event's contextual information.

IntegrationOpts

The structure of IntegrationOpts looks like the following:

{
All: boolean, // default true
<Destination1>: boolean,
<Destination2>: boolean,
...
}

The following table describes each of the above parameters in detail:

ParameterTypePresenceDescription
AllBooleanOptionalCorresponds to all the destinations to which the event is to be sent. The default value is set to true. All: false will lead to RudderStack not sending the event data to any destination.
<Destination>BooleanOptionalSpecific destination to which the event is to be sent or not sent, depending on the Boolean value assigned to it.

More information on using IntegrationOpts can be found in the Filtering selective destinations section.

QueueOpts

The structure of QueueOpts is shown below:

{
maxRetryDelay: 360000,
minRetryDelay: 1000,
backoffFactor: 2,
maxAttempts: 10,
maxItems: 100,
}

The following table describes each of the above parameters in detail:

ParameterTypeDescriptionDefault value
maxRetryDelayIntegerThe upper limit on the maximum delay for an event (in ms)360000
minRetryDelayIntegerThe minimum delay expected before sending an event (in ms)1000
backoffFactorIntegerRefers to the exponential base.2
maxAttemptsIntegerMaximum number of attempts to send the event to the destination.10
maxItemsIntegerMaximum number of events kept in the storage.100

cookieConsentManager

Once the 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
}
}
}
);
For more information on the consent managers supported by RudderStack, refer to this section.

Capturing anonymousId automatically

The JavaScript SDK provides anonymousIdOptions object in the load() call options. It automatically captures the anonymous ID from a source and sets it as Rudderstack’s anonymousId.

The structure of anonymousIdOptions object is shown below:

{
autoCapture: {
enabled: true,
source: "segment",
}
}
ParameterTypeDescription
enabledBooleanIdentifies if the auto-capturing of anonymous ID is enabled.
sourceStringIdentifies the external source of the anonymous ID.
If the RudderStack anonymousId is already set in your browser, then anonymousIdOptions will not take effect.
You can use the Reset method to generate a new anonymousId whether the anonymousIdOptions object is enabled or not. However, if the anonymousIdOptions object is enabled and you reset the anonymousId and then reload the page, Rudderstack anonymousId will be set as the provided source's anonymousId.

Adding callbacks to standard methods

RudderStack lets you define callbacks to the common methods of the rudderanalytics object.

This functionality is supported only for the syncPixel method which is called in the SDK when making synchronization calls for the relevant destinations.

An example is shown below:

<script>
rudderanalytics.syncPixelCallback = obj => {
rudderanalytics.track(
"sync lotame",
{
destination: obj.destination
},
{
integrations: {
All: false,
S3: true
}
}
);
};
</script>
<script src="https://cdn.rudderlabs.com/rudder-analytics.min.js"></script>

In the above example, RudderStack defines a syncPixelCallback on the rudderanalytics object loading the SDK. This will lead to RudderStack calling this registered callback with the parameter {destination: <destination_name>} whenever a sync call is made from the SDK to the relevant integrations, e.g. Lotame.

You can also add the callback in the options parameter as shown below:

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
clientSuppliedCallbacks: {
syncPixelCallback: () => {
console.log("sync done!");
},
},
});

We will be adding similar callbacks for other APIs such as track, page, identify, etc. very soon.

Filtering events

When sending events to a destination via the web device mode, you can explicitly specify which events should be discarded or allowed to flow through - by allowlisting or denylisting them.

Refer to the Client-side Event Filtering guide for more information on this feature.

Filtering selective destinations

RudderStack lets you load or send your event data to only the destinations specified by you. You can do so by passing an integrations object in the options parameter of the API methods. RudderStack then loads or sends events only to those destinations that are specified and enabled.

The format of the load method with the integration names passed as arguments is as shown:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
integrations: {
All: false,
destination_name: true
}
});

Here, <destination_name> is the name of the destination.

Examples

  • The format of the track method with the integration names passed as arguments is as shown below:
rudderanalytics.track(
"test track event GA3",
{
revenue: 30,
currency: "USD",
user_actual_id: 12345
},
{
integrations: {
All: false,
destination_name: true
}
}
);
  • The following example shows how to load only the Google Analytics and Intercom destinations:
rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
integrations: {
All: false,
"Google Analytics": true,
Intercom: true
}
});
  • The following example highlights how you can send the track type of events only to Google Analytics:
rudderanalytics.track(
"test track event GA3",
{
revenue: 30,
currency: "USD",
user_actual_id: 12345
},
{
integrations: {
All: false,
"Google Analytics": true
}
}
);

You can refer to the Common destination names for the naming conventions for the destinations.

Common destination names

The following table lists some of the popular destinations along with their supported names that RudderStack uses as values when sending the event data.

DestinationSupported Common Names
Google AnalyticsGoogle Analytics
GoogleAnalytics
GA
Google Analytics 4Google Analytics 4
GoogleAnalytics4
GA4
Google AdsGoogle Ads
GoogleAds
GOOGLEADS
BrazeBraze
BRAZE
ChartbeatChartbeat
CHARTBEAT
Customer.ioCustomer.io
CUSTOMERIO
Facebook PixelFB Pixel
Facebook Pixel
FB_PIXEL
Google Tag ManagerGoogle Tag Manager
GTM
HotjarHotjar
HOTJAR
HubspotHubspot
HUBSPOT
IntercomIntercom
INTERCOM
Keen.IOKeen
KEEN
Keen.io
KissmetricsKissmetrics
KISSMETRICS
LotameLotame
LOTAME
VWOVisual Website Optimizer
VWO
OptimizelyOPTIMIZELY
Optimizely
AmplitudeAmplitude
AMPLITUDE
MixpanelMixpanel
Facebook App EventsFacebook App Events
Amazon S3Amazon S3
MinIOMinIO
SalesforceSalesforce
AutopilotAutopilot
Heap.ioHeap.io
MailchimpMailChimp
RedshiftRedshift
BigQueryBigQuery
Google Cloud StorageGoogle Cloud Storage
Azure Blob StorageAzure Blob Storage
Branch MetricsBranch Metrics
KochavaKochava
LeanplumLeanplum
SlackSlack
ZendeskZendesk
AWS PersonalizeAWS Personalize
Amazon KinesisAmazon Kinesis
CleverTapCLEVERTAP
Clevertap
Adobe AnalyticsAdobe Analytics
AdobeAnalytics
ADOBE_ANALYTICS
adobeanalytics
DCM Floodlightdcm floodlight
dcm_floodlight
dcmfloodlight
DCM Floodlight
DCM_Floodlight
DCMFloodlight

Context and traits

RudderStack gives you the option to automatically capture certain event-specific and user-specific data, based on the type of the event.

In this section, we cover two specific dictionaries within the options parameter included in the supported API methods.

Context

A context is a dictionary of additional information about a particular event data, such as a user’s locale.

A context is a complete and specific piece of information. Any other information provided outside of this specification is ignored.

Traits

Traits is an optional dictionary included within context which specifies the user's unique traits. This is a very useful field for linking the user's information from a previously made identify() call to the subsequent track() or page() calls.

Use-case

To better understand how contexts and traits work, refer to the following identify event:

rudderanalytics.identify("userId", {
plan: "Paid, Premium",
email: "name@surname.org"
});

The trait in the above event is plan. If you wish to include this trait in a subsequent track() or page()event triggered by the user, you can establish the association by passing it in context.traits as shown:

rudderanalytics.track(
"Subscribed",
{
campaign: "Subscribe"
},
{
context: {
traits: {
plan: "Paid, Premium"
}
}
}
);

The above snippet will append plan as a trait to the track event. Note that the trait email will not be appended, as it was not specified in the context.traits field.

FAQs

Refer to the FAQs section for solutions to some of the commonly faced issues while using the JavaScript SDK on your website.

Contact us

For more information on any of the sections covered in this guide, you can contact us or start a conversation in our Slack community.

If you come across any issues while using this SDK, feel free to submit them on our GitHub issues page.