Send events by leveraging different JavaScript SDK APIs.
14 minute read
The JavaScript SDK provides a comprehensive API that lets you track and send your event data to any destination.
Identify
The identify API lets you identify a user and associate them to their actions. It also lets you record any traits about them like their name, email, etc.
Once you make the identify call, the SDK persists the user information and passes it to the subsequent calls.
// Identify call with user ID, traits, and callback
rudderanalytics.identify(userId,[traits],[callback]);// Identify call with user ID and callback
rudderanalytics.identify(userId,[callback]);// Identify call with user traits, apiOptions, and callback
rudderanalytics.identify(traits,[apiOptions],[callback]);// Identify call with user traits and callback
rudderanalytics.identify(traits,[callback]);
The following table describes the above parameters in detail:
Parameter
Type
Name
userId
String
The unique user identifier. When provided, RudderStack prefers this over anonymousId while sending data to the destinations.
traits
Dictionary
Contains the user’s traits or the properties associated with userId such as email, address, etc. See Identify traits for more information.
Note that:
RudderStack stores the traits as context.traits in the final event object.
If you do not want to send the user traits, pass an empty object ({}) instead.
apiOptions
Dictionary
Option to override integrations, anonymousId, and originalTimestamp fields. Any other keys are merged into the event’s context object.
Invoked after successfully processing and queueing the event data for delivery. It does not indicate the actual delivery of the event but ensures that the SDK makes a delivery attempt.
A sample identify call is shown below:
rudderanalytics.identify("1hKOmRA4GRlm",{firstName:"Alex",lastName:"Keener",email:"alex@example.com",phone:"+1-202-555-0146"},{environment:"production"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});
In the above example, the JavaScript SDK captures the userId along with firstName, lastName, email, and phone as traits and environment as the contextual information along with other automatically-captured contextual fields.
Anonymous user ID
The anonymousId is an auto-generated UUID (Universally Unique Identifier) that gets assigned to each unique and unidentified visitor to your website.
Retrieve anonymous user ID
Run the following snippet to retrieve the anonymous ID of any visitor:
rudderanalytics.getAnonymousId();
The SDK always ensures that a valid anonymous user ID is returned by the getAnonymousId API. If required, it even auto-generates and sets a new value. For example, if the anonymousId is null and you call the getAnonymousId function, then the SDK automatically sets a new value for anonymousId.
How SDK uses anonymous user ID
The JavaScript SDK generates a unique anonymousId, stores it in the rl_anonymous_id cookie in the top-level domain by default, and attaches it to every subsequent event. This helps in sharing the identity of the anonymous users across the parent domain and all the sub-domain sites.
If you identify a user with your application’s unique identifier like email, database ID, etc., RudderStack stores this ID in the rl_user_id cookie and attaches it to every event.
Refer to the Data Storage guide for more information on how the JavaScript SDK stores persistent user data in cookies.
Override anonymous user ID
You can use any of the following three methods to override the anonymousId generated by the JavaScript SDK:
Set the anonymousId for all future events using the setAnonymousId() method. An example is shown below:
rudderanalytics.setAnonymousId("my-anonymous-id");// All event payloads will have the anonymousId key set "my-anonymous-id".
rudderanalytics.identify("1hKOmRA4el9Zt1WSfVJIVo4GRlm",{email1:"alex@example.com"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});
Parse the AMP Linker ID and set the anonymousId using AMP Analytics:
Calling the above method will parse the Linker ID and set the rs_amp_id key value as the anonymousId.
Provide anonymousId in the apiOptions parameter of the identify call.
Note that all other events will have the anonymousId persisted from the cookie except the particular event where you override the apiOptions parameter.
An example is shown below:
rudderanalytics.identify("1hKOmRA4el9Zt1WSfVJIVo4GRlm",{email:"alex@example.com"},{anonymousId:"my-anonymous-id"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});
Set a blank user ID
To set a blank user ID, you can pass an empty string as the userId parameter in the identify API call.
Note that setting an empty string as the userId only clears the user ID unlike the reset API (that also clears the persisted values, for example, user traits).
Do not set the userId value to null to reset its value in the SDK.
Use case
Suppose an anonymous user is identified with a userId and then logs out of their account. You can then call identify("", {isLoggedIn: false}) and the user will continue to be identified by their anonymousId for the future events.
Identify new users
You can use any of the below approaches to identify new users in scenarios like new logins:
Call identify with a new userId
Call reset followed by the identify
RudderStack resets all cookies related to the user (associated with the userId and traits) and updates them with the newly provided values.
The anonymousId remains unchanged in this case. It will be the auto-generated value set by the SDK or the one explicitly set using the setAnonymousId method.
Update user traits
For updating the user traits, you can call identify method with the same userId multiple times with the new traits. This will append or modify all traits associated with that user.
Calling the reset() method resets the existing user traits and calling identify() method with new traits updates the new user traits.
An example is shown below:
rudderanalytics.identify("1hKOmRA4GRlm",{email1:"alex@example.com"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});rudderanalytics.identify("1hKOmRA4GRlm",{email2:"john@example.com"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});
In the above example, both email1 and email2 will be sent in the payload for the second identify call.
You can also update the user traits by calling the identify method with the new traits object, as shown:
rudderanalytics.identify("1hKOmRA4GRlm",{email1:"alex@example.com"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});rudderanalytics.identify({email2:"john@example.com"},()=>{console.log("Identify event successfully submitted to the RudderStack SDK.");});
Page
The page API lets you record your website’s page views with any additional relevant information about the viewed page. Many destinations require the page call to be made at least once every page load.
// Page call with page category, name, properties, options, and callback
rudderanalytics.page(category,name,[properties],[apiOptions],[callback]);// Page call with page category, name, properties, and callback
rudderanalytics.page(category,name,[properties],[callback]);// Page call with page category, name, and callback
rudderanalytics.page(category,name,[callback]);// Page call with page name, properties, options, and callback
rudderanalytics.page(name,[properties],[apiOptions],[callback]);// Page call with page name, properties, and callback
rudderanalytics.page(name,[properties],[callback]);// Page call with page name and callback
rudderanalytics.page(name,[callback]);// Page call with page properties, options, and callback
rudderanalytics.page(properties,[apiOptions],[callback]);// Page call with page properties, and callback
rudderanalytics.page(properties,[callback]);// Page call with callback
rudderanalytics.page([callback]);
The following table describes the above (optional) parameters in detail:
Parameter
Type
Description
category
String
Category of the page.
name
String
Name of the page.
properties
Dictionary
The page properties. The SDK auto-captures the page path, url, referrer, search, and title fields if not explicitly provided in the page API.
Note: If you do not want to send the page properties, pass an empty object ({}) instead.
apiOptions
Dictionary
Provides information such as integrations, anonymousId, and originalTimestamp. Reference.
callback
Function
Called after the successful execution of page method.
A sample page call is shown below:
rudderanalytics.page("Cart","Cart Viewed",{environment:"production"},{integrations:{All:false,Amplitude:true}}()=>{console.log("Page event successfully submitted to the RudderStack SDK.");});
In the above example, the JavaScript SDK captures the page category and name along with the contextual information, and sends the event only to the Amplitude destination.
Track
The track API lets you capture user events along with the associated properties.
// Track call with event, properties, and callback
rudderanalytics.track(event,[properties],[callback]);// Track call with event and callback
rudderanalytics.track(event,[callback]);
The following table describes the above parameters in detail:
Parameter
Type
Description
event
String
The name of the tracked event.
properties
Dictionary
The event-related properties.
Note: If you do not want to send the properties, pass an empty object ({}) instead.
apiOptions
Dictionary
Provides information such as integrations, anonymousId, and originalTimestamp. Reference.
callback
Function
Called after the successful execution of the track call.
A sample track call is shown below:
rudderanalytics.track("Order Completed",{revenue:30,currency:"USD",user_actual_id:12345},()=>{console.log("Track event successfully submitted to the RudderStack SDK.");});
In the above example, the track method tracks the Order Completed event along with other information like revenue, currency, and the user_actual_id.
// Group call with group ID, traits, and callback
rudderanalytics.group(groupId,[traits],[callback]);// Group call with group ID and callback
rudderanalytics.group(groupId,[callback]);// Group call with traits, apiOptions, and callback
rudderanalytics.group(traits,[apiOptions],[callback]);// Group call with traits and callback
rudderanalytics.group(traits,[callback]);
The following table describes the above parameters in detail:
Parameter
Type
Description
groupId
String
The unique group identifier in the database. RudderStack calls the relevant destination APIs to associate the identified user to this group.
traits
Dictionary
The group-related traits. RudderStack passes these traits to the destination to enhance the group properties.
Note that:
RudderStack stores the group traits at the root level as traits object in the final event object.
If you do not want to send the group traits, pass an empty object ({}) instead.
apiOptions
Dictionary
Provides information such as integrations, anonymousId, and originalTimestamp. Reference.
callback
Function
Called after the successful execution of the group call.
// Alias call with new and old user identifier and callback
rudderanalytics.alias(to,[from],[callback]);// Alias call with new user identifier, apiOptions, and callback
rudderanalytics.alias(to,[apiOptions],[callback]);// Alias call with new user identifier and callback
rudderanalytics.alias(to,[callback]);
The following table describes the above parameters in detail:
Parameter
Type
Description
to
String
New user identifier (userId) associated with the user.
Note: Subsequent events will still have the previous identifier as the userId field.
from
String
Old user identifier which will be an alias for the to parameter. If not provided, the SDK populates this as the currently identified userId, or anonymousId in case of anonymous users.
apiOptions
Dictionary
Provides information such as integrations, anonymousId, and originalTimestamp. Reference.
callback
Function
Called after the successful execution of the alias call.
A sample alias call is shown below:
rudderanalytics.alias("new_id","old_id",()=>{console.log("Alias event successfully submitted to the RudderStack SDK.");});
Reset
The reset API lets you clear the ID, anonymous ID, and traits of both the user and the group.
If you have enabled session tracking, calling the reset method clears the current sessionId and generates a new one.
You can use the reset method as shown:
rudderanalytics.reset([resetAnonymousId]);
Set the resetAnonymousId flag to true to reset the anonymous user ID.
The reset API only clears the user data persisted by RudderStack. It does not clear the data stored by the integrated destinations.
apiOptions parameter
You can use the apiOptions parameter to override specific event-level properties and include any additional contextual information.
The SDK does not carry forward any of the information contained in apiOptions to the other events.
The structure of the apiOptions parameter is shown:
{integrations:IntegrationOpts,anonymousId:string,originalTimestamp:ISO8601datestring,<otherkeys>:<value>// Additional keys merged with event's contextual information
}
The following table describes the above parameters in detail:
Overrides the current event’s anonymousId at the top level.
originalTimestamp
ISO 8601 Date string
Overrides the current event’s originalTimestamp at the top level. See Clock skew considerations for more information.
Note that:
The SDK merges any fields other than the ones mentioned above into the event’s context object.
If you specify the IP address in the event’s apiOptions, RudderStack uses that instead of automatically capturing it in the backend. You can use this feature to anonymize your users’ IP addresses.
Ready
The JavaScript SDK exposes a ready API with a callback parameter that fires when the SDK has initialized itself and the other third-party destination SDKs.
You can use this API in cases where you want to tap into the features provided by the end-destination SDKs to enhance user tracking and other functionalities.
rudderanalytics.ready(()=>{console.log('The JavaScript SDK is ready.');});
RSA_Ready event
The JavaScript SDK also supports the RSA_Ready event as an alternative to the ready API to ensure that the SDK is ready. It provides a reference to the analytics instance (analyticsInstance) to invoke any API method and can be used for orchestration with the JavaScript frameworks and libraries.
The RSA_Ready event is useful in cases where the relevant business logic is in functions that cannot be declared alongside the analytics integration or they need to be declared on a decoupled code base.
While working with consent management, you can use the consent API to pass the end-user consent:
<scripttype="text/javascript">// consent provider callback
functionConsentManagerWrapper(){/// pseudo name
if(window.isConsented()){// pseudo name
// pass the allowed and denied categoryIds
rudderanalytics.consent({consentManagement:{allowedConsentIds:['id1','id2'],deninedConsentIds:['id3']}});}}</script>
Query string API
RudderStack’s Query string API lets you trigger the track, identify and setAnonymousId calls using the query parameters (listed below) within the URL.
You can use this API to achieve the following use cases:
Track actions that redirect users to a new web page.
Implement consistent identity tracking for users (known and anonymous) across multiple top-level domains.
Note that the JavaScript SDK executes these calls immediately upon loading, making them the first set of events processed by the SDK even if there are any buffered calls on the web page.
Parameter
Action
ajs_aid
Triggers a rudderanalytics.setAnonymousId() call with anonymousId having the parameter value.
ajs_uid
Triggers a rudderanalytics.identify() call with userId having the parameter value.
ajs_trait_<trait>
If ajs_uid is provided as a query string, the value of this parameter populates the traits of the identify call.
ajs_event
Triggers a rudderanalytics.track() call with event name as the parameter value.
ajs_prop_<property>
If ajs_event is passed as a query string, the value of this parameter populates the properties of the corresponding event in the track call.
For example, consider the following URL containing the query string parameters:
It will trigger the following API calls (in order):
// Sets the user ID/anonymous ID
rudderanalytics.setAnonymousId("abcde");// Identify call
rudderanalytics.identify("12345",{name:"Firstname Lastname"});// Track call
rudderanalytics.track("test event",{testProp:"prop1"});
Context and traits
Context
The context object in the event payload is a dictionary of additional information about a particular event. It contains:
Event or user-specific data provided through the API as apiOptions
Data automatically captured by the JavaScript SDK.
See Contextual fields for the complete list of auto-captured data. The SDK merges the apiOptions data with these auto-captured contextual fields and makes them available in the event payload.
Traits
The traits object is an optional dictionary included within context specifying 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 calls, for example, track or page.
Use case
To understand the concept of context and traits better, see the following identify event:
The traits in the above event are name, email, subscriptionStatus, and plan. If you wish to add or override any traits in the subsequent track or page event triggered by the user, you can do so by passing it in the traits object as apiOptions as shown:
The above snippet will add a new trait addOn and update the user trait plan to Gold for the track event. Note that the subsequent events will still have the old traits.
This site uses cookies to improve your experience while you navigate through the website. Out of
these
cookies, the cookies that are categorized as necessary are stored on your browser as they are as
essential
for the working of basic functionalities of the website. We also use third-party cookies that
help
us
analyze and understand how you use this website. These cookies will be stored in your browser
only
with
your
consent. You also have the option to opt-out of these cookies. But opting out of some of these
cookies
may
have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This
category only includes cookies that ensures basic functionalities and security
features of the website. These cookies do not store any personal information.
This site uses cookies to improve your experience. If you want to
learn more about cookies and why we use them, visit our cookie
policy. We'll assume you're ok with this, but you can opt-out if you wish Cookie Settings.