How to Initialize Web-Tracing in a Vanilla JavaScript Project

To initialize web-tracing in a vanilla JavaScript project, import the init function from @web-tracing/core as an ES module and call it with a configuration object containing your dsn endpoint and appName.

The m-cheng-web/web-tracing repository provides a lightweight, framework-agnostic monitoring SDK that captures errors, performance metrics, and user interactions without requiring a build step. This guide explains how to initialize web-tracing in a vanilla JavaScript project using native ES modules, referencing the actual source implementation in packages/core/src/lib/exportMethods.ts.

What Happens When You Call init()

The init() function in packages/core/index.ts (exported from packages/core/src/lib/exportMethods.ts) performs a strict initialization sequence to prevent conflicts and ensure all monitors are properly instrumented:

  1. Duplicate initialization guard – The SDK checks _global.__webTracingInit__ and throws if the SDK is already initialized to prevent double-patching native APIs.
  2. Options validation – initOptions(options) parses the user-provided InitOptions interface and stores them in the internal _options object.
  3. Low-level patching – initReplace monkey-patches XMLHttpRequest, fetch, addEventListener, and other browser APIs to intercept network and event data.
  4. Utility initialization – initBase, initSendData, and initLineStatus set up the event bus, data buffering, and connection status detection.
  5. Monitor activation – Individual modules for error, event, http, performance, pv (page view), intersection observer (exposure tracking), and optional screen recording are started.
  6. State marking – The SDK sets _global.__webTracingInit__ = true to lock the initialized state.

Minimal Setup Without a Bundler

You can load the SDK directly in an HTML file without webpack, vite, or any build tool. The official example at examples/vanilla/index.html demonstrates this pattern.

CDN-based ES Module Import

Use the JSDelivr CDN to import the core package as an ES module:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Web-Tracing Vanilla Demo</title>
</head>
<body>
  <div id="app"></div>

  <script type="module">
    import { init } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";

    init({
      dsn: "https://your-endpoint.example.com/track",
      appName: "my-vanilla-app",
      debug: true,
      pv: true,
      performance: true,
      error: true,
      event: true,
      cacheMaxLength: 20,
      cacheWatingTime: 1500
    });
  </script>
</body>
</html>

Key configuration options:

  • dsn (required): The endpoint URL where telemetry data is sent.
  • appName (required): Identifier for your application in the dashboard.
  • debug: Enables console logging for development.
  • pv, performance, error, event: Boolean flags to toggle specific monitors.

Advanced Initialization Patterns

Delayed Initialization

For privacy compliance or performance optimization, you can delay initialization until user interaction. Expose a global helper function that calls init() on demand:

<script type="module">
  import { init } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";
  
  window.startTracing = () => {
    init({
      dsn: "https://your-endpoint.example.com/track",
      appName: "my-vanilla-app",
      debug: true,
      pv: true,
      performance: true,
      error: true,
      event: true
    });
  };
</script>

<button onclick="startTracing()">Initialize Web-Tracing</button>

Manual Cache Management

When you need to force-send cached events or handle storage overflow, use the utility functions from packages/core/src/lib/sendData.ts:

import { sendLocal, setLocalizationOverFlow } from "https://cdn.jsdelivr.net/npm/@web-tracing/core/dist/index.esm.js";

setLocalizationOverFlow((data) => {
  console.warn("Cache overflow – sending now", data);
});

sendLocal();

Core Architecture and Source Files

Understanding the internal structure helps with debugging and custom builds:

Summary

  • Use ES modules: Load @web-tracing/core via CDN using <script type="module"> to avoid bundler complexity.
  • Call init() once: The SDK guards against duplicate initialization using _global.__webTracingInit__; subsequent calls will throw.
  • Provide required options: At minimum, specify dsn and appName in your InitOptions configuration.
  • Leverage utilities: Use sendLocal() to flush cached data manually and destroyTracing() to clean up listeners when needed.
  • Reference source: All logic resides in packages/core/src/lib/ with the entry point at packages/core/index.ts.

Frequently Asked Questions

Can I use web-tracing without a CDN or npm?

Yes. Download the index.esm.js file from the CDN or build the repository from source, then serve it locally alongside your static assets. Import the local path in your module script: import { init } from './web-tracing/index.esm.js'.

What is the minimal required configuration to initialize web-tracing?

The init() function requires at least a dsn (your data collection endpoint) and an appName (application identifier). All other options in the InitOptions interface are optional and default to sensible production values.

How does the SDK prevent duplicate initialization?

The init() function checks _global.__webTracingInit__ before executing. If this flag is already true, the SDK throws an error to prevent double-patching of XMLHttpRequest and fetch, which would cause infinite loops and memory leaks.

Yes. Defer the init() call until a user interaction or consent signal. Wrap the initialization in a function exposed to the global scope (e.g., window.startTracing) and invoke it only after the user accepts your tracking policy, as shown in the delayed initialization pattern above.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →