| description | Detailed technical documentation on the RudderStack’s JavaScript SDK to send data from your website to your destinations via RudderStack |
|---|
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.
{% hint style="info" %} NOTE: To quickly get up and running with setting up and using the RudderStack JavaScript SDK, please go through our quick start guide. {% endhint %}
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.
<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>{% hint style="info" %} You can find your source write key and the data plane URL on your RudderStack dashboard. {% endhint %}
<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_URL);
//For example,
//rudderanalytics.load("1Qb1F3jSWv0eKFBPZcrM7ypgjVo", "http://localhost:8080");
rudderanalytics.page();
</script>
<script src="https://cdn.rudderlabs.com/v1/rudder-analytics.min.js"></script>{% hint style="success" %}
NOTE: The above code snippet will load rudder-analytics.js on to your page synchronously. To load the 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>
{% endhint %}
// 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, DATA_PLANE_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 aspath,referrer,search,title, andURL. If you want to override them, use the call mentioned in the section JavaScript SDK APIs.
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 RudderStack directly into your project.
To install, run the following command:
npm install rudder-sdk-js --save{% hint style="info" %} 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. {% endhint %}
{% hint style="warning" %} 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. {% endhint %}
import * as rudderanalytics from "rudder-sdk-js"
rudderanalytics.ready(() => {console.log("we are all set!!!")})
rudderanalytics.load(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(WRITE_KEY, DATA_PLANE_URL)
exports.rudderanalytics = rudderanalyticsPlease refer to the following projects for a detailed walk-through of the above steps:
{% hint style="info" %} The related APIs exported by the module are:
loadreadyidentifyaliaspagetrackgroupresetgetAnonymousIdsetAnonymousId{% endhint %}
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:
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);
{% hint style="info" %}
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.
{% endhint %}
The options parameter in the above load call includes one of the following arguments:
If you are self-hosting the Control Plane, your load call will look like the following:
rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {configUrl: CONTROL_PLANE_URL});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(WRITE_KEY, DATA_PLANE_URL, {
integrations: { All: false, destination_name: true },
});For more information, please check the How to Filter Selective Destinations section.
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(
"userId",
{ email: "name@domain.com" },
{
page: {
path: "",
referrer: "",
search: "",
title: "",
url: "",
}
},
() => {
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. |
{% hint style="info" %}
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.
{% endhint %}
{% hint style="success" %}
There is no need to callidentify()for anonymous visitors to your website. Such visitors are automatically assigned an anonymousId
{% endhint %}
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.
{% hint style="info" %} 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. {% endhint %}
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:
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.
{% hint style="info" %}
All other events will haveanonymousId from the one persisted in the cookie, except this event where you override the options.
{% endhint %}
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");
}
);jsYou 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("userId", { email1: "name@domain.com" }, () => {
console.log("in identify call");
});To identify new users in scenarios like a new login, you can take one of the following approaches:
- Call the
identifyAPI with a newuserid. RudderStack will reset all cookies related to the user foruseridanduser-traitsand update them with the new values provided by you.
{% hint style="info" %}
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.
{% endhint %}
- Explicitly call
rudderanalytics.reset()and then callidentify. 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("userId",
{ email1: "name@domain.com" },
() => { console.log("in identify call"); }
);
rudderanalytics.identify("userId",
{ email2: "name@domain.com" },
() => { console.log("in identify call"); }
);
// both email1 and email2 with be sent in the identify payload
// for the second call.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: "",
},
() => {
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 |
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
},
() => {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 |
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.
{% hint style="success" %}
Simply put, the alias call associates the user with a new identification.
{% endhint %}
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");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",
});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();{% hint style="info" %}
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.
{% endhint %}
RudderStack allows you to send your event data only to a few intended destinations by filtering out 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,
},
}
);{% hint style="info" %}
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.
{% endhint %}
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.
{% hint style="success" %}
NOTE: Unless explicitly defined otherwise, 'All' is always set to true. This means that sending events to all destinations is enabled by default.
{% endhint %}
You can also choose to load selective destinations by modifying the load method to take a third argument. You can pass anintegrationsdictionary containing the destination names in the format specified above. RudderStack loads only those destinations that are marked as enabled with the boolean value true .
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(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
integrationsdictionary containingGoogle AnalyticsandIntercomas the destination names
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.
A context is a dictionary of additional information about a particular data, such as a user’s IP address.
{% hint style="info" %} NOTE: A context is a complete and specific piece of information. Any other information provided outside of this specification is ignored. {% endhint %}
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("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 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.
RudderStack's Querystring API allows you to trigger track, identify calls using the query parameters.
You may use the below parameters as a query string 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 a query string, 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 query sting, the 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+LastnameThe following SDK calls will be triggered:
rudderanalytics.identify("userId", {name: "Firstname Lastname"});
rudderanalytics.track("test event", {testProp: "prop1"});
rudderanalytics.setAnonymousId("anonymousId");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(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.
{% hint style="info" %} Since most ad blockers block the request to the Google AdSense servers, this is assumed as a good measure to detect ad-blocked pages. {% endhint %}
sendAdblockPageOptions: The RudderStack SDK will make an implicitpagecall about the ad-blocked pages ifsendAdblockPageis set totrue. WithsendAdblockPageOptions, you can provide the destinations to which you want to forward thispagecall.
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",
});This section provides solutions to some of the commonly faced issues while using the RudderStack JavaScript SDK on your website.
Simply put, the Data Plane URL is used to connect to the RudderStack backend for processing and routing your events.
{% hint style="info" %} To get the Data Plane URL: ****
- If you're using the open-source version of RudderStack, you are required to set up your own data plane by installing and setting up RudderStack in your preferred dev environment.
- If you're using the enterprise version of RudderStack, please contact us for the data plane URL with the email ID used to sign up for RudderStack. {% endhint %}
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) orCommand+Option+I(Mac) and go to theConsoletab - Chrome:
Ctrl+Shift+J(Windows) orCommand+Option+J(Mac) - Firefox:
Ctrl+Shift+K(Windows) orCommand+Option+K(Mac) and select theConsoletab - Internet Explorer: Press
F12and go to theConsoletab
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.
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.
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.
To check if data is being transmitted to the specified destinations, go to the Network tab of your JavaScript console on your browser.
{% hint style="info" %} 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. {% endhint %}
The size limit on requests is 32 KB per message.
Yes, you can. Refer to the How to Filter Selective Destinations to Send Your Event Data section above to see how to do this.
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();{% hint style="info" %}
NOTE: In case the anonymousId value is null, calling the above function will lead to automatically setting a new anonymousId.
{% endhint %}
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 Slack channel.
In case you come across any issues while using this SDK, please feel free to submit them on our GitHub issues page.
