or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

examples

edge-cases.mdreal-world-scenarios.md
index.md
tile.json

initialization.mddocs/reference/

Initialization

The SDK initialization function must be called as early as possible in the web page lifecycle, as most instrumentations can only observe events after init has been called.

Critical Timing Requirements:

  • Must be called before DOMContentLoaded event for full instrumentation coverage
  • Must be called before other SDK functions (identify, sendEvent, etc.)
  • Ideal placement is in <head> section or immediately after opening <body> tag
  • If called after page load, navigation timing and early web vitals may be missed
  • If called after user interactions, those interactions may not be tracked

Capabilities

Initialize SDK

Initializes the Dash0 Web SDK with the provided configuration options.

/**
 * Initializes the Dash0 Web SDK
 * @param opts - Configuration options for the SDK
 * @throws May throw errors if required fields are missing or invalid
 */
function init(opts: InitOptions): void;

interface InitOptions {
  // Required: Basic service information
  serviceName: string;
  serviceVersion?: string;

  // Deployment information
  environment?: string;
  deploymentName?: string;
  deploymentId?: string;

  // Required: Telemetry endpoint configuration
  endpoint: Endpoint | Endpoint[];

  // Instrumentation configuration
  enabledInstrumentations?: InstrumentationName[];

  // Session tracking configuration
  sessionInactivityTimeoutMillis?: number;
  sessionTerminationTimeoutMillis?: number;

  // Trace propagation configuration
  propagators?: PropagatorConfig[];
  propagateTraceHeadersCorsURLs?: RegExp[];

  // Filtering and scrubbing
  ignoreUrls?: RegExp[];
  ignoreErrorMessages?: RegExp[];
  urlAttributeScrubber?: UrlAttributeScrubber;

  // Error tracking options
  wrapEventHandlers?: boolean;
  wrapTimers?: boolean;

  // HTTP instrumentation options
  maxWaitForResourceTimingsMillis?: number;
  maxToleranceForResourceTimingsMillis?: number;
  headersToCapture?: RegExp[];

  // Page view instrumentation
  pageViewInstrumentation?: PageViewInstrumentationSettings;

  // Additional attributes
  additionalSignalAttributes?: Record<string, AttributeValueType | AnyValue>;

  // Transport options
  enableTransportCompression?: boolean;
}

Usage Example:

import { init } from "@dash0/sdk-web";

init({
  serviceName: "my-website",
  serviceVersion: "1.2.3",
  environment: "production",
  endpoint: {
    url: "https://ingress.dash0.com",
    authToken: "auth_your_token_here",
  },
  additionalSignalAttributes: {
    "app.region": "us-east-1",
    "app.tier": "premium",
  },
});

Multiple Endpoints:

init({
  serviceName: "my-website",
  endpoint: [
    {
      url: "https://primary.dash0.com",
      authToken: "auth_primary_token",
      dataset: "production",
    },
    {
      url: "https://backup.monitoring.com",
      authToken: "auth_backup_token",
    },
  ],
});

Critical Behavior:

  • Initialization is synchronous but sets up asynchronous telemetry collection
  • If called multiple times, behavior is undefined (may override or merge configuration)
  • Must be called before other SDK functions for proper operation
  • If called after page load, some automatic instrumentations may miss early events
  • Missing serviceName or endpoint may cause initialization to fail
  • Invalid endpoint URLs may cause telemetry transmission failures
  • Network failures during initialization do not prevent SDK from operating
  • Configuration validation occurs synchronously during initialization
  • Invalid configuration values may be ignored, clamped, or cause errors

Configuration Types

Endpoint Configuration

interface Endpoint {
  /** OTLP HTTP URL excluding the /v1/* prefix */
  url: string;
  /** Authorization token (placed in Authorization: Bearer header) */
  authToken: string;
  /** Optional dataset specification */
  dataset?: string;
}

Critical Behavior:

  • URL must be a valid HTTP/HTTPS URL
  • URL should not include the /v1/traces or /v1/logs path segments
  • Auth token is sent in Authorization: Bearer {token} header
  • If multiple endpoints are provided, telemetry is sent to all endpoints
  • If endpoint URL is invalid, telemetry transmission may fail silently
  • Network errors do not prevent SDK from continuing to operate
  • Invalid auth tokens may cause 401/403 errors; telemetry may be dropped
  • Endpoints are processed in order; failures in one endpoint do not affect others
  • Very long URLs or tokens may cause transmission issues
  • Empty strings for URL or authToken may cause initialization failure

Instrumentation Names

type InstrumentationName =
  | "@dash0/navigation"
  | "@dash0/web-vitals"
  | "@dash0/error"
  | "@dash0/fetch";

The available instrumentations are:

  • @dash0/navigation - Page view and navigation timing
  • @dash0/web-vitals - Core Web Vitals metrics (CLS, INP, LCP)
  • @dash0/error - Automatic error tracking
  • @dash0/fetch - HTTP request instrumentation

Usage Example:

init({
  serviceName: "my-website",
  endpoint: { url: "...", authToken: "..." },
  enabledInstrumentations: ["@dash0/navigation", "@dash0/error"],
});

Critical Behavior:

  • If enabledInstrumentations is not provided, all instrumentations are enabled by default
  • If an invalid instrumentation name is provided, it is ignored
  • Disabling an instrumentation prevents it from collecting data but does not affect other instrumentations
  • Instrumentations are initialized after init() completes
  • Instrumentations cannot be enabled/disabled after initialization
  • Disabled instrumentations do not consume resources
  • Empty array disables all instrumentations (not recommended)

Propagator Configuration

Configure trace context propagators for distributed tracing across services.

type PropagatorType = "traceparent" | "xray";

interface PropagatorConfig {
  type: PropagatorType;
  match: RegExp[];
}
  • traceparent - W3C TraceContext headers for OpenTelemetry-compatible services
  • xray - AWS X-Ray headers for AWS services

Same-origin behavior: All same-origin requests automatically receive traceparent headers plus headers for ALL other configured propagator types, regardless of match patterns.

Cross-origin behavior: For cross-origin requests, only matching propagators are applied. Multiple propagators can match the same URL to send both headers.

Usage Example:

init({
  serviceName: "my-website",
  endpoint: { url: "...", authToken: "..." },
  propagators: [
    // W3C traceparent for internal API
    { type: "traceparent", match: [/.*\/api\/internal.*/] },
    // AWS X-Ray for AWS services
    { type: "xray", match: [/.*\.amazonaws\.com.*/] },
    // Both headers for specific endpoints
    { type: "traceparent", match: [/.*\/api\/special.*/] },
    { type: "xray", match: [/.*\/api\/special.*/] },
  ],
});

Important: Cross-origin endpoints must include the appropriate headers in their Access-Control-Allow-Headers response:

  • traceparent for W3C trace context
  • X-Amzn-Trace-Id for AWS X-Ray

Critical Behavior:

  • Same-origin requests always get traceparent headers regardless of match patterns
  • Cross-origin requests only get headers if URL matches at least one propagator pattern
  • Multiple propagators can match the same URL (both headers are sent)
  • If no propagators match a cross-origin URL, no trace headers are sent
  • Invalid propagator types are ignored
  • Empty match arrays result in no headers for cross-origin requests
  • Invalid RegExp patterns may cause errors or be ignored
  • Propagator matching occurs for every HTTP request; complex patterns may impact performance
  • Headers are added to request before it is sent; modifying headers after SDK initialization may not work

URL Attribute Scrubber

Custom function to scrub sensitive information from URL attributes before transmission.

type UrlAttributeScrubber = (attr: UrlAttributeRecord) => UrlAttributeRecord;

interface UrlAttributeRecord {
  "url.full": string;
  "url.path"?: string;
  "url.domain"?: string;
  "url.scheme"?: string;
  "url.fragment"?: string;
  "url.query"?: string;
}

Usage Example:

init({
  serviceName: "my-website",
  endpoint: { url: "...", authToken: "..." },
  urlAttributeScrubber: (attrs) => {
    // Redact sensitive query parameters
    if (attrs["url.query"]?.includes("token=")) {
      attrs["url.query"] = attrs["url.query"].replace(/token=[^&]+/, "token=REDACTED");
    }
    return attrs;
  },
});

Critical Behavior:

  • Scrubber is called for all URLs before transmission
  • Scrubber must return a UrlAttributeRecord object
  • If scrubber throws an error, original attributes may be used or transmission may fail
  • Scrubber is called synchronously during telemetry collection
  • Modifying the input object directly is allowed (mutating is safe)
  • Scrubber is called for every URL; performance-sensitive operations should be optimized
  • Returning undefined or null may cause errors
  • Scrubber can add, modify, or remove URL attributes
  • Very slow scrubber functions may impact telemetry collection performance

Page View Instrumentation Settings

Configure page view tracking behavior for single-page applications.

interface PageViewInstrumentationSettings {
  /** Function to generate custom page metadata based on URL */
  generateMetadata?: (url: URL) => PageViewMeta | undefined;
  /** Track virtual page views via history API (default: true) */
  trackVirtualPageViews?: boolean;
  /** URL parts that trigger virtual page views */
  includeParts?: Array<"HASH" | "SEARCH">;
}

interface PageViewMeta {
  /** Page title (defaults to document.title) */
  title?: string;
  /** Additional page attributes */
  attributes?: Record<string, AttributeValueType | AnyValue>;
}

Usage Example:

init({
  serviceName: "my-website",
  endpoint: { url: "...", authToken: "..." },
  pageViewInstrumentation: {
    trackVirtualPageViews: true,
    includeParts: ["HASH", "SEARCH"],
    generateMetadata: (url) => {
      if (url.pathname.startsWith("/product/")) {
        return {
          title: "Product Page",
          attributes: {
            "page.category": "product",
            "page.id": url.pathname.split("/")[2],
          },
        };
      }
      return undefined;
    },
  },
});

Critical Behavior:

  • generateMetadata is called for each page view (physical and virtual)
  • If generateMetadata returns undefined, default metadata is used
  • If generateMetadata throws an error, default metadata is used
  • trackVirtualPageViews: false disables virtual page view tracking
  • includeParts controls which URL changes trigger virtual page views
  • Hash changes trigger virtual page views only if "HASH" is in includeParts
  • Search parameter changes trigger virtual page views only if "SEARCH" is in includeParts
  • generateMetadata is called synchronously; slow functions may impact performance
  • Invalid URL objects passed to generateMetadata may cause errors
  • generateMetadata can be called multiple times per page load for virtual page views

Configuration Defaults

Session Timeouts

sessionInactivityTimeoutMillis: 10800000  // 3 hours
sessionTerminationTimeoutMillis: 21600000 // 6 hours

Maximum allowed timeout: 24 hours (86400000 ms)

Critical Behavior:

  • Timeouts exceeding 24 hours are clamped to 24 hours
  • Timeouts less than 0 are treated as invalid (may use default or cause error)
  • Timeouts are stored in browser storage and persist across page loads
  • If storage is unavailable, timeouts may not persist
  • Timeout values are validated during initialization
  • Very small timeout values (< 1000ms) may cause frequent session resets
  • Timeout precision is limited to milliseconds

Error Tracking

wrapEventHandlers: true  // Auto-wrap DOM event handlers
wrapTimers: true         // Auto-wrap setTimeout/setInterval

Note: Wrapping improves error tracking for cross-origin errors but may affect performance.

Critical Behavior:

  • Wrapping occurs during initialization
  • Wrapped functions may have slightly different behavior than originals
  • Wrapping may interfere with some libraries that rely on native function identity
  • Disabling wrapping reduces error tracking coverage but improves performance
  • Wrapping cannot be changed after initialization
  • Wrapped functions maintain original behavior but add error tracking
  • Some edge cases may not be caught by wrapped functions

HTTP Request Instrumentation

maxWaitForResourceTimingsMillis: 10000      // 10 seconds
maxToleranceForResourceTimingsMillis: 50    // 50 milliseconds

Critical Behavior:

  • Resource timing data may not be available immediately after request completes
  • SDK waits up to maxWaitForResourceTimingsMillis for timing data
  • maxToleranceForResourceTimingsMillis is the tolerance for timing accuracy
  • If timing data is not available within the wait period, request is still tracked without full timing data
  • Very short wait times may miss timing data
  • Very long wait times may delay telemetry transmission
  • Timing data availability depends on browser and resource type

Page View Tracking

pageViewInstrumentation: {
  trackVirtualPageViews: true,
  includeParts: [],
}

Critical Behavior:

  • Empty includeParts means only pathname changes trigger virtual page views
  • Hash and search parameter changes are ignored if not in includeParts
  • Virtual page views are tracked via pushState and replaceState API calls
  • Virtual page views are not tracked for hashchange events unless "HASH" is in includeParts
  • Virtual page views may be tracked multiple times if URL changes rapidly
  • Virtual page view tracking requires History API support

Transport

enableTransportCompression: false  // Experimental: gzip compression

Critical Behavior:

  • Compression is experimental and may not be available in all environments
  • Compression reduces payload size but increases CPU usage
  • Compression may fail silently if not supported
  • Compression is applied per request; very large payloads may take time to compress
  • Compression may not be beneficial for very small payloads

Auto-Detection

Certain configuration values can be auto-detected when using specific cloud providers:

Vercel

Requires Next.js. Auto-detected from environment variables:

Configuration KeyEnvironment Variable
environmentNEXT_PUBLIC_VERCEL_ENV
deploymentNameNEXT_PUBLIC_VERCEL_TARGET_ENV
deploymentIdNEXT_PUBLIC_VERCEL_BRANCH_URL

Critical Behavior:

  • Auto-detection only works in Next.js applications
  • Auto-detection occurs during initialization
  • If environment variables are not set, values remain undefined
  • Explicit configuration values override auto-detected values
  • Auto-detection only works for specific environment variable names
  • Auto-detection may not work in all Next.js deployment scenarios

Edge Cases and Error Conditions

Initialization Timing

  • Early Initialization: If init() is called in <head> before DOM is ready, some DOM-based instrumentations may not work
  • Late Initialization: If init() is called after page load, early events (e.g., navigation timing) may be missed
  • Multiple Initialization: Calling init() multiple times may override previous configuration or cause undefined behavior
  • Concurrent Initialization: If init() is called from multiple scripts simultaneously, race conditions may occur
  • Initialization During Page Unload: If init() is called during page unload, initialization may not complete
  • Initialization in iframe: If init() is called in an iframe, behavior may differ from main page

Configuration Validation

  • Missing Required Fields: If serviceName or endpoint is missing, initialization may fail silently or throw an error
  • Invalid URLs: Invalid endpoint URLs may cause telemetry transmission failures
  • Invalid Regex: Invalid RegExp patterns in ignoreUrls, ignoreErrorMessages, or propagators may cause errors
  • Invalid Timeouts: Negative or extremely large timeout values may be clamped or cause errors
  • Invalid Instrumentation Names: Invalid instrumentation names are ignored; no error is thrown
  • Invalid Propagator Types: Invalid propagator types are ignored; no error is thrown
  • Invalid Attribute Values: Invalid attribute values in additionalSignalAttributes may be ignored or cause errors
  • Circular References: Circular references in configuration objects may cause serialization errors

Network and Transmission

  • Network Failures: SDK continues to operate even if endpoint is unreachable; telemetry may be queued or dropped
  • CORS Errors: Cross-origin requests may fail if CORS headers are not properly configured
  • Authentication Failures: Invalid auth tokens may cause 401/403 errors; telemetry may be dropped
  • Rate Limiting: Endpoints may rate limit requests; SDK may retry or drop telemetry
  • Slow Network: Very slow network connections may cause telemetry queuing and memory issues
  • Network Interruption: Network interruptions during transmission may cause partial data loss
  • DNS Failures: DNS resolution failures may prevent telemetry transmission
  • SSL/TLS Errors: SSL/TLS errors may prevent telemetry transmission

Browser Compatibility

  • Storage Unavailable: If localStorage/sessionStorage is unavailable, session persistence is lost
  • API Unavailable: If required browser APIs (e.g., fetch, Performance API) are unavailable, some features may not work
  • Browser Extensions: Ad blockers or privacy extensions may interfere with telemetry collection
  • Content Security Policy: Strict CSP may block telemetry transmission or SDK initialization
  • Browser Restart: Browser restart may clear in-memory data but preserves storage-based data
  • Private Browsing: Private browsing mode may disable storage, causing session reset on each page load
  • Browser Updates: Browser updates may change API behavior, affecting SDK operation

Scrubber and Filtering

  • Scrubber Errors: If urlAttributeScrubber throws an error, original attributes may be used or transmission may fail
  • Filter Performance: Complex regex patterns in ignoreUrls or ignoreErrorMessages may impact performance
  • Filter Matching: URLs and error messages are matched against all patterns; first match determines behavior
  • Invalid Regex Patterns: Invalid regex patterns may cause errors or be ignored
  • Very Long Patterns: Very long regex patterns may impact performance
  • Case Sensitivity: Regex pattern matching respects case sensitivity settings

Multiple Endpoints

  • Endpoint Failures: If one endpoint fails, telemetry is still sent to other endpoints
  • Endpoint Ordering: Endpoints are processed in order; order may affect performance
  • Partial Failures: Partial endpoint failures do not affect other endpoints
  • Endpoint Timeouts: Endpoint timeouts may cause telemetry to be dropped for that endpoint
  • Endpoint Configuration: Invalid endpoint configurations are ignored; no error is thrown
  • Very Many Endpoints: Very many endpoints may impact performance and memory usage

Performance Considerations

  • Initialization Overhead: Initialization has minimal overhead but may impact page load time
  • Telemetry Collection: Telemetry collection has minimal overhead but may impact performance with high volume
  • Storage Operations: Storage operations are synchronous and may block if storage is slow
  • Regex Matching: Complex regex patterns may impact performance for every request/error
  • Scrubber Performance: Slow scrubber functions may impact telemetry collection performance
  • Memory Usage: Queued telemetry may increase memory usage if transmission is slow