RudderStack JavaScript SDK

Detailed technical documentation on the RudderStack’s JavaScript SDK to send data from your website to the destinations, through RudderStack

1. What is the RudderStack JavaScript SDK?

The RudderStack JavaScript SDK allows you to utilize our rudder-analytics.js library to start sending data from your website to RudderStack. After integrating this SDK, you will also be able to connect to multiple destinations such as Amplitude, Google Analytics, and more, to send your event data.

2. Installing the RudderStack JavaScript SDK

NOTE: To quickly get up and running with setting up and using the RudderStack JavaScript SDK, please go through our quick start guide.

To integrate the RudderStack JavaScript SDK with your website, place either the minified or non-minified version of the code snippet in the <head> section of your website.

2.1. Minified Code

<script>
rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}rudderanalytics.load(<YOUR_WRITE_KEY>,<DATA_PLANE_URL>),rudderanalytics.page();
</script>
<script src="https://cdn.rudderlabs.com/rudder-analytics.min.js"></script>

2.2. Non-minified Code

<script>
rudderanalytics = window.rudderanalytics = [];
var methods = [
"load",
"page",
"track",
"identify",
"alias",
"group",
"ready",
"reset",
"getAnonymousId",
"setAnonymousId"
];
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
rudderanalytics[method] = function (methodName) {
return function () {
rudderanalytics.push([methodName].concat(Array.prototype.slice.call(arguments)));
};
}(method);
}
rudderanalytics.load("YOUR_WRITE_KEY", "DATA_PLANE_URI");
//For example,
//rudderanalytics.load("1Qb1F3jSWv0eKFBPZcrM7ypgjVo", "http://localhost:8080");
rudderanalytics.page();
</script>
<script src="https://cdn.rudderlabs.com/v1/rudder-analytics.min.js"></script>

NOTE: The above code snippet will load rudder-analytics.js on to your page synchronously. To load Rudder SDK asynchronously to keep your page load time unaffected use the following instead: <script async src="https://cdn.rudderlabs.com/rudder-analytics.min.js"></script>

Combining the initialization and the above async script together
<script type="text/javascript">
!function(){var e=window.rudderanalytics=window.rudderanalytics||[];e.methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],e.factory=function(t){return function(){var r=Array.prototype.slice.call(arguments);return r.unshift(t),e.push(r),e}};for(var t=0;t<e.methods.length;t++){var r=e.methods[t];e[r]=e.factory(r)}e.loadJS=function(e,t){var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.rudderlabs.com/v1/rudder-analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a)},e.loadJS(),
e.load("WRITE_KEY","RUDDER_SERVER_URL"), e.page()}();
</script>

The above code snippet does the following:

  • Creates an array to store the events until the analytics object is ready.

  • Stores a list of methods to replay them when the analytics object is ready. These methods include:

Method

Description

load()

Loads rudderanalytics.js with your write key

page()

Records page views whenever a user visits a page

track()

Keeps track of user actions and important events

identify()

Associates users and their traits or actions

reset()

Resets the userid and the associated traits

  • Loads the analytics object with your write key.

  • Makes the page()call to track the page view. It auto-captures properties such as path, referrer, search, title, and URL. If you want to override them, use the call mentioned in the section JavaScript SDK APIs.

2.3. Alternative Installation

Although we recommend using the minified or non-minified snippet as mentioned above to use RudderStack SDK with your website, you can also use this NPM module to package Rudder directly into your project.

To install, run the following command:

npm install rudder-sdk-js --save

This NPM module is only meant to be used for a browser installation. If you want to integrate RudderStack with your Node.js applications, please refer to the RudderStack Node.js repository.

Important: Since the module exports the related APIs on an already-defined object combined with the Node.js module caching, you should run the below code snippet only once and use the exported object throughout your project.

import * as rudderanalytics from "rudder-sdk-js"
rudderanalytics.ready(() => {console.log("we are all set!!!")})
rudderanalytics.load(<YOUR_WRITE_KEY>,<DATA_PLANE_URL>)
export { rudderanalytics }

You can also do so with ES5, using the require method, as shown:

var rudderanalytics = require("rudder-sdk-js")
rudderanalytics.load(<YOUR_WRITE_KEY>,<DATA_PLANE_URL>)
exports.rudderanalytics = rudderanalytics

Please refer to the following projects for a detailed walk-through of the above steps:

The related APIs exported by the module are:

  • load

  • ready

  • identify

  • alias

  • page

  • track

  • group

  • reset

  • getAnonymousId

  • setAnonymousId

3. JavaScript SDK APIs

RudderStack’s JavaScript SDK makes it very easy for you to send your event data to any destination without having to implement a new API every single time.

Let us take a look at some of the key methods in this section:

3.1. Load

The load() method loads the rudderanalytics.js file with your write key.

The load()method is defined as follows:

rudderanalytics.load(<YOUR_WRITE_KEY>, <DATA_PLANE_URL>, options);

NOTE: You need to replace <YOUR_WRITE_KEY> with the write key in the RudderStack Control Plane and <DATA_PLANE_URL> with the URL of the RudderStack Server.

The options parameter in the above load call includes one of the following arguments:

3.1.1. Autotracking

This feature allows you to auto-track your user interactions with a web app. Get more information on RudderStack's Autotrack feature here.

A sample load call with the autotrack argument is as shown:

rudderanalytics.load(<YOUR_WRITE_KEY>,<DATA_PLANE_URL>, {useAutoTracking: true});

3.1.2. Self-hosted Config Plane

If you are self-hosting the Config Plane, your load call will look like the following:

rudderanalytics.load(<YOUR_WRITE_KEY>,<DATA_PLANE_URL>, {configUrl: <CONFIG_PLANE_URL>});

3.1.3. Selective Destinations

RudderStack allows you to load selective destinations as specified by you and disable sending events to the remaining destinations. You can specify these destinations through the load call, as shown:

rudderanalytics.load(
<YOUR_WRITE_KEY>,<DATA_PLANE_URL>,
{
integrations: { All: false, <destination name>: true}
}
);

For more information, please check the How to Filter Selective Destinations section.

3.2. Identify

This method allows you to link the users and their actions to a specific userid.

The identify() method definition is as follows:

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

A sample example of how to use the identify() method is as shown:

rudderanalytics.identify(
"12345",
{ email: "name@domain.com" },
{
context: {
ip: "0.0.0.0"
},
page: {
path: "",
referrer: "",
search: "",
title: "",
url: ""
},
anonymousId: "12345"
},
() => {console.log("in identify call");}
);

In the above example, information such as the userid and email along with contextual information such as IP address, etc. is captured.

The above identify call has the following parameters:

Parameter

Description

userid

This string defines the database ID of the user. If provided, this optional argument will be sent to destinations as the user ID instead of an anonymous ID

traits

This optional dictionary contains the traits or properties associated with a userid such as email, address, etc.

options

This dictionary is also optional, and provides information such as context, integrations, and anonymousId. Specific user traits can be provided as the context as well

callback

This function gets executed after successful execution of the identify() method.

NOTE: The anonymousId is a UUID (Universally Unique Identifier) generated to uniquely identify the user. Also, if it is provided by the user using the setAnonymousId method, the user-specified anonymousId overrides the SDK-generated one.

There is no need to callidentify()for anonymous visitors to your website. Such visitors are automatically assigned an anonymousId

3.2.1. identify Options

The JavaScript SDK generates one unique anonymousId , stores it in a cookie named rl_anonymous_id , and attaches to every subsequent event. This helps in identifying the users from other sites that hosted under a sub-domain.

As an 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.

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.

There are two options that you can use to identify users when using the JavaScript SDK:

3.2.2. Overriding anonymousID in the options parameter

There can be scenarios where you may want to provide your own anonymousID instead of an auto-generated ID by the SDK. 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.

All other events will haveanonymousId 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");}
);

3.2.3. Overriding the anonymousID for all future events using setAnonymousId

You can also override the anonymousID for all the future events using the rudderAnanlytics.setAnonymousId method.

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

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

3.2.4. Identifying New Users

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

  • Call the identify API with a new userid. RudderStack will reset all cookies related to the user for userid and user-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 call rudderanalytics.reset() and then call identify. It has the same effect as described above.

For updating the traits of a user, you can call identify with the same userid multiple times with new traits. All the traits for that user keep on getting appended/modified.

Calling reset() or identifying with a new userId with new traits will reset the earlier traits and update them with the new values, as shown:

rudderanalytics.identify(
"12345",
{ email1: "name@domain.com" },
() => {
console.log("in identify call");
}
);
rudderanalytics.identify(
"12345",
{ email2: "name@domain.com" }
() => {
console.log("in identify call");
}
);
// both email1 and email2 with be sent in the identify payload
// for the second call.

3.3. Page

This method lets you record information about the web page being viewed by the user. This includes page views, category, and other relevant information about the page.

The page() method definition is as follows:

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

A sample example of how to use the page() method is as shown:

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

In the above example, the page() method captures information such as the page category and page name. It also captures contextual information such as IP address and the ID of the user.

The above code snippet has the following parameters:

Parameter

Description

category

An optional string that defines the category of the page

name

An optional string that defines the name of the page

properties

An optional dictionary that defines the properties of the page. These properties are auto-captured by the page

options

An optional dictionary that provides information such as context, integrations, anonymousId, etc. Specific user traits can be provided as the context as well

callback

This function gets executed after successful execution of the page() method

3.4. Track

This method allows you to track any actions that your users might perform. Each of these actions is commonly referred to as an event.

The track()method definition is as follows:

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

A sample example of how to use the track() method is as shown:

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

In the above example, the method tracks the event test track event GA3, information such as the revenue, currently, user ID, and other contextual information such as IP address.

The above code snippet has the following parameters:

Parameter

Description

event

A string that captures the name of the event that is being tracked

properties

An optional dictionary that tracks the properties of the event

options

An optional dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well

callback

This function gets executed after successful execution of the track call

3.5. 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 the users in the future. The RudderStack alias API allows you to implement this functionality.

Simply put, the alias call associates the user with a new identification.

The format of an alias call is as shown:

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

The above alias call has the following parameters:

Parameter

Presence

Description

to

Required

Denotes the new identifier

from

Optional

Denotes 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.

options

Optional

This dictionary provides additional context to the event payload.

callback

Optional

This function gets executed after successful execution of the alias() method.

A sample example of how to use the alias() method is as shown:

rudderanalytics.alias("test_new_id");

3.6. Group

The group call associates a user to a specific organization.

The format of a group call is as shown:

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

The above group call has the following parameters:

Parameter

Presence

Description

groupId

Required

Denotes 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.

traits

Optional

Denotes the traits of the group. RudderStack will pass these traits to the destination to enhance the group properties.

options

Optional

This dictionary provides additional context to the event payload.

callback

Optional

This function gets executed after successful execution of the group() method.

An example of how to use the group call is as shown below:

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

3.7. Reset

This method resets the userid and the associated traits and properties of that specific user.

The reset() method can be used as shown:

rudderanalytics.reset();

NOTE: The reset()method only clears the cookies and local storage set by RudderStack, and not the information stored by the integrated destinations. To completely clear the user session, please refer to the documentation provided by those respective tools.

4. How to Filter Selective Destinations to Send Event Data

RudderStack allows you to send your event data only to a few intended destinations by filtering out all the rest. You can do so by passing an integrations object in the options parameter of the identify(), page(), and track() methods.

The following is an example of how to send a sample message only to Google Analytics and Intercom:

rudderanalytics.identify('samplename', {
email: 'name@email.org',
name: 'Samplename',
}, {
integrations: {
'All': false,
'Google Analytics': true,
'Intercom': true
}
});

The line 'All': false instructs RudderStack not to send the event data to any destinations by default, unless they are explicitly listed as true in the subsequent lines.

You can also disable sending event data to certain destinations. In this case, the event data is sent to all the other destinations except the specified ones. An example of this is as shown:

rudderanalytics.identify('samplename', {
email: 'name@email.org',
name: 'Samplename',
}, {
integrations: {
'Google Analytics': false,
'Intercom': false
}
});

As seen in the above code snippet, RudderStack will send the event data to all the destinations except Google Analytics and Intercom.

NOTE: Unless explicitly defined otherwise, 'All' is always set to true. This means that sending events to all destinations is enabled by default.

4.1. Specifying Selective Destinations in the load Method

You can also choose to load selective destinations by modifying the load method to take a third argument. You can pass an integrations dictionary containing the destination names in the format specified above. RudderStack loads only those destinations that are marked as enabled with the boolean value true .

4.2. Common Destination Names

RudderStack supports the following destination names for sending the event data through the load method as described above:

Destination

Supported Common Names

Google Analytics

Google Analytics

GoogleAnalytics

GA

Google Ads

Google Ads

GoogleAds

GOOGLEADS

Braze

Braze

BRAZE

Chartbeat

Chartbeat

CHARTBEAT

Customer.io

Customer.io

CUSTOMERIO

Facebook Pixel

FB Pixel

Facebook Pixel

FB_PIXEL

Google Tag Manager

Google Tag Manager

GTM

Hotjar

Hotjar

HOTJAR

Hubspot

Hubspot

HUBSPOT

Intercom

Intercom

INTERCOM

Keen.IO

Keen

KEEN

Keen.io

Kissmetrics

Kissmetrics

KISSMETRICS

Lotame

Lotame

LOTAME

VWO

Visual Website Optimizer

VWO

Amplitude

Amplitude

Mixpanel

Mixpanel

Facebook App Events

Facebook App Events

Amazon S3

Amazon S3

MinIO

MinIO

Salesforce

Salesforce

Autopilot

Autopilot

Heap.io

Heap.io

Mailchimp

Mailchimp

Redshift

Redshift

BigQuery

BigQuery

Google Cloud Storage

Google Cloud Storage

Azure Blob Storage

Azure Blob Storage

Branch Metrics

Branch Metrics

Kochava

Kochava

Leanplum

Leanplum

Slack

Slack

Zendesk

Zendesk

AWS Personalize

AWS Personalize

Amazon Kinesis

Amazon Kinesis

A sample RudderStack load method with integration names passed as arguments will look like the following snippet:

rudderanalytics.load(
<YOUR_WRITE_KEY>,<DATA_PLANE_URL>,
{
integrations: { All: false, <destination name>: true}
}
);

Where <destination name> is the name of the destination as per the above list of common names.

An example of the load method is as shown:

rudderanalytics.load(
<YOUR_WRITE_KEY>,<DATA_PLANE_URL>,
{
integrations: { All: false, 'Google Analytics': true, 'Intercom': true }
}
);

As seen from the example above, three arguments are now passed in the load method:

  • writekey

  • <DATA_PLANE_URL>

  • The integrations dictionary containing Google Analytics and Intercom as the destination names

5. Contexts and Traits in RudderStack

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 argument, which is included in the identify(), page(), and track() methods.

5.1. Context

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

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

5.2. Trait

A trait is an optional dictionary included within context, which specifies the unique traits of the user. This is a very useful field for linking information of a user from a previously made identify() call to a track() or page() event.

In order to better understand how contexts and traits work, let us look at the following identify event:

rudderanalytics.identify('1234567890', {
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 that is triggered by the user, you can establish the association by passing this trait into context.traits as shown:

rudderanalytics.track('Subscribed', {
Campaign: 'Subscribe'
},
{
traits: {
plan: 'Paid, Premium'
}
}
);

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

6. Querystring API

RudderStack's Querystring API allows you to trigger track, identify calls using the query parameters.

You may use the below parameters as querystring parameters, and trigger the corresponding call.

Parameter

Action

ajs_uid

Makes a rudderanalytics.identify() call with userId having the parameter value.

ajs_aid

Makes a rudderanalytics.setAnonymousId() call with anonymousId having the parameter value.

ajs_event

Makes a rudderanalytics.track() call with event name as the parameter value.

ajs_prop_<property>

If ajs_event is passed as querystring, value of this parameter will populate the properties of the corresponding event in the track call.

ajs_trait_<trait>

If ajs_uid is provided as a querysting, value of this parameter will populate the traits of the identify call made.

As an example, if you pass the following parameters in the URL as shown:

http://hostname.com/?ajs_uid=12345&ajs_event=test%20event&ajs_aid=abcde&ajs_prop_testProp=prop1&ajs_trait_name=Firstname+Lastname

The following SDK calls will be triggered:

rudderanalytics.identify("12345", {name: "Firstname Lastname"});
rudderanalytics.track("test event", {testProp: "prop1"});
rudderanalytics.setAnonymousId("abcde");

7. Detecting Ad-blocked Pages

RudderStack's JavaScript SDK provides a way to send a page view containing relevant markers on whether a page is ad-blocked. You can analyze this data to find what percent of your site's page views are affected by ad-blockers.

To send an ad-blocked page view, load the SDK as follows:

rudderanalytics.load(
<YOUR_WRITE_KEY>,
<DATA_PLANE_URL>,
{
sendAdblockPage: true,
sendAdblockPageOptions: {integrations: {All: false, Amplitude: true}}
}
);

Some of the properties in the snippet above are:

  • sendAdblockPage: Enables the JavaScript SDK to make a call to load the Google AdSense library. If RudderStack fails to load this library, it concludes that an ad blocker is enabled on the page.

Since most ad blockers block the request to the Google AdSense servers, this is assumed as a good measure to detect ad-blocked pages.

  • sendAdblockPageOptions: The RudderStack SDK will make an implicit page call about the ad-blocked pages if sendAdblockPage is set to true. With sendAdblockPageOptions, you can provide the destinations to which you want to forward this page call.

The implicit page call semantics is as follows:

rudderanalytics.page("RudderJS-Initiated", "ad-block page request", {path: "/ad-blocked",
title: "error in script loading:: src:: http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js id:: ad-block"}),

8. Troubleshooting

This section provides solutions to some of the commonly faced issues while using the RudderStack JavaScript SDK on your website.

How to load analytics.js correctly?

In order to load analytics.js, simply copy the minified or non-minified version of the code snippet provided in the Installing the RudderStack JavaScript SDK section.

To check if it has loaded correctly, open 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

In the console, run rudderanalytics. If it returns an object as shown in the following code snippet, it means that the rudderanalytics.js file has loaded successfully:

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

If it gives you an undefined error, you might want to verify if the setting up procedure was correctly followed. Our Quick Start Guide may be able to help you get up and running.

Should I disable ad-blockers on my browser?

Yes, it is important that you ensure no ad-blockers are running on your browser, as they restrict therudderanalytics.js script from executing and storing user information in the browser.

Can I load multiple instances of rudderanalytics.js?

No, it is not possible to load multiple instances of rudderanalytics.js, as it is bound to exceed the maximum stack call size and give you an error.

How to check if the data is being transmitted to the desired destinations?

To check if data is being transmitted to the specified destinations, go to the Network tab of your JavaScript console on your browser.

page call as seen in the Network tab
track call as seen in the Network tab

NOTE: If the outbound request is not being shown, check if you have installed and set up the RudderStack JavaScript SDK correctly, or if ad-blockers are enabled on your browser.

What is the size limit on the requests?

The size limit on requests is 32 KB per message.

Can I send the event data to specific destinations only?

Yes, you can. Refer to the How to Filter Selective Destinations to Send Your Event Data section above to see how to do this.

What is an Anonymous ID and how to retrieve it?

An Anonymous ID is an auto-generated UUID (Universally Unique Identifier) that gets assigned to each unique visitor to your website.

To retrieve the anonymous ID of any visitor, simply call the following:

rudderanalytics.getAnonymousId();

NOTE: In case the anonymousId value is null, calling the above function will lead to automatically setting a new anonymousId.

Contact Us

To know more about the RudderStack JavaScript SDK or to see it in action, you can contact us or see the SDK in action. You can also talk to us on our Discord channel.

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