Version:

JavaScript SDK APIs

Send events by leveraging different JavaScript SDK APIs.

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.

info

The subsequent identify calls with the same userId deeply merge (values are merged recursively, exhausting the entire hierarchy tree) the new user traits with the previously persisted traits.

See Update user traits section for more information.

The identify method definition is as follows:

The following table describes the above parameters in detail:

ParameterType
Name
userIdStringThe unique user identifier. When provided, RudderStack prefers this over anonymousId while sending data to the destinations.
traitsDictionaryContains 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.
apiOptionsDictionaryOption to override integrations, anonymousId, and originalTimestamp fields. Any other keys are merged into the event’s context object.

See apiOptions section for more details.
callbackFunctionInvoked 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();
info
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.

info
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:
rudderanalytics.setAnonymousId(
  null,
  "<version>*<checkSum>*<idName1>*<idValue1>*<idName2>*<idValue2>..."
);

Here, the second parameter is the AMP Linker ID format in the specified structure. For websites using the RudderStack AMP Analytics SDK, the <idName1> value will be rs_amp_id.

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.
info
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).

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

info
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. See How SDK merges traits section for more information.

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, as shown:

{
  "userId": "1hKOmRA4GRlm",
  "email1": "alex@example.com",
  "email2": "john@example.com",
    "library": {
        "name": "http"
    },
  "timestamp": "2020-02-02T00:23:09.544Z"
}

How SDK merges traits

While updating user traits via the identify API, the SDK deeply merges (values are merged recursively, exhausting the entire hierarchy tree) the new user traits with the existing traits.

Note the following:

  • Missing properties: The SDK adds any properties present in one object but missing in the other to the resulting object.

  • Shared properties: If both the objects contain the same properties, then:

    • If both the properties are objects, then their contents are merged recursively.
    • If both the properties are arrays, then values from the right-side array will replace those in the left-side array at the same position. Note this could result in duplicate values in the array.
    • If the data types of the shared properties do not match, then the value from the right-side object will take precedence, overwriting the left-side value.

Reset user traits vs. update user traits

Calling the reset() API resets the existing user traits.

  • To reset a trait, set its new value to undefined. The resulting trait’s value will then be set to undefined.
  • To reset all the existing traits, set the traits argument to null or undefined.

On the other hand, call the identify() API with new traits to update the existing user traits, as shown:

rudderanalytics.identify("1hKOmRA4GRlm", {
  email: "alex@example.com"
}, () => {
  console.log("Identify event successfully submitted to the RudderStack SDK.");
});

rudderanalytics.identify({
  email: "alice@example.com"
}, () => {
  console.log("Identify event successfully submitted to the RudderStack SDK.");
});

In this case, the SDK updates the email field from alex@example.com to alice@example.com.

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.

The page method definition is as follows:

The following table describes the above (optional) parameters in detail:

ParameterTypeDescription
categoryStringCategory of the page.
nameStringName of the page.
propertiesDictionaryThe 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.
apiOptionsDictionaryProvides information such as integrations, anonymousId, and originalTimestamp. Reference.
callbackFunctionCalled 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.

The track method definition is as follows:

The following table describes the above parameters in detail:

ParameterTypeDescription
eventStringThe name of the tracked event.
propertiesDictionaryThe event-related properties.

Note: If you do not want to send the properties, pass an empty object ({}) instead.
apiOptionsDictionaryProvides information such as integrations, anonymousId, and originalTimestamp. Reference.
callbackFunctionCalled 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.

Refer to the Ecommerce Events Specification for more information on the ecommerce events captured by RudderStack.

Group

The group API lets you associate an identified user with a group such as a company, organization, or an account.

warning
RudderStack does not support associating a user to more than one group in a single group API call.

The group method definition is as follows:

The following table describes the above parameters in detail:

ParameterTypeDescription
groupIdStringThe unique group identifier in the database. RudderStack calls the relevant destination APIs to associate the identified user to this group.
traitsDictionaryThe 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.
apiOptionsDictionaryProvides information such as integrations, anonymousId, and originalTimestamp. Reference.
callbackFunctionCalled after the successful execution of the group call.

A sample group call is shown:

rudderanalytics.group("grp114412", {
  name: "Apple Inc.",
  location: "USA",
});

Update group traits

For updating the group traits, you can call group method with the same groupId multiple times along with the new traits. This appends or modifies all traits associated with that group. See How SDK merges group traits section for more information.

An example is shown below:

rudderanalytics.group("grp114412", {
  name1: "Group A"
}, () => {
    console.log("Group event successfully submitted to the RudderStack SDK.");
});

rudderanalytics.group("grp114412", {
    name2: "Group B"
}, () => {
    console.log("Group event successfully submitted to the RudderStack SDK.");
});

In the above example, both name1 and name2 will be sent in the payload for the second group call, as shown:

{
  "groupId": "grp114412",
  "name1": "Group A",
  "name2": "Group B",
    "library": {
        "name": "http"
    },
  "timestamp": "2020-02-02T00:23:09.544Z"
}

How SDK merges group traits

While updating group traits via the group API, the SDK deeply merges (values are merged recursively, exhausting the entire hierarchy tree) the new user traits with the existing traits.

Note the following:

  • Missing properties: The SDK adds any properties present in one object but missing in the other to the resulting object.

  • Shared properties: If both the objects contain the same properties, then:

    • If both the properties are objects, then their contents are merged recursively.
    • If both the properties are arrays, then values from the right-side array will replace those in the left-side array at the same position. Note this could result in duplicate values in the array.
    • If the data types of the shared properties do not match, then the value from the right-side object will take precedence, overwriting the left-side value.

Reset group traits vs. update group traits

Calling the reset() API resets the existing traits.

  • To reset a trait, set its new value to undefined. The resulting trait’s value will then be set to undefined.
  • To reset all the existing traits, set the traits argument to null or undefined.

On the other hand, call the group() API with new traits to update the existing group traits, as shown:

rudderanalytics.group("grp114412", {
  name: "Group A"
}, () => {
  console.log("Group event successfully submitted to the RudderStack SDK.");
});

rudderanalytics.group({
  name: "Group B"
}, () => {
  console.log("Group event successfully submitted to the RudderStack SDK.");
});

In this case, the SDK updates the name field from Group A to Group B.

Alias

The alias API lets you merge different identities of a known user.

The alias method definition is as follows:

The following table describes the above parameters in detail:

ParameterTypeDescription
toStringNew user identifier (userId) associated with the user.

Note: Subsequent events will still have the previous identifier as the userId field.
fromStringOld 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.
apiOptionsDictionaryProvides information such as integrations, anonymousId, and originalTimestamp. Reference.
callbackFunctionCalled 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.

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

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

warning
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: ISO 8601 date string,
  <other keys>: <value> // Additional keys merged with event's contextual information
}

The following table describes the above parameters in detail:

ParameterTypeDescription
integrationsIntegrationOptsSends event data only to the selective destinations.
anonymousIdStringOverrides the current event’s anonymousId at the top level.
originalTimestampISO 8601 Date stringOverrides the current event’s originalTimestamp at the top level. See Clock skew considerations for more information.
info

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.

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

You can listen to the RSA_Ready event as follows:

<script>
   document.addEventListener('RSA_Ready', function(e) {
     console.log('RSA_Ready', e.detail.analyticsInstance);
   })
</script>

While working with consent management, you can use the consent API to pass the end-user consent:

<script type = "text/javascript">
  // consent provider callback
  function ConsentManagerWrapper() { /// pseudo name
    if (window.isConsented()) { // pseudo name
      // pass the allowed and denied categoryIds
      rudderanalytics.consent({
        consentManagement: {
          allowedConsentIds: ['id1', 'id2'],
          deniedConsentIds: ['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.

ParameterAction
ajs_aidTriggers a rudderanalytics.setAnonymousId() call with anonymousId having the parameter value.
ajs_uidTriggers 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_eventTriggers 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:

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

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:

rudderanalytics.identify("1hKOmRA4el9Zt1WSfVJIVo4GRlm", {
  name: "Alex Keener",
  email: "alex@example.com",
  subscriptionStatus: "subscribed",
  plan: "Silver"
});

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:

rudderanalytics.track(
  "Subscription Update", {
    campaign: "Subscribe"
  }, {
    traits: {
      plan: "Gold",
      addOn: true
    }
  }
);

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.



Questions? Contact us by email or on Slack