Skip to content

Latest commit

 

History

History
351 lines (251 loc) · 18.3 KB

README.md

File metadata and controls

351 lines (251 loc) · 18.3 KB

Releases TypeScript Quality Gate Status Maintainability Rating Reliability Rating Security Rating Coverage

RudderStack
The Customer Data Platform for Developers

Website · Documentation · Community Slack


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: The service worker export has been deprecated from the RudderStack JavaScript SDK npm package and moved to a new package.
If you still wish to use it for your project, see @rudderstack/analytics-js-service-worker package.

Installing the JavaScript SDK

For detailed installation steps, see the JavaScript SDK documentation.

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(){"use strict";window.RudderSnippetVersion="3.0.3";var sdkBaseUrl="https://cdn.rudderlabs.com/v3"
  ;var sdkName="rsa.min.js";var asyncScript=true;window.rudderAnalyticsBuildType="legacy",window.rudderanalytics=[]
  ;var e=["setDefaultInstanceKey","load","ready","page","track","identify","alias","group","reset","setAnonymousId","startSession","endSession","consent"]
  ;for(var n=0;n<e.length;n++){var t=e[n];window.rudderanalytics[t]=function(e){return function(){
  window.rudderanalytics.push([e].concat(Array.prototype.slice.call(arguments)))}}(t)}try{
  new Function('return import("")'),window.rudderAnalyticsBuildType="modern"}catch(a){}
  if(window.rudderAnalyticsMount=function(){
  "undefined"==typeof globalThis&&(Object.defineProperty(Object.prototype,"__globalThis_magic__",{get:function get(){
  return this},configurable:true}),__globalThis_magic__.globalThis=__globalThis_magic__,
  delete Object.prototype.__globalThis_magic__);var e=document.createElement("script")
  ;e.src="".concat(sdkBaseUrl,"/").concat(window.rudderAnalyticsBuildType,"/").concat(sdkName),e.async=asyncScript,
  document.head?document.head.appendChild(e):document.body.appendChild(e)
  },"undefined"==typeof Promise||"undefined"==typeof globalThis){var d=document.createElement("script")
  ;d.src="https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=Symbol%2CPromise&callback=rudderAnalyticsMount",
  d.async=asyncScript,document.head?document.head.appendChild(d):document.body.appendChild(d)}else{
  window.rudderAnalyticsMount()}window.rudderanalytics.load(<WRITE_KEY>,<DATA_PLANE_URL>,{})}();
</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 SDK script on to your page synchronously, see the JavaScript SDK documentation.

IMPORTANT: The implicit page call at the end of the snippet (present in the previous JavaScript SDK versions) is removed in the latest SDK v3. You need to make a page call explicitly, if required, as shown below:

rudderanalytics.page();

NPM installation

Although we recommend using the CDN installation method 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 @rudderstack/analytics-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, see the RudderStack Node.js documentation.

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:

  • For ECMAScript modules (ESM):
import { RudderAnalytics } from '@rudderstack/analytics-js';

const rudderAnalytics = new RudderAnalytics();
rudderAnalytics.load(WRITE_KEY, DATA_PLANE_URL, {});

export { rudderAnalytics };
  • For CJS using the require method:
var RudderAnalytics = require('@rudderstack/analytics-js');

const rudderAnalytics = new RudderAnalytics();
rudderAnalytics.load(WRITE_KEY, DATA_PLANE_URL, {});

exports.rudderanalytics = rudderAnalytics;

Sample implementations

See the following projects for a detailed walkthrough of the above steps:

Exported APIs

The APIs exported by the module are:

  • load
  • ready
  • identify
  • page
  • track
  • group
  • alias
  • reset
  • setAnonymousId
  • startSession
  • endSession

See JavaScript SDK installation workflow for more information on these methods.

Supported browser versions

Browser Supported Versions
Browser Supported Versions
:-------------- :---------------------
Safari v7 and above
IE v11 and above
Edge v80 and above
Mozilla Firefox v47 and above
Chrome v54 and above
Opera v43 and above

You can try adding the browser polyfills to your application if the SDK does not work on your browser.

Migrating SDK from an older version

If you are migrating the JavaScript SDK from an older version (<=v1.1), see the Migration Guide for details.

Loading the SDK

For detailed information on the load() method, see the JavaScript SDK documentation.

You can load the JavaScript SDK using the load API method to track and send events from your website to RudderStack. Make sure to replace the "write key" and data plane URL with their actual values.

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, [loadOptions]);

You can use the loadOptions object in the above load call to define various options while loading the SDK.

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

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

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 destinations.
  • 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.

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(
    '1hKOmRA4el9Zt1WSfVJIVo4GRlm',
    {
      firstName: 'Alex',
      lastName: 'Keener',
      email: 'alex@example.com',
      phone: '+1-202-555-0146',
    },
    {
      page: {
        path: '/best-seller/1',
        referrer: 'https://www.google.com/search?q=estore+bestseller',
        search: 'estore bestseller',
        title: 'The best sellers offered by EStore',
        url: 'https://www.estore.com/best-seller/1',
      },
    },
    () => {
      console.log('identify call');
    },
  );

In the above example, the JavaScript SDK captures the user information like userId, firstName, lastName, email, and phone, along with the contextual information.

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

See the JavaScript SDK documentation for more information on how to use the identify call.

Tracking user actions

The track call lets you capture the user events along with any associated properties.

A sample track call is shown below:

rudderanalytics.track(
  'Order Completed',
  {
    revenue: 30,
    currency: 'USD',
    user_actual_id: 12345,
  },
  () => {
    console.log('track call');
  },
);

In the above example, the track method tracks the user event ‘Order Completed’ and information like the revenue, currency, etc.

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, see the JavaScript SDK APIs.

Self-hosted control plane

Control Plane Lite is now deprecated. It will not work with the latest rudder-server versions (after v1.2). Using RudderStack Open Source to set up your control plane is strongly recommended.

If you are self-hosting the control plane using the 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 obtaining the CONTROL_PLANE_URL can be found here.

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 dist/cdn/legacy/rudder-analytics.min.js.
    • npm run build:npm: This outputs dist/npm folder that contains the npm package contents.
    • npm run build:integration:all: This outputs dist/cdn/legacy 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

You can use the JavaScript SDK in Chrome Extensions with manifest v3, both as a content script (via the JavaScript SDK package) or as a background script service worker (via the service worker package).

For examples and specific details, see Chrome Extensions Usage.

Usage in Serverless runtimes

RudderStack JS SDK service worker can be used in serverless runtimes like Cloudflare Workers or Vercel Edge functions.

For examples and specific details look into:

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.

Follow Us

👏 Our Supporters

Stargazers repo roster for @rudderlabs/rudder-sdk-js

Forkers repo roster for @rudderlabs/rudder-sdk-js