• Stars
    star
    141
  • Rank 259,971 (Top 6 %)
  • Language
    TypeScript
  • License
    Other
  • Created about 5 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript SDK for RudderStack - the Customer Data Platform for Developers.

The Customer Data Platform for Developers

Website Β· Documentation Β· Community Slack

Releases Quality Gate Status Maintainability Rating Reliability Rating Security Rating Coverage


RudderStack JavaScript SDK

The JavaScript SDK lets you track customer event data from your website and send it to your specified destinations via RudderStack.

For detailed documentation on the RudderStack JavaScript SDK, click here.

Table of Contents

IMPORTANT: We have deprecated the Autotrack feature for the RudderStack JavaScript SDK and it will soon be removed. If you still wish to use it for your project, refer to this repository.

Installing the JavaScript SDK

To integrate the JavaScript SDK with your website, place the following code snippet in the <head> section of your website.

<script type="text/javascript">
!function(){var e=window.rudderanalytics=window.rudderanalytics||[];e.methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],e.factory=function(t){return function(){e.push([t].concat(Array.prototype.slice.call(arguments)))}};for(var t=0;t<e.methods.length;t++){var r=e.methods[t];e[r]=e.factory(r)}e.loadJS=function(e,t){var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.rudderlabs.com/v1.1/rudder-analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a)},e.loadJS(),
e.load(<WRITE_KEY>,<DATA_PLANE_URL>),
e.page()}();
</script>

The above snippet lets you integrate the SDK with your website and load it asynchronously to keep your page load time unaffected.

To load rudder-analytics.js on to your page synchronously, you can refer to the minified or non-minified versions of the code in the following sections:

Minified code

<script>
  rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}rudderanalytics.load(<WRITE_KEY>,<DATA_PLANE_URL>),rudderanalytics.page();
</script>

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

Non-minified code

<script>
  rudderanalytics = window.rudderanalytics = [];

  var methods = [
    'load',
    'page',
    'track',
    'identify',
    'alias',
    'group',
    'ready',
    'reset',
    'getAnonymousId',
    'setAnonymousId',
  ];

  for (var i = 0; i < methods.length; i++) {
    var method = methods[i];
    rudderanalytics[method] = (function (methodName) {
      return function () {
        rudderanalytics.push([methodName].concat(Array.prototype.slice.call(arguments)));
      };
    })(method);
  }
  rudderanalytics.load(YOUR_WRITE_KEY, DATA_PLANE_URL);
  //For example,
  //rudderanalytics.load("1Qb1F3jSWv0eKFBPZcrM7ypgjVo", "http://localhost:8080");
  rudderanalytics.page();
</script>

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

In all the above versions, there is an explicit page call at the end. This is added to ensure that whenever the SDK loads in a page, a page call is sent. You can remove this call completely or modify it with the extra page properties to suit your requirement. You can also add page calls in your application in places not tied directly to page load, e.g., virtual page views, page renders on route change such as in SPAs, etc.

Write key and data plane URL

To integrate and initialize the JavaScript SDK, you will need the source write key and the data plane URL.

Alternative installation using NPM

Although we recommend using the snippets mentioned above to use the JavaScript SDK with your website, you can also use this NPM module to package RudderStack directly into your project.

To install the SDK via npm, run the following command:

npm install rudder-sdk-js --save

Note that this NPM module is only meant to be used for a browser installation. If you want to integrate RudderStack with your Node.js application, refer to the RudderStack Node.js repository.

IMPORTANT: Since the module exports the related APIs on an already-defined object combined with the Node.js module caching, you should run the following code snippet only once and use the exported object throughout your project:

import * as rudderanalytics from "rudder-sdk-js";
rudderanalytics.ready(() => {
  console.log("we are all set!!!");
});
rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>);
export { rudderanalytics };

You can also do this with ES5 using the require method, as shown:

var rudderanalytics = require("rudder-sdk-js");
rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>);
exports.rudderanalytics = rudderanalytics;

For destinations where you don't want the SDK to load the third-party scripts separately, modify the load call as shown:

rudderanalytics.load(<YOUR_WRITE_KEY>, <DATA_PLANE_URL>, {loadIntegration:  false})

For more information on the load() method, refer to the detailed JavaScript SDK documentation.

A few important things to note:

  • The SDK expects the destination global queue or function for pushing the events is already present for the particular destination/s.
  • Currently, loadIntegration is supported only for Amplitude and Google Analytics.
  • The JavaScript SDK expects window.amplitude and window.ga to be already defined by the user separately for the sending the events to these destinations.

Exported APIs

The APIs exported by the module are:

  • load
  • ready
  • identify
  • alias
  • page
  • track
  • group
  • reset
  • getAnonymousId
  • setAnonymousId

Sample implementations

Refer to the following projects for a detailed walk-through of the above steps:

Supported browser versions

Browser Supported Versions
Safari v7 or later
IE v10 or later
Edge v15 or later
Mozilla Firefox v40 or later
Chrome v37 or later
Opera v23 or later
Yandex v14.12 or later

If the SDK does not work on the browser versions that you are targeting, verify if adding the browser polyfills to your application solves the issue.

Identifying users

The identify call lets you identify a visiting user and associate them to their actions. It also lets you record the traits about them like their name, email address, etc.

A sample identify() call is shown below:

rudderanalytics.identify(
  '12345',
  {
    email: '[email protected]',
  },
  {
    page: {
      path: '',
      referrer: '',
      search: '',
      title: '',
      url: '',
    },
  },
  () => {
    console.log('in identify call');
  },
);

In the above example, the user-related information like the userId and email along with the contextual information is captured.

There is no need to call identify() for anonymous visitors to your website. Such visitors are automatically assigned an anonymousId.

For more information on how to use the identify call, refer to the JavaScript SDK documentation.

Tracking user actions

The track call lets you record the customer events, i.e. the actions that they perform, along with any associated properties.

A sample track call is shown below:

rudderanalytics.track(
  'test track event GA3',
  {
    revenue: 30,
    currency: 'USD',
    user_actual_id: 12345,
  },
  () => {
    console.log('in track call');
  },
);

In the above example, the track method tracks the user event β€˜test track event GA3’ and information such as the revenue, currency, anonymousId.

You can use the track method to track various success metrics for your website like user signups, item purchases, article bookmarks, and more.

The ready API

There are cases when you may want to tap into the features provided by the end-destination SDKs to enhance tracking and other functionalities. The JavaScript SDK exposes a ready API with a callback parameter that fires when the SDK is done initializing itself and the other third-party native SDK destinations.

An example is shown in the following snippet:

rudderanalytics.ready(() => {
  console.log('we are all set!!!');
});

For more information on the other supported methods, refer to the JavaScript SDK APIs.

Self-Hosted control plane

If you are using a device mode destination like Heap, FullStory, etc., the JavaScript SDK needs to fetch the required configuration from the 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:

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

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

For detailed technical documentation and troubleshooting guide on the RudderStack’s JavaScript SDK, check out our docs.

Adding your own integrations

You can start adding integrations of your choice for sending the data through their respective web (JavaScript) SDKs.

How to build the SDK

  • Look for run scripts in the package.json file for getting the browser minified and non-minified builds. The builds are updated in the dist folder of the directory. Among the others, some of the important ones are:

    • npm run build:browser: This outputs rudder-analytics.min.js.
    • npm run build:npm: This outputs rudder-sdk-js folder that contains the npm package contents.
    • npm run build:integration:all: This outputs integrations folder that contains the integrations.

We use rollup to build our SDKs. The configuration for it is present in rollup-configs folder.

  • For adding or removing integrations, modify the imports in index.js under the src/integrations folder.

Usage in Chrome Extensions

RudderStack JS SDK can be used in Chrome Extensions with manifest v3, both as a content script or as a background script service worker.

For examples and specific details look into Chrome Extensions Usage

Contribute

We would love to see you contribute to this project. Get more information on how to contribute here.

Contact us

For more information on any of the sections covered in this readme, you can contact us or start a conversation on our Slack channel.

More Repositories

1

rudder-server

Privacy and Security focused Segment-alternative, in Golang and React
Go
4,051
star
2

rudder-transformer

Open-source, warehouse-first Customer Data Pipeline and Segment-alternative. Collects and routes clickstream data and builds your customer data lake on your data warehouse.
TypeScript
79
star
3

rudderstack-helm

Open-source, warehouse-first Customer Data Pipeline and Segment-alternative. Collects and routes clickstream data and builds your customer data lake on your data warehouse.
Mustache
59
star
4

rudder-workflow-engine

A generic embeddable workflow execution engine library
TypeScript
33
star
5

rudderstack-docs

Documentation repository for RudderStack - the Customer Data Platform for Developers.
JavaScript
23
star
6

rudder-json-template-engine

JSON path based template language for data transformations
TypeScript
21
star
7

config-generator

Repo for RudderStack's Config Generator, that generates configuration JSON files to be used with the RudderStack server.
TypeScript
18
star
8

graceful-shutdown-examples

Code examples for graceful shutdown
Go
17
star
9

rudder-sdk-android

Android SDK for RudderStack - the Customer Data Platform for Developers.
Java
16
star
10

github-notion

Get issues to reflect in Notion
JavaScript
15
star
11

dbt-sessionization

Using DBT for Creating Session Abstractions on RudderStack - an open-source, warehouse-first customer data pipeline and Segment alternative.
15
star
12

rudder-sdk-ios

iOS SDK for RudderStack - the Customer Data Platform for Developers. Now supports tvOS, watchOS and macOS tracking!
Objective-C
14
star
13

rudder-sdk-react-native

Repository for RudderStack's React Native SDK - to track your event data via RudderStack.
Java
14
star
14

sample-user-transformers

Sample User Transformations for RudderStack - the CDP for Developers.
JavaScript
12
star
15

dbt-id-stitching

Stitch together multiple identities within your warehouse
Shell
11
star
16

dbt-id-resolution

Using DBT for ID Resolution on RudderStack - an open-source, warehouse-first customer data pipeline and Segment alternative.
10
star
17

query-generator

Source code for RudderStack's Event Query Generator tool.
TypeScript
9
star
18

js-chrome-extension

JavaScript
9
star
19

rudder-blog

The open-source repo for the RudderStack blog.
JavaScript
7
star
20

dbt-customer-journey-analysis

Using DBT for Customer Journey Analysis on RudderStack - an open-source, warehouse-first customer data pipeline and Segment alternative.
7
star
21

github-notion-sync

GIthub action for syncing issues from github to notion
JavaScript
6
star
22

rudder-go-kit

Common Go utilities and libraries for rudder projects!
Go
6
star
23

rudder-plugins-manager

Go library to create plugins and workflows for data pipelines
Go
6
star
24

rudder-shopify-tracker

Shopify web device mode tracking code
JavaScript
6
star
25

rudder-sdk-flutter

Flutter SDK for RudderStack - the Customer Data Platform for Developers. Now supports Android, iOS and Web tracking!
Dart
6
star
26

sqlconnect-go

A uniform client interface in Go for accessing different warehouses
Go
5
star
27

rudder-sdk-unity

Repo for RudderStack's Unity SDK. RudderStack is an open-source, warehouse-first Customer Data Pipeline and Segment-alternative. It collects and routes clickstream data and builds your customer data lake on your data warehouse.
Objective-C
5
star
28

terraform-provider-rudderstack

Go
4
star
29

rudder-kafka-sink-connector

Apache Kafka Connect sink connector for Rudderstack
Java
4
star
30

rudder-php-sdk

RudderStack's PHP SDK for effective server-side event tracking.
PHP
4
star
31

rudder-transformation-action

JavaScript
3
star
32

gatsby-plugin-rudderstack

Gatsby plugin to send customer event data to RudderStack
JavaScript
3
star
33

rudder-sdk-js-autotrack

Privacy and Security focused Segment-alternative, in Golang and React
JavaScript
3
star
34

rudder-integration-appcenter-ios

RudderStack's Native SDK integration with Visual Studio App Center.
Objective-C
2
star
35

rudderstack-profiles-basic-example

quick-start for learning about rudderstack profiles
2
star
36

looker-snowflake

Looker block for creating analytics dashboard on RudderStack data.
LookML
2
star
37

data-apps-ecommerce-template

2
star
38

dbt-rudderstack-attribution

Repository for DBT code related to Attribution Use Case
2
star
39

rudder-integration-bugsnag-ios

RudderStack's Native SDK integration support for Bugsnag.
Objective-C
2
star
40

looker-bigquery

Looker Block for Sessionization of the track-type events in the RudderStack platform.
LookML
2
star
41

rscp_pyclient

'This package(RudderStack Control Plain Python Client) includes python functions to execute CRUD operations on REST API exported by RudderStack.
Python
2
star
42

rudderstack-posthog-plugin

PostHog plugin to send events to RudderStack
JavaScript
2
star
43

profiles-shopify-features

2
star
44

profiles-base-features

2
star
45

rudderstack-profiles-shopify-churn

2
star
46

rudder-integration-appsflyer-ios

RudderStack's Native SDK integration support for AppsFlyer.
Objective-C
2
star
47

terraform-aws-eks

Terraform code and scripts for creating a new AWS EKS cluster in a new VPC
HCL
2
star
48

rudder-api-go

Rudder Public API Golang SDK
Go
2
star
49

rudder-repo-template

Repository Template for RudderStack - the open-source, warehouse-first customer data pipeline and Segment alternative.
2
star
50

rudder-event-analytics

2
star
51

dbt-events-registry

Using DBT for Creating Events Registry on RudderStack - an open-source, warehouse-first customer data pipeline and Segment alternative.
2
star
52

torpedo-client

Open-source, warehouse-first Customer Data Pipeline and Segment-alternative. Collects and routes clickstream data and builds your customer data lake on your data warehouse.
C#
2
star
53

rudder-sdk-rust

Rust SDK for RudderStack - Open-source, warehouse-first Customer Data Pipeline and Segment-alternative. It collects and routes clickstream data and builds your customer data lake on your data warehouse.
Rust
2
star
54

rudderstack-profiles-classifier

Python
2
star
55

rudder-cp-sdk

Rudder Control Plane SDK
Go
2
star
56

rudder-integration-adjust-android

RudderStack's Native SDK integration support for Adjust.
Java
1
star
57

safequery

Preparing SQL queries in simple and safe way
Go
1
star
58

rudder-integration-adjust-ios

RudderStack's Native SDK integration support for Adjust.
Objective-C
1
star
59

cp-client-go

Go
1
star
60

rudderstack-shopify-app

Shopify App to send customer event data to RudderStack
JavaScript
1
star
61

rudder-airflow-provider

Rudderstack provider for Apache Airflow
Python
1
star
62

compose-test

Run go tests using docker-compose for external dependencies
Go
1
star
63

sql-tunnels

Augment sql driver with tunnelling capabilities
Go
1
star
64

community-user-transformations

1
star
65

segment-migrator

Python
1
star
66

data-apps-attribution-template

Jupyter Notebook
1
star
67

profiles-shopify-template-test

test repo for shopify profiles project. Used for dev testing
1
star
68

rudder-integration-bugsnag-android

RudderStack's Native SDK integration support for Bugsnag.
Kotlin
1
star
69

rudder-observability-kit

Common libraries for Rudderstack Observability
Go
1
star
70

rudder-json-template-web-app

Playground for Rudder JSON template Language
TypeScript
1
star
71

rudder-samples

Sample applications to demonstrate various use-cases of RudderStack - the customer data platform for developers.
HTML
1
star
72

rudder-sdk-js-snippet

Repo with an alternative approach to rendering the rudder-analytics.js snippet dynamically in RudderStack - an open-source, warehouse-first customer data pipeline and Segment alternative.
JavaScript
1
star
73

profiles-pycorelib

A Python Native package that registers the core python models
Python
1
star
74

dagster-rudderstack

A Dagster library for triggering reverse ETL syncs in RudderStack
Python
1
star
75

rudder-utility

RudderStack is an open-source, warehouse-first Customer Data Pipeline and Segment-alternative. It collects and routes clickstream data and builds your customer data lake on your data warehouse.
Go
1
star