LogoLogo
  • Contributing to RudderStack
  • Destination_Name
  • LICENSE
  • RudderStack Docs
  • docs
    • FAQ
    • Identity Resolution
    • Home
    • cloud-extract-sources
      • ActiveCampaign Source
      • Bing Ads
      • Chargebee
      • Common Settings
      • Facebook Ads
      • Freshdesk
      • Google Ads Source
      • Google Analytics
      • Google Search Console
      • Google Sheets
      • Cloud Extract Sources
      • Intercom v2
      • Intercom
      • Mailchimp
      • Marketo
      • Mixpanel
      • NetSuite
      • Pipedrive
      • QuickBooks
      • Salesforce Pardot
      • Sendgrid Source
      • Stripe Source
      • Xero
      • Zendesk Chat
      • Zendesk
      • hubspot
        • HubSpot Data Model and Schema Information
        • HubSpot
      • salesforce
        • Salesforce
        • Schema Comparison: RudderStack vs. Segment
    • connections
      • Connection Modes: Cloud Mode vs. Device Mode
    • data-governance
      • Data Governance
      • RudderTyper
      • Data Governance API
      • RudderTyper
      • tracking-plans
        • Tracking Plans
        • Tracking Plan Spreadsheet
    • data-warehouse-integrations
      • Amazon Redshift
      • Azure Data Lake
      • Azure Synapse
      • ClickHouse
      • Databricks Delta Lake
      • Google Cloud Storage Data Lake
      • Google BigQuery
      • Identity Resolution
      • Warehouse Destinations
      • Microsoft SQL Server
      • PostgreSQL
      • Amazon S3 Data Lake
      • Snowflake
      • FAQ
      • Warehouse Schema
    • destinations
      • Destinations
      • Webhooks
      • advertising
        • Bing Ads
        • Criteo
        • DCM Floodlight
        • Facebook App Events
        • Facebook Custom Audience
        • Facebook Pixel
        • Google Ads (gtag.js)
        • Google AdWords Enhanced Conversions
        • Google Adwords Remarketing Lists (Customer Match)
        • Advertising
        • LinkedIn Insight Tag
        • Lotame
        • Pinterest Tag
        • Reddit Pixel
        • Snap Pixel
        • TikTok Ads
      • analytics
        • Amplitude
        • AWS Personalize
        • Chartbeat
        • Firebase
        • FullStory
        • Google Analytics 360
        • Google Analytics
        • Heap.io
        • Hotjar
        • Analytics
        • Indicative
        • Keen
        • Kissmetrics
        • Kubit
        • Lytics
        • Mixpanel
        • Pendo
        • PostHog
        • Quantum Metric
        • Singular
        • adobe-analytics
          • Adobe Analytics Heartbeat Measurement
          • Mobile Device Mode Settings
          • Web Device Mode Settings
          • E-commerce Events
          • Adobe Analytics
          • Setting Up Adobe Analytics in RudderStack
        • google-analytics-4
          • Cloud Mode
          • Device Mode
          • Google Analytics 4
          • Setting up Google Analytics 4
        • profitwell
          • ProfitWell
          • Cloud Mode
          • Device Mode
      • attribution
        • Adjust
        • AppsFlyer
        • Branch
        • Attribution
        • Kochava
        • TVSquared
      • business-messaging
        • Business Messaging
        • Intercom
        • Kustomer
        • Slack
        • Trengo
      • continuous-integration
        • Visual Studio App Center
        • Continuous Integration
      • crm
        • Delighted
        • HubSpot
        • CRM
        • Salesforce
        • Variance
        • Zendesk
      • customer-data-platform
        • Customer Data Platform
        • Segment
      • error-reporting
        • Bugsnag
        • Error Reporting
        • Sentry
      • marketing
        • ActiveCampaign
        • AdRoll
        • Airship
        • Appcues
        • Autopilot
        • Blueshift
        • Braze
        • CleverTap
        • Customer.io
        • Gainsight PX
        • Gainsight
        • Marketing
        • Iterable
        • Klaviyo
        • Leanplum
        • Mailchimp
        • Marketo Lead Import
        • Marketo
        • MoEngage
        • Ometria
        • Pardot
        • Post Affiliate Pro
        • Qualtrics
        • SendGrid
        • Salesforce Marketing Cloud
        • Userlist
        • drip
          • Cloud Mode
          • Device Mode
          • Drip
          • Setting Up Drip in RudderStack
      • productivity
        • Google Sheets
        • Productivity
      • storage-platforms
        • Amazon S3
        • DigitalOcean Spaces
        • Google Cloud Storage
        • Storage Platforms
        • Azure Blob Storage
        • MinIO
        • Redis
      • streaming-platforms
        • Amazon EventBridge
        • Amazon Kinesis Firehose
        • Amazon Kinesis
        • Azure Event Hubs
        • BigQuery Stream
        • Confluent Cloud
        • Google Pub/Sub
        • Streaming Platforms
        • Apache Kafka
      • tag-managers
        • Google Tag Manager
        • Tag Managers
      • testing-and-personalization
        • Algolia Insights
        • Candu
        • Google Optimize
        • A/B Testing & Personalization
        • LaunchDarkly
        • Monetate
        • Optimizely Full Stack
        • Optimizely Web
        • Split.io
        • Statsig
        • VWO (Visual Website Optimizer)
    • get-started
      • RudderStack Cloud vs. RudderStack Open Source
      • Glossary
      • Get Started
      • RudderStack Architecture
    • reverse-etl
      • Amazon Redshift
      • Amazon S3
      • ClickHouse
      • FAQ
      • Google BigQuery
      • Reverse ETL
      • PostgreSQL
      • Snowflake
      • common-settings
        • Importing Data using Models
        • Importing Data using Tables
        • Common Settings
        • Sync Modes
        • Sync Schedule
      • features
        • Airflow Provider
        • Features
        • Models
        • Visual Data Mapper
    • rudderstack-api
      • Data Regulation API
      • HTTP API
      • RudderStack API
      • Personal Access Tokens
      • Pixel API
      • Test API
      • api-specification
        • Application Lifecycle Events Specification
        • API Specification
        • Video Events Specification
        • rudderstack-ecommerce-events-specification
          • Browsing
          • Coupons
          • E-Commerce Events Specification
          • Ordering
          • Promotions
          • Reviewing
          • Sharing
          • Wishlist
        • rudderstack-spec
          • Alias
          • Common Fields
          • Group
          • Identify
          • RudderStack Event Specification
          • Page
          • Screen
          • Track
    • rudderstack-cloud
      • Audit Logs
      • Dashboard Overview
      • Destinations
      • RudderStack Cloud
      • Live Events
      • Connection Modes: Cloud Mode vs. Device Mode
      • Sources
      • Teammates (User Management)
      • connections
        • Adding a Destination
        • Connections
    • rudderstack-open-source
      • Control Plane Setup
      • RudderStack Open Source
      • installing-and-setting-up-rudderstack
        • Developer Machine Setup
        • Docker
        • Data Plane Setup
        • Kubernetes
        • Sending Test Events
    • stream-sources
      • App Center
      • AppsFlyer
      • Auth0
      • Braze
      • Customer.io
      • Extole
      • Event Stream Sources
      • Iterable
      • Looker
      • PostHog
      • Segment
      • Shopify
      • Webhook Source
      • rudderstack-sdk-integration-guides
        • Client-side Event Filtering
        • SDKs
        • AMP Analytics
        • Cordova
        • .NET
        • Go
        • Java
        • Node.js
        • PHP
        • Python
        • React Native
        • Ruby
        • Rust
        • Unity
        • SDK FAQs
        • rudderstack-android-sdk
          • Adding Application Class
          • Flushing Events Periodically
          • Android
        • rudderstack-flutter-sdk
          • Flutter SDK v1
          • Flutter v2
          • Flutter
        • rudderstack-ios-sdk
          • iOS
          • tvOS
          • watchOS
        • rudderstack-javascript-sdk
          • Data Storage in Cookies
          • Detecting Ad-blocked Pages
          • JavaScript
          • JavaScript SDK Enhancements
          • JavaScript SDK FAQs
          • Querystring API
          • Quick Start Guide
          • Version Migration Guide
          • consent-managers
            • Consent Managers
            • OneTrust
    • transformations
      • Access Token
      • FAQ
      • Transformations
      • Transformations API
    • user-guides
      • User Guides
      • administrators-guide
        • Troubleshooting Guide
        • Alerting Guide
        • Bucket Configuration Settings for Event Backups
        • Configuration Parameters
        • Event Replay
        • High Availability
        • Horizontal Scaling
        • Administrator's Guides
        • Infrastructure Provisioning
        • Monitoring and Metrics
        • Okta SSO Setup
        • OneLogin SSO Setup
        • RudderStack Grafana Dashboard
        • Software Releases
      • how-to-guides
        • How to Use Custom Domains
        • How to Develop Integrations for RudderStack
        • How to Configure a Destination via the Event Payload
        • How to Filter Events using Different Methods
        • How to Filter Selective Destinations
        • How to Submit a Pull Request for a New Integration
        • How-to Guides
        • How to Debug Live Destination Events
        • How to Use AWS Lambda Functions with RudderStack
        • create-a-new-destination-transformer-for-rudder
          • Best Practices for Coding Transformation Functions in JavaScript
          • How to Create a New Destination Transformation for RudderStack
        • implement-native-js-sdk-integration
          • How to Add a Device Mode SDK to RudderStack JavaScript SDK
          • How to Implement a Native JavaScript SDK Integration
        • rudderstack-jamstack-integration
          • How to Integrate RudderStack with Your JAMstack Site
          • How to Integrate Rudderstack with Your Angular App
          • How to Integrate Rudderstack with Your Astro Site
          • How to Integrate Rudderstack with Your Eleventy Site
          • How to Integrate Rudderstack with Your Ember.js App
          • How to Integrate Rudderstack with a Gatsby Website
          • How to Integrate Rudderstack with a Hugo Site
          • How to Integrate Rudderstack with Your Jekyll Site
          • How to Integrate Rudderstack with Your Next.js App
          • How to Integrate Rudderstack with Your Nuxt.js App
          • How to Integrate Rudderstack with Your Svelte App
          • How to Integrate Rudderstack with Your Vue App
      • migration-guides
        • Migrating from Blendo to RudderStack
        • Migrating Your Warehouse Destination from Segment to RudderStack
        • Migration Guides
        • Migrating from Segment to RudderStack
  • src
    • @rocketseat
      • gatsby-theme-docs
        • text
          • Home
Powered by GitBook
On this page
  • Installing the SDK
  • Supported APIs
  • Load
  • Write key and data plane URL
  • The options parameter
  • Loading the SDK for self-hosted control plane
  • Loading selective destinations
  • Chromecast
  • Identify
  • anonymousId
  • Setting a blank userId
  • Identifying new users
  • Updating user traits
  • Page
  • Track
  • Alias
  • Group
  • Reset
  • Parameter definitions
  • options
  • IntegrationOpts
  • QueueOpts
  • Adding callbacks to standard methods
  • Filtering events
  • Filtering selective destinations
  • Examples
  • Common destination names
  • Context and traits
  • Context
  • Traits
  • FAQs
  • Contact us

Was this helpful?

  1. docs
  2. stream-sources
  3. rudderstack-sdk-integration-guides
  4. rudderstack-javascript-sdk

JavaScript

Detailed technical documentation on the RudderStack’s JavaScript SDK to send data from your website to your specified destinations.

PreviousDetecting Ad-blocked PagesNextJavaScript SDK Enhancements

Last updated 2 years ago

Was this helpful?

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 .

The JavaScript SDK stores persistent user data in the cookies. For more information on these cookies, refer to the 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 .

Installing the SDK

To quickly set up and start using the RudderStack JavaScript SDK, go through our .

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:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, [options]);

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.

The options parameter

The options parameter in the above load call looks like the following:

{
  logLevel: "DEBUG" | "INFO" | "WARN",
  integrations: IntegrationOpts,
  configUrl: string,  // defaults to https://api.rudderlabs.com
  queueOptions: QueueOpts,
  loadIntegration: boolean, // defaults to true.
  secureCookie: boolean, // defaults to false.
  destSDKBaseURL: string, // defaults to https://cdn.rudderlabs.com/v1.1/js-integrations
  useBeacon: boolean, // defaults to false.
  beaconQueueOptions: BeaconQueueOpts,
  cookieConsentManager: cookieConsentManager,
  anonymousIdOptions: AnonymousIdOptions
}

It includes the following details:

Parameter
Type
Description

logLevel

String

Options include DEBUG, INFO, and WARN.

integrations

configUrl

String

Defaults to https://api.rudderlabs.com. You need to provide the server (Control Plane) endpoint serving your destination configurations. Note that sourceConfig is automatically appended to this endpoint by the SDK.

queueOpts

loadIntegration

Boolean

Defaults to true. If set to false, the destination SDKs are not fetched by the SDK. This is supported for Amplitude and Google Analytics.

secureCookie

Boolean

Defaults to false. If set to true, the SDK sends the cookie to the storage backend via HTTPS.

destSDKBaseURL

String

useBeacon

Boolean

Defaults to false. If set to true, the SDK sends the event payloads via the navigator.sendBeacon() utility.

beaconQueueOptions

cookieConsentManager

Object

anonymousIdOptions

Object

The useBeacon option

Loading the SDK for self-hosted control plane

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
  configUrl: <CONTROL_PLANE_URL>,
});

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:

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
  integrations: { All: false, destination_name: true },
});

Chromecast

Identify

The SDK defines the identify method as shown below:

rudderanalytics.identify(userId, [traits], [options], [callback]);

The identify method has the following parameters:

Parameter
Type
Presence
Description

userId

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

traits

Dictionary

Optional

options

Dictionary

Optional

callback

Function

Optional

This function gets executed after successful execution of the identify() method.

A sample identify call is shown below:

rudderanalytics.identify(
  "userId",
  { email: "name@domain.com" },
  {
    page: {
      path: "",
      referrer: "",
      search: "",
      title: "",
      url: ""
    }
  },
  () => {
    console.log("Sample identify call");
  }
);

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.

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

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

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

rudderanalytics.identify(
  "12345",
  { email: "name@domain.com" },
  {
    anonymousId: "my-anonymous-id"
  },
  () => {
    console.log("in identify call");
  }
);

Overriding the 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:

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");
});

Using AMP Analytics

You can also parse the AMP Linker ID and set the anonymousId, as shown:

rudderanalytics.setAnonymousId(
  null,
  "<version>*<checkSum>*<idName1>*<idValue1>*<idName2>*<idValue2>..."
);

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

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

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

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:

rudderanalytics.identify("userId", { email1: "name@domain.com" }, () => {
  console.log("in identify call");
});

rudderanalytics.identify("userId", { email2: "name@domain.com" }, () => {
  console.log("in identify call");
});

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:

rudderanalytics.page(category, name, [properties], [options], [callback]);

The page method has the following parameters:

Parameter

Type

Presence

Description

category

String

Optional

Defines the page category.

name

String

Optional

Defines the name of the page.

properties

Dictionary

Optional

Defines the properties of the page. These properties are auto-captured by the SDK.

options

Dictionary

Optional

callback

Function

Optional

Called after the successful execution of the page() method.

A sample page() call is shown below:

rudderanalytics.page(
  "Cart",
  "Cart Viewed",
  {
    path: "",
    referrer: "",
    search: "",
    title: "",
    url: ""
  },
  () => {
    console.log("in page call");
  }
);

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:

rudderanalytics.track(event, [properties], [options], [callback]);

The track method has the following parameters:

Parameter

Type

Presence

Description

event

String

Required

Captures the name of the tracked event.

properties

Dictionary

Optional

Tracks the event properties.

options

Dictionary

Optional

callback

Function

Optional

Called after the successful execution of the track call.

A sample track call 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 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:

rudderanalytics.alias(to, from, [options], [callback]);

The alias call has the following parameters:

Parameter

Type

Presence

Description

to

String

Required

Denotes the new identifier of the user.

from

String

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

Dictionary

Optional

callback

Function

Optional

This function gets executed after the successful execution of the alias() method.

A sample alias() method is shown below:

rudderanalytics.alias("test_new_id", "old_user_id", () => {
  console.log("alias call");
});

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:

rudderanalytics.group(groupId, [traits], [options], [callback]);

The group method has the following parameters:

Parameter

Type

Presence

Description

groupId

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.

traits

Dictionary

Optional

Denotes the group traits. RudderStack will pass these traits to the destination to enhance the group properties.

options

Dictionary

Optional

callback

Function

Optional

Gets executed after the successful execution of the group() method.

A sample group() call is as shown:

rudderanalytics.group("sample_group_id", {
  name: "CompanyA",
  location: "USA",
});

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:

rudderanalytics.reset();

You can also reset the anonymousId along with the details mentioned above by passing true to the reset() method, as shown:

rudderanalytics.reset(true);

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

The structure of options parameter is as shown:

{
  integrations: IntegrationOpts,
  anonymousId: string,
  originalTimestamp: ISO 8601 date string,
  <other keys>: <value> // merged with event's contextual information
}

The following table describes each of the above parameters in detail:

Parameter

Type

Description

integrations

anonymousId

String

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.

<other keys>: <value>

-

Merged with the event's contextual information.

IntegrationOpts

The structure of IntegrationOpts looks like the following:

{
  All: boolean, // default true
  <Destination1>: boolean,
  <Destination2>: boolean,
  ...
}

The following table describes each of the above parameters in detail:

Parameter

Type

Presence

Description

All

Boolean

Optional

Corresponds to all the destinations to which the event is to be sent. The default value is set to true. All: false will lead to RudderStack not sending the event data to any destination.

<Destination>

Boolean

Optional

Specific destination to which the event is to be sent or not sent, depending on the Boolean value assigned to it.

QueueOpts

The structure of QueueOpts is shown below:

{
  maxRetryDelay: 360000,
  minRetryDelay: 1000,
  backoffFactor: 2,
  maxAttempts: 10,
  maxItems: 100,
}

The following table describes each of the above parameters in detail:

Parameter

Type

Description

Default value

maxRetryDelay

Integer

The upper limit on the maximum delay for an event (in ms)

360000

minRetryDelay

Integer

The minimum delay expected before sending an event (in ms)

1000

backoffFactor

Integer

Refers to the exponential base.

2

maxAttempts

Integer

Maximum number of attempts to send the event to the destination.

10

maxItems

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:

rudderanalytics.load(
  <WRITE_KEY>,
  <DATA_PLANE_URL>, {
    cookieConsentManager: {
      oneTrust: {
        enabled: true
      }
    }
  }
);

Capturing anonymousId automatically

The structure of anonymousIdOptions object is shown below:

{
  autoCapture: {
    enabled: true,
    source: "segment",
  }
}
Parameter
Type
Description

enabled

Boolean

Identifies if the auto-capturing of anonymous ID is enabled.

source

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:

<script>
rudderanalytics.syncPixelCallback = obj => {
  rudderanalytics.track(
    "sync lotame",
    {
      destination: obj.destination
    },
    {
      integrations: {
        All: false,
        S3: true
      }
    }
  );
};
</script>

<script src="https://cdn.rudderlabs.com/rudder-analytics.min.js"></script>

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:

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
  clientSuppliedCallbacks: {
    syncPixelCallback: () => {
      console.log("sync done!");
    },
  },
});

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.

Filtering selective destinations

The format of the load method with the integration names passed as arguments is as shown:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  integrations: {
    All: false,
    destination_name: true
  }
});

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:

rudderanalytics.track(
  "test track event GA3",
  {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345
  },
  {
    integrations: {
      All: false,
      destination_name: true
    }
  }
);
  • The following example shows how to load only the Google Analytics and Intercom destinations:

rudderanalytics.load(WRITE_KEY, DATA_PLANE_URL, {
  integrations: {
    All: false,
    "Google Analytics": true,
    Intercom: true
  }
});
  • The following example highlights how you can send the track type of events only to Google Analytics:

rudderanalytics.track(
  "test track event GA3",
  {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345
  },
  {
    integrations: {
      All: false,
      "Google Analytics": true
    }
  }
);

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

GoogleAnalytics

GA

Google Analytics 4

Google Analytics 4

GoogleAnalytics4

GA4

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

Optimizely

OPTIMIZELY

Optimizely

Amplitude

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

CleverTap

CLEVERTAP

Clevertap

Adobe Analytics

Adobe Analytics

AdobeAnalytics

ADOBE_ANALYTICS

adobeanalytics

DCM Floodlight

dcm floodlight

dcm_floodlight

dcmfloodlight

DCM Floodlight

DCM_Floodlight

DCMFloodlight

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.

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

Use-case

To better understand how contexts and traits work, refer to 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 triggered by the user, you can establish the association by passing it in context.traits as shown:

rudderanalytics.track(
  "Subscribed",
  {
    campaign: "Subscribe"
  },
  {
    context: {
      traits: {
        plan: "Paid, Premium"
      }
    }
  }
);

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

Contact us

To get the source write key, follow .

To get the data plane URL, follow .

Refer to the section. More information on how to use this parameter can be found .

Refer to the section.

Defaults to https://cdn.rudderlabs.com/v1.1/js-integrations. The SDK will load the integrations from this path. You can also set your own integrations path using this field. For more information, refer to .

Refer to the section.

Refer to the section for more information.

Refer to the section for more information.

For more details, refer to the parameter section.

The JavaScript SDK supports a new Boolean field, useBeacon, in the load() call options. When set to true, the SDK sends events using the utility.

Refer to for more details on using the Beacon transport mechanism.

If you are self-hosting the control plane using the utility, your load call will look like the following:

More information on how to get the CONTROL_PLANE_URL can be found .

For more information, check the section.

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 to build your web sender app. Then, add the JavaScript SDK to it.

Follow the for more details.

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 or calls.

To reset the user identification, you can use the method.

This dictionary contains the traits or properties associated with a userId such as email, address, etc. More information on the identify traits can be found .

This dictionary provides information such as context, integrations, and anonymousId. Specific user traits can be provided as the context as well. Refer to the section for more information.

In the above example, information such as the userId and email along with the is captured.

For more information on the setAnonymousId method, refer to the section below.

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 .

Here, the second parameter is the AMP Linker ID format in accordance with the . For the links decorated with the , the <idName1> value will be rs_amp_id.

Provides information such as context, integrations, anonymousId, etc. Specific user traits can also be provided as the context. Refer to the section for more information.

In the above example, the SDK also captures the information such as the page category and page name along with the .

Tracks the information like the context, integrations, etc. Specific user traits can also be provided as the context. Refer to the section for more information.

A dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the section for more information.

A dictionary of information such as context, integrations, etc. Specific user traits can be provided as the context as well. Refer to the section for more information.

Refer to the section. More information on how to use this parameter can be found .

More information on using IntegrationOpts can be found in the section.

For more information on the consent managers supported by RudderStack, refer to .

The JavaScript SDK provides anonymousIdOptions object in the call options. It automatically captures the anonymous ID from a source and sets it as Rudderstack’s anonymousId.

Refer to the guide for more information on this feature.

RudderStack lets you load or send your event data to only the destinations specified by you. You can do so by passing an in the options parameter of the API methods. RudderStack then loads or sends events only to those destinations that are specified and enabled.

You can refer to the for the naming conventions for the destinations.

In this section, we cover two specific dictionaries within the parameter included in the supported API methods.

Traits is an optional dictionary included within which specifies the user's unique traits. This is a very useful field for linking the user's information from a previously made call to the subsequent or calls.

Refer to the section for solutions to some of the commonly faced issues while using the JavaScript SDK on your website.

For more information on any of the sections covered in this guide, you can or start a conversation in our community.

If you come across any issues while using this SDK, feel free to submit them on our .

this guide
this guide
navigator.sendBeacon
this section
RudderStack Control Plane Lite
here
Google Chromecast
these instructions
Google Cast developer guide
contextual information
Data Storage in Cookies
specified structure
RudderStack Linker parameter
contextual information
this section
load()
Client-side Event Filtering
Common destination names
FAQs
contact us
Slack
GitHub issues page
options
Filtering selective destinations
track
page
reset
Overriding the anonymousId using setAnonymousId
Filtering selective destinations
integrations object
options
context
identify()
track()
page()
this section
BeaconQueueOpts
BeaconQueueOpts
here
IntegrationOpts
IntegrationOpts
here
QueueOpts
QueueOpts
cookieConsentManager
Capturing anonymousId automatically
options
options
options
options
options
IntegrationOpts
IntegrationOpts
here
Introducing RudderStack's New, High-performance JavaScript SDK
Migrating to JavaScript SDK v1.1
GitHub repository
Data Storage in Cookies
this guide
quick start guide
Github Badge