RudderStack JavaScript SDK

repository·develop·Indexed 41 days ago

https://github.com/rudderlabs/rudder-sdk-js

A client-side library used to track customer event data from websites and stream it to specified destinations via the RudderStack platform. Version 3.122.0.

Tokens
48.1K
Snippets
209
Records
268
Agent score
51%

What's inside RudderStack

  1. Overview of @rudderstack/analytics-js-common

    develop

    The @rudderstack/analytics-js-common package contains shared logic and common code used across the RudderStack JavaScript SDK ecosystem. This includes the core analytics, plugins, integrations, and service worker packages.

    For high-level implementation guides and detailed documentation on using the RudderStack JavaScript SDK to track events, refer to the official RudderStack documentation.

  2. Use @rudderstack/sanity-suite for testing

    develop

    The @rudderstack/sanity-suite is a testing utility designed for manual and automated testing of the RudderStack JavaScript SDK. It provides pre-configured environments to verify SDK behavior across different installation methods.

    To perform testing, you can access the hosted Sanity Suites:

    For automated testing workflows, this suite is intended to be used in conjunction with the RudderStack client-side testing framework.

  3. Project Structure of the Cloudflare Worker Example

    develop

    The example repository is organized as follows:

    • src/worker.js: Contains the main worker logic and RudderStack implementation.
    • wrangler.toml: The configuration file for Cloudflare Workers.
    • .env: Local environment variables (contains sensitive credentials; not committed to git).
    • scripts/update-wrangler-config.js: A utility script used to update wrangler.toml with values from the .env file.
  4. Use @rudderstack/loading-scripts to load the RudderStack JavaScript SDK

    develop
    The @rudderstack/loading-scripts package provides the snippet code required to asynchronously load the RudderStack JavaScript SDK into your web application. This is the standard method for initializing the SDK via a script tag, ensuring that tracking can begin as soon as the library is available.
  5. Implementation Patterns for RudderStack in Cloudflare Workers

    develop

    When implementing RudderStack within a Cloudflare Worker, follow these best practices for performance and reliability:

    • Singleton Initialization: Initialize the RudderStack Analytics client as a global variable outside the request handler. This ensures the client is only initialized once, improving performance across multiple requests.
    • Environment Variable Usage: The client automatically utilizes environment variables defined in your wrangler.toml file.
    • Event Flushing: For every incoming request, the worker should trigger a track event and explicitly ensure the event is flushed before the worker sends its final response to the client.
  6. How Environment Variables are Handled in the Angular Sample

    develop

    The sample app uses a specific workflow to inject environment variables into the Angular runtime:

    1. Definition: Variables are defined in .env or .env.example files.
    2. Processing: Before the app starts, scripts/replace-env-placeholders.js processes src/env-config.js, replacing placeholders with actual values from the .env file.
    3. Access: The Angular application accesses these values via the window object.

    Key Files:

    • src/env-config.js: Loads environment variables into the window object.
    • src/app/use-rudder-analytics.ts: Contains the actual RudderStack SDK initialization logic.
  7. How RetryQueue works

    develop

    The RetryQueue provides durable retries by maintaining a queue in localStorage (falling back to memory if necessary).

    Each page maintains its own list of queued and in-progress tasks and periodically refreshes its 'ack time'. If a queue does not update its ack time for more than 10 seconds, another page will assume the queue is abandoned, remove it, claim all queued tasks, and retry all in-progress tasks.

  8. What are @rudderstack/analytics-js-plugins?

    develop
    Plugins are features available in the RudderStack JavaScript SDK v3 that can be loaded on demand. This package contains the plugin code used within the main analytics package, for legacy packaging bundles, or as separate bundle chunks for dynamic imports. This allows developers to keep the initial SDK footprint small by only loading specific plugin functionality when needed.
  9. Implement dual-environment tracking in Next.js

    develop

    This sample demonstrates how to use both the JavaScript SDK and the Node SDK within a Next.js application to capture events from different runtimes:

    1. Browser Runtime: Uses @rudderstack/analytics-js to call APIs like page, identify, track, group, and alias directly from the client.
    2. Server Runtime: Uses @rudderstack/rudder-sdk-node within getServerSideProps or Next.js API routes to capture server-side events.

    To configure destinations for both paths, edit src/lib/rudderstack-config.ts to select destinations by their dashboard names using the integrations setting.

  10. Determine the top-level domain using top-domain

    develop

    The top-domain utility constructs possible domain levels from a given URL and attempts to set a cookie for each level (using the format "." + domain"). If setting the cookie succeeds, it returns that level as the top-level domain.

    Important Limitation: This utility only works when executed on the domain itself, as it relies on the ability to set cookies for the target domain levels.

    var domain = require('top-domain');
    
    // Examples of successful domain extraction:
    console.log(domain('http://www.google.com'));      // 'google.com'
    console.log(domain('http://www.google.co.uk'));   // 'google.co.uk'
    console.log(domain('http://gist.github.com/...')); // 'github.com'
    
    // Examples where it returns an empty string (e.g., local or IP addresses):
    console.log(domain('http://localhost:3000'));     // ''
    console.log(domain('127.0.0.1'));                 // ''
  11. How the Plugin Engine and Extension Points work

    develop

    The RudderStack Plugin Engine uses a plugin-based architecture to decouple business logic and allow for extensible modules.

    Core Concepts:

    • Extension Point: A string representing a path in a plugin object (e.g., menu.processMenuItems). It acts as a hook that modules can call to allow plugins to contribute logic or data.
    • Plugin: A JavaScript object that contributes to one or more extension points. Every plugin must have a unique name.
    • Provider/Consumer Relationship: An extensible module (the provider) calls plugin.invoke(extPoint) or plugin.getPlugins(extPoint). A plugin (the consumer) defines a structure that matches that extension point path.

    Example Workflow:

    1. A component defines an extension point:
      const menuItems = [];
      plugin.invoke('menu.processMenuItems', menuItems);
    2. A plugin contributes to it:
      plugin.register({
        name: 'samplePlugin',
        menu: {
          processMenuItems(items) {
            items.push({ label: 'label', link: 'hello/sample' });
          },
        },
      });
    const menuItems = [];
    plugin.invoke('menu.processMenuItems', menuItems);
    
    plugin.register({
      name: 'samplePlugin',
      menu: {
        processMenuItems(items) {
          items.push({ label: 'label', link: 'hello/sample' });
        },
      },
    });