JavaScript
Detailed technical documentation on the RudderStack’s JavaScript SDK to send data from your website to your specified destinations.
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.
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:
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:
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.
To get the source write key, follow this guide.
To get the data plane URL, follow this guide.
The options
parameter
options
parameterThe options
parameter in the above load
call looks like the following:
It includes the following details:
Parameter | Type | Description |
---|---|---|
| String | Options include |
| Refer to the | |
| String | Defaults to |
| Refer to the | |
| Boolean | Defaults to |
| Boolean | Defaults to |
| String | Defaults to |
| Boolean | Defaults to |
| Refer to the BeaconQueueOpts section. | |
| Object | Refer to the |
| Object | Refer to the Capturing |
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:
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:
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:
The identify
method has the following parameters:
Parameter | Type | Presence | Description |
---|---|---|---|
| String | Optional | This 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 |
| Dictionary | Optional | This dictionary contains the traits or properties associated with a |
| Dictionary | Optional | This dictionary provides information such as context, integrations, and |
| Function | Optional | This function gets executed after successful execution of the |
A sample identify
call is shown below:
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
anonymousId
in the options
parameterThere 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:
Overriding the anonymousId
using setAnonymousId
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:
Using AMP Analytics
You can also parse the AMP Linker ID and set the anonymousId
, as shown:
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
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
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
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:
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:
The page
method has the following parameters:
Parameter | Type | Presence | Description |
| String | Optional | Defines the page category. |
| String | Optional | Defines the name of the page. |
| Dictionary | Optional | Defines the properties of the page. These properties are auto-captured by the SDK. |
| Dictionary | Optional | Provides information such as context, integrations, |
| Function | Optional | Called after the successful execution of the |
A sample page()
call is shown below:
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:
The track
method has the following parameters:
Parameter | Type | Presence | Description |
| String | Required | Captures the name of the tracked event. |
| Dictionary | Optional | Tracks the event properties. |
| Dictionary | Optional | Tracks the information like the context, integrations, etc. Specific user traits can also be provided as the context. Refer to the |
| Function | Optional | Called after the successful execution of the |
A sample track
call is as shown:
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:
The alias
call has the following parameters:
Parameter | Type | Presence | Description |
| String | Required | Denotes the new identifier of the user. |
| String | Optional | Denotes the old identifier which will be an alias for the |
| Dictionary | Optional | A dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the |
| Function | Optional | This function gets executed after the successful execution of the |
A sample alias()
method is shown below:
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:
The group
method has the following parameters:
Parameter | Type | Presence | Description |
| String | 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. |
| Dictionary | Optional | Denotes the group traits. RudderStack will pass these traits to the destination to enhance the group properties. |
| Dictionary | Optional | A dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the |
| Function | Optional | Gets executed after the successful execution of the |
A sample group()
call is as shown:
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:
You can also reset the anonymousId
along with the details mentioned above by passing true
to the reset()
method, as shown:
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
options
The structure of options
parameter is as shown:
The following table describes each of the above parameters in detail:
Parameter | Type | Description |
| Refer to the | |
| String | Overrides the current event's |
| ISO 8601 Date string | Overrides the current event's |
| - | Merged with the event's contextual information. |
IntegrationOpts
IntegrationOpts
The structure of IntegrationOpts
looks like the following:
The following table describes each of the above parameters in detail:
Parameter | Type | Presence | Description |
| Boolean | Optional | Corresponds to all the destinations to which the event is to be sent. The default value is set to |
| Boolean | Optional | Specific 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
QueueOpts
The structure of QueueOpts
is shown below:
The following table describes each of the above parameters in detail:
Parameter | Type | Description | Default value |
| Integer | The upper limit on the maximum delay for an event (in ms) | 360000 |
| Integer | The minimum delay expected before sending an event (in ms) | 1000 |
| Integer | Refers to the exponential base. | 2 |
| Integer | Maximum number of attempts to send the event to the destination. | 10 |
| Integer | Maximum 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:
For more information on the consent managers supported by RudderStack, refer to this section.
Capturing anonymousId
automatically
anonymousId
automaticallyThe 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:
Parameter | Type | Description |
---|---|---|
| Boolean | Identifies if the auto-capturing of anonymous ID is enabled. |
| String | Identifies 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:
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:
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 whitelisting or blacklisting 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:
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:
The following example shows how to load only the Google Analytics and Intercom destinations:
The following example highlights how you can send the
track
type of events only to Google Analytics:
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.
Destination | Supported Common Names |
---|---|
Google Analytics |
|
| |
| |
Google Analytics 4 |
|
| |
| |
Google Ads |
|
| |
| |
Braze |
|
| |
Chartbeat |
|
| |
Customer.io |
|
| |
Facebook Pixel |
|
| |
| |
Google Tag Manager |
|
| |
Hotjar |
|
| |
Hubspot |
|
| |
Intercom |
|
| |
Keen.IO |
|
| |
| |
Kissmetrics |
|
| |
Lotame |
|
| |
VWO |
|
| |
Optimizely |
|
| |
Amplitude |
|
| |
Mixpanel |
|
Facebook App Events |
|
Amazon S3 |
|
MinIO |
|
Salesforce |
|
Autopilot |
|
Heap.io |
|
Mailchimp |
|
Redshift |
|
BigQuery |
|
Google Cloud Storage |
|
Azure Blob Storage |
|
Branch Metrics |
|
Kochava |
|
Leanplum |
|
Slack |
|
Zendesk |
|
AWS Personalize |
|
Amazon Kinesis |
|
CleverTap |
|
| |
Adobe Analytics |
|
| |
| |
| |
DCM Floodlight |
|
| |
| |
| |
| |
|
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:
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:
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.
Last updated