Getting Started with JavaScript SDK

Detailed technical documentation on RudderStack’s JavaScript SDK to send data from your website to the RudderStack platform, along with multiple other destinations

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, etc. in order to send your event data.

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

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.

Minified code

<script>
rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","reset"],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_URI"),rudderanalytics.page();
</script>
<script src="https://cdn.rudderlabs.com/rudder-analytics.min.js"></script>

Non-minified code

<script>
rudderanalytics = window.rudderanalytics = [];
var methods = [
"load",
"page",
"track",
"identify",
"reset"
];
for (var i=0; i<methods.length; i++) {
var method = methods[i];
rudderanalytics[method] = function(methodName) {
return function() {
rudderanalytics.push([methodName, ...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/rudder-analytics.min.js"></script>

NOTE: The above code snippet will load rudder-analytics.js on to your page asynchronously. This means that your page load speed will be unaffected.

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 user ID and the associated traits

  • Loads analytics object with your write key.

  • Makes the page()call to track the page view. It auto captures the 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

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.

load

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

The load()method is defined as follows:

rudderanalytics.load("YOUR_WRITE_KEY", "DATA_PLANE_URI");

NOTE: You need to replace YOUR_WRITE_KEY with the write key in the RudderStack Control Plane and DATA_PLANE_URI with the URI of the RudderStack Server/ Data Plane.

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

rudderanalytics.load(“1S2kNlbkMrWLBO79H2eNuEST27I”,"http://localhost:8080");

The above line of code loads the rudderanalytics.js file with the write key 1S2kNlbkMrWLBO79H2eNuEST27I and the Data Plane URI as http://localhost:8080.

identify

This method allows you to link users and their actions to a specific user id.

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 user ID, email along with contextual information such as IP address, etc. will be captured.

The above call has the following parameters:

Parameter

Description

userid

This string defines the database ID of the user. If provided, this optional argument will override the anonymousId. This argument is optional.

traits

This optional dictionary provides the user traits such as email, address,etc.

options

This dictionary is also optional, and 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 a successful execution of the identify() method

NOTE: There is no need to callidentify()for anonymous visitors to your website. Such visitors are automatically assigned an anonymousId. page This method lets you record information such as page views, and other relevant information about the page that is being viewed.

page

This method lets you record information such as page views, and other relevant information about the page being viewed by the user.

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, page name, and 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 a successful execution of the page() method

track

This method allows you to track any actions that your users might perform.

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 a successful execution of the track call.

NOTE: anonymousId is a UUID (Universally Unique Identifier) generated to identify the user. If provided by the user, it will override the generated one. reset This method resets the userId and the associated traits and properties of that specific user.

reset

This method resets the user ID 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.

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 Amplitude:

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

You can also disable certain destinations so that the event data is sent to all the other destinations except those. An example of this is as shown:

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

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

NOTE: Unless defined otherwise, 'All' is always set to true, meaning sending to all destinations is enabled by default.

Understanding Contexts 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 2 specific dictionaries, within the options argument, which is included in the identify(), page()and track() methods.

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.

Trait

A trait is an optional dictionary included within context, which specifies 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 a page() event.

In order to 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 the context.traits as shown below:

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.

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, type and enter rudderanalytics. If it returns an object like the following, it means that the rudderanalytics.js 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, please check it out.

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?

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 is null, calling the above function will lead to automatically setting a new anonymousId.

In case you come across any other issues, please feel free to submit them here. For any other support, please feel free to contact us.