Rudder Sdk Js Save

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

Project README

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.

Using CDN

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.10";var e="rudderanalytics";window[e]||(window[e]=[])
  ;var t=window[e];if(Array.isArray(t)){if(true===t.snippetExecuted&&window.console&&console.error){
  console.error("RudderStack JavaScript SDK snippet included more than once.")}else{t.snippetExecuted=true,
  window.rudderAnalyticsBuildType="legacy";var sdkBaseUrl="https://cdn.rudderlabs.com/v3";var sdkName="rsa.min.js"
  ;var r="async"
  ;var n=["setDefaultInstanceKey","load","ready","page","track","identify","alias","group","reset","setAnonymousId","startSession","endSession","consent"]
  ;for(var i=0;i<n.length;i++){var d=n[i];t[d]=function(r){return function(){var n
  ;Array.isArray(window[e])?t.push([r].concat(Array.prototype.slice.call(arguments))):null===(n=window[e][r])||void 0===n||n.apply(window[e],arguments)
  }}(d)}try{new Function('return import("")'),window.rudderAnalyticsBuildType="modern"}catch(c){}
  var o=document.head||document.getElementsByTagName("head")[0]
  ;var a=document.body||document.getElementsByTagName("body")[0];window.rudderAnalyticsAddScript=function(e,t,n){
  var i=document.createElement("script");i.src=e,i.setAttribute("data-loader","RS_JS_SDK"),t&&n&&i.setAttribute(t,n),
  "async"===r?i.async=true:"defer"===r&&(i.defer=true),o?o.insertBefore(i,o.firstChild):a.insertBefore(i,a.firstChild)},
  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__),
  window.rudderAnalyticsAddScript("".concat(sdkBaseUrl,"/").concat(window.rudderAnalyticsBuildType,"/").concat(sdkName),"data-rsa-write-key",<WRITE_KEY>)
  },
  "undefined"==typeof Promise||"undefined"==typeof globalThis?window.rudderAnalyticsAddScript("https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=Symbol%2CPromise&callback=rudderAnalyticsMount"):window.rudderAnalyticsMount()
  ;t.load(<WRITE_KEY>,<DATA_PLANE_URL>,{})}}}();
</script>

The above snippet lets you integrate the SDK with your website and load it asynchronously to avoid impacting the performance of your webpages.

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();

Using NPM

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 applications for a detailed walkthrough of the above steps:

See the examples directory in this repository for more sample applications for different frameworks.

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

You can load the JavaScript SDK using the load API 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.

Identifying users

The identify API 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: '[email protected]',
    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 is successful.');
  },
);

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

There is no need to call identify API 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 API.

Tracking user actions

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

A sample track API is shown below:

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

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

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

Ready state

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 device-mode destinations.

An example is shown in the following snippet:

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

Loaded state

Alternatively, if you just want to wait for the SDK to load, you can use the onLoaded load API option to configure a callback function.

The configured callback function is executed when the SDK has loaded successfully but before all the device-mode destinations are initialized.

This is especially helpful to query information from the SDK after it has loaded to use it elsewhere. For example, you can retrieve the anonymous ID generated by the SDK after it has loaded.

An example is shown in the following snippet:

rudderanalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
  onLoaded: () => {
    console.log('SDK has loaded.');
    console.log('Anonymous ID:', rudderanalytics.getAnonymousId());
  },
});

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.

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

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

  • 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 more 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 more details, see:

License

This project is licensed under the Elastic License 2.0. See the LICENSE.md file for details. Review the license terms to understand your permissions and restrictions.

If you have any questions about licensing, please contact us or refer to the official Elastic licensing page.

Contribute

We encourage contributions to this project. For detailed guidelines on how to contribute, please refer to 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

:clap: Our Supporters

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

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

Open Source Agenda is not affiliated with "Rudder Sdk Js" Project. README Source: rudderlabs/rudder-sdk-js