The Customer Data Platform for Developers
Website · Documentation · Community Slack
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.
- Installing the JavaScript SDK
- Migrating SDK from an older version
- Loading the SDK
- Identifying your users
- Tracking user actions
- The
ready
API - Self-hosted control plane
- Adding your own integrations
- How to build the SDK
- Usage in Chrome Extensions
- Usage in Serverless Runtimes
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. |
---|
For detailed installation steps, see the JavaScript SDK documentation. |
---|
See CDN installation for detailed steps.
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 apage
call explicitly, if required, as shown below:
rudderanalytics.page();
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;
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.
If you are migrating the JavaScript SDK from an older version (<= v1.1), see the Migration Guide for details.
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.
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: '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 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 ananonymousId
.
See the JavaScript SDK documentation for more information on how to use the identify
API.
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.
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!!!');
});
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.
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.
-
Look for run scripts in the
package.json
file for getting the browser minified and non-minified builds. The builds are updated in thedist
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 thesrc/integrations
folder.
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.
RudderStack JS SDK service worker can be used in serverless runtimes like Cloudflare Workers or Vercel Edge functions.
For more details, see:
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.
We encourage contributions to this project. For detailed guidelines on how to contribute, please refer to here.
For more information on any of the sections covered in this readme, you can contact us or start a conversation on our Slack channel.