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:
<head> section or immediately after opening <body> tagInitializes 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:
serviceName or endpoint may cause initialization to failinterface 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:
/v1/traces or /v1/logs path segmentsAuthorization: Bearer {token} headertype 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 instrumentationUsage Example:
init({
serviceName: "my-website",
endpoint: { url: "...", authToken: "..." },
enabledInstrumentations: ["@dash0/navigation", "@dash0/error"],
});Critical Behavior:
enabledInstrumentations is not provided, all instrumentations are enabled by defaultinit() completesConfigure 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 servicesxray - AWS X-Ray headers for AWS servicesSame-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 contextX-Amzn-Trace-Id for AWS X-RayCritical Behavior:
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:
UrlAttributeRecord objectConfigure 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)generateMetadata returns undefined, default metadata is usedgenerateMetadata throws an error, default metadata is usedtrackVirtualPageViews: false disables virtual page view trackingincludeParts controls which URL changes trigger virtual page views"HASH" is in includeParts"SEARCH" is in includePartsgenerateMetadata is called synchronously; slow functions may impact performancegenerateMetadata may cause errorsgenerateMetadata can be called multiple times per page load for virtual page viewssessionInactivityTimeoutMillis: 10800000 // 3 hours
sessionTerminationTimeoutMillis: 21600000 // 6 hoursMaximum allowed timeout: 24 hours (86400000 ms)
Critical Behavior:
wrapEventHandlers: true // Auto-wrap DOM event handlers
wrapTimers: true // Auto-wrap setTimeout/setIntervalNote: Wrapping improves error tracking for cross-origin errors but may affect performance.
Critical Behavior:
maxWaitForResourceTimingsMillis: 10000 // 10 seconds
maxToleranceForResourceTimingsMillis: 50 // 50 millisecondsCritical Behavior:
maxWaitForResourceTimingsMillis for timing datamaxToleranceForResourceTimingsMillis is the tolerance for timing accuracypageViewInstrumentation: {
trackVirtualPageViews: true,
includeParts: [],
}Critical Behavior:
includeParts means only pathname changes trigger virtual page viewsincludePartspushState and replaceState API callshashchange events unless "HASH" is in includePartsenableTransportCompression: false // Experimental: gzip compressionCritical Behavior:
Certain configuration values can be auto-detected when using specific cloud providers:
Requires Next.js. Auto-detected from environment variables:
| Configuration Key | Environment Variable |
|---|---|
environment | NEXT_PUBLIC_VERCEL_ENV |
deploymentName | NEXT_PUBLIC_VERCEL_TARGET_ENV |
deploymentId | NEXT_PUBLIC_VERCEL_BRANCH_URL |
Critical Behavior:
init() is called in <head> before DOM is ready, some DOM-based instrumentations may not workinit() is called after page load, early events (e.g., navigation timing) may be missedinit() multiple times may override previous configuration or cause undefined behaviorinit() is called from multiple scripts simultaneously, race conditions may occurinit() is called during page unload, initialization may not completeinit() is called in an iframe, behavior may differ from main pageserviceName or endpoint is missing, initialization may fail silently or throw an errorignoreUrls, ignoreErrorMessages, or propagators may cause errorsadditionalSignalAttributes may be ignored or cause errorsurlAttributeScrubber throws an error, original attributes may be used or transmission may failignoreUrls or ignoreErrorMessages may impact performance