rudderlabs/rudder-sdk-js
概要
JavaScript SDK for RudderStack - the Customer Data Platform for Developers.
開発ツール計測したスター増加
- 24時間
- 0
- 7日間
- 0
- 15日間
- 0
- 1か月
- 履歴を収集中
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナル
🚀 Just launched RudderAI - the agentic layer for the entire customer data lifecycle
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
- Installing the JavaScript SDK
- Migrating SDK from an older version
- Loading the SDK
- Security hardening
- Identifying your users
- Tracking user actions
- The
readyAPI - 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. |
|---|
Installing the JavaScript SDK
| For detailed installation steps, see the JavaScript SDK documentation. |
|---|
Using CDN
See CDN installation for detailed steps.
To load SDK script on to your page synchronously, see the JavaScript SDK documentation.
IMPORTANT: The implicit
pagecall at the end of the snippet (present in the previous JavaScript SDK versions) is removed in the latest SDK (v3). You need to make apagecall 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
requiremethod:
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.
Security hardening
| For the full guide, see Harden the JavaScript SDK. |
|---|
You can harden the SDK by reducing its reliance on external resources that could be used to disrupt the event flow or compromise your app. RudderStack recommends installing the SDK using NPM.
Device mode destinations load third-party vendor SDKs into your website, so avoid them and use cloud mode destinations instead. Steps 1 and 2 apply to every NPM setup; for the CDN snippet, see Hardening the CDN snippet. In step 3, choose cloud mode destinations only (3a) for the most hardened setup, where the SDK loads no device mode destinations, or strict mode (3b) if you must keep device mode destinations.
Use the bundled NPM export. The SDK then makes no request to download plugins at runtime. You can also self-host the plugins and integration SDKs or serve the SDK from your own domain.
import { RudderAnalytics } from '@rudderstack/analytics-js/bundled';Disable polyfills. Set
polyfillIfRequiredtofalseso the SDK adds no polyfills script from a third-party domain.Choose how destinations load:
a. Cloud mode destinations only: mock the source configuration. With a
getSourceConfigfunction, the SDK makes no source configuration request. The mocked configuration lists no destinations, so the SDK loads no vendor SDKs. Cloud mode destinations still receive your events, as RudderStack routes them on the server. See the fullloadcall below.b. Device mode destinations: use strict mode. The SDK needs the real source configuration to load device mode destinations, so do not mock it. Set
vendorSdkVersionPolicytostrictso the SDK loads only the vendor SDKs it can pin. Destinations whose vendor scripts cannot be pinned are skipped; destinations without vendor scripts, custom integrations and vendor scripts loaded from URLs you set still load.rudderAnalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, { polyfillIfRequired: false, vendorSdkVersionPolicy: 'strict', });
Without strict mode, the SDK still loads an exact release of each vendor SDK it can pin (Amplitude, Bugsnag, Iterable, Keen, LaunchDarkly, Rollbar and Sentry), verified with a Subresource Integrity (SRI) hash. If the vendor's file changes, the browser refuses to run it, and only that destination is affected.
The final load call for a setup with cloud mode destinations only (steps 1, 2 and 3a):
import { RudderAnalytics } from '@rudderstack/analytics-js/bundled';
const rudderAnalytics = new RudderAnalytics();
rudderAnalytics.load(<WRITE_KEY>, <DATA_PLANE_URL>, {
polyfillIfRequired: false,
getSourceConfig: () => ({
updatedAt: new Date().toISOString(),
source: {
// Use relevant valid values from the RudderStack dashboard
name: <SOURCE_NAME>,
id: <SOURCE_ID>,
workspaceId: <WORKSPACE_ID>,
writeKey: <WRITE_KEY>,
updatedAt: new Date().toISOString(),
config: {
statsCollection: {
errors: { enabled: false },
metrics: { enabled: false },
},
},
enabled: true,
destinations: [],
},
}),
});
export { rudderAnalytics };
Hardening the CDN snippet
If you must load the SDK using the CDN snippet, pin sdkVersion to an exact release and leave sdkFileName unchanged:
var sdkVersion = '<EXACT_SDK_VERSION>'; // For example, '3.36.0'
The SDK derives the plugins and integration SDK paths from its own script URL, so this also pins them, unless you set destSDKBaseURL or pluginsSDKBaseURL in the load options. Update those to the pinned version too, or remove them.
IMPORTANT: A pinned SDK does not receive fixes or security updates automatically. Watch the releases and update
sdkVersionwith each release.
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
identifyAPI 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.
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
trackAPI 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.jsonfile for getting the browser minified and non-minified builds. The builds are updated in thedistfolder 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-configsdirectory.
- For adding or removing integrations, modify the imports in
index.jsunder thesrc/integrationsfolder.
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 MIT License. See the LICENSE.md file for details.
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
関連プロジェクトを探す
読み込み中…