This SDK enables users of dash0's web monitoring features to instrument a website or single-page-application to capture and transmit telemetry to dash0.
Features include:
- Page view instrumentation
- Navigation timing instrumentation
- HTTP request instrumentation
- Error tracking
The SDK is currently only distributed as an npm package, additional distribution formats will be added in the future. Should you need a currently unavailable format, let us know by creating a github issue or via support@dash0.com.
You'll need a couple of prequesites before you can start:
- An active dash0 account. Sign Up
- An Auth Token
Auth tokens for client monitoring will be public as part of your website, please make sure to:
- Use a separate token, exclusively for web monitoring
- Limit the dataset to the dataset you want to ingest to
- Limit permissions to
Ingesting
- The Endpoint url for your dash0 region. You can find it via
Organization Settings > Endpoints > OTLP via HTTP
.
-
Add the SDK to your dependencies
# npm npm install @dash0hq/sdk-web # yarn yarn add @dash0hq/sdk-web
-
Initialize the sdk In order to initialize the sdk you'll need to call the
init
function at a convenient time in your applications lifecycle. Ideally this should happen as early as possible, as most instrumentations can only observe events after init has been called.import { init } from "@dash0hq/sdk-web"; init({ serviceName: "my-website", endpoint: { // Replace this with the endpoint url identified during preparation url: "http://example.com", // Replace this with your auth token you created earlier // Ideally inject the value at build time to not commit the token to git, even if its effectively public authToken: "you-auth-token-goes-here", }, });
The following configuration options are available, in order to customize the behaviour of the sdk.
These can all be passed via the sdk's init
call.
Backend Correlation for HTTP requests is by default only enabled for endpoints that share the same origin as the website.
Note
Misconfiguration of cross origin trace correlation can lead to request failures. Please make sure to carefully validate the configuration provided in the next steps
If you want to enable correlation for cross-origin requests you have to follow these steps:
- Make sure the endpoints respond to
OPTIONS
requests and includetraceparent
in theirAccess-Control-Allow-Headers
response header. - Include a regex matching the endpoint you want to enable in the propagateTraceHeadersCorsURLs configuration option.
Certain configuration values can be auto-detected if using the module version of the SDK in combination with certain cloud providers.
This currently also requires the use of Next.js
Configuration Key | Source |
---|---|
environment | NEXT_PUBLIC_VERCEL_ENV |
deploymentName | NEXT_PUBLIC_VERCEL_TARGET_ENV |
deploymentId | NEXT_PUBLIC_VERCEL_BRANCH_URL |
- Ignore URLs
key:ignoreUrls
type:Array<RegExp>
optional:true
default:undefined
An array of URL regular expression for which no data should be collected. These regular expressions are evaluated against the document, XMLHttpRequest, fetch and resource URLs.
- Service Name
key:serviceName
type:string
optional:false
The logical name or your website, maps to the service.name otel attribute. - Service Version
key:serviceVersion
type:string
optional:true
default:undefined
The current version of your website, maps to the service.version otel attribute. - Environment
key:environment
type:string
optional:true
default:undefined
Name of the deployment environment, for examplestaging
, orproduction
. Maps to the deployment.environment.name otel attribute. This value is auto detected in certain build environments. - Deployment Name
key:deploymentName
type:string
optional:true
default:undefined
Name of the deployment, maps to the deployment.name otel attribute. This value is auto detected in certain build environments. - Deployment Id
key:deploymentId
type:string
optional:true
default:undefined
Id of the deployment, aps to the deployment.id otel attribute. This value is auto detected in certain build environments. - Additional Signal Attributes
key:additionalSignalAttributes
type:Record<string, AttributeValueType | AnyValue>
optional:true
default:undefined
Allows the configuration of additional attributes to be included with any transmitted event. See AttributeValueType and AnyValue for detailed types.
- Endpoint
key:endpoint
type:Endpoint | Endpoint[]
optional:false
The OTLP to which the generated telemtetry should be sent. Supports multiple endpoints in parallel if an array is provided. - Endpoint URL
key:endpoint.url
type:string
optional:false
The OTLP HTTP URL of the endpoint, not including the/v1/*
part of the path - Endpoint Auth Token
key:endpoint.authToken
type:string
optional:false
The auth token used for the endpoint. Will be placed intoAuthorization: Bearer {auth_token}
header. - Endpoint Dataset
key:endpoint.dataset
type:string
optional:true
Optionally specify what dataset should be placed into. Can also be configured within Dash0 through the auth token.
- Session Inactivity Timeout
key:sessionInactivityTimeoutMillis
type:number
optional:true
default:10800000
(3 hours)
The session inactivity timeout. Session inactivity is the maximum allowed time to pass between two page loads before the session is considered to be expired. The maximum value is the maximum session duration of 24 hours. - Session Termination Timeout
key:sessionTerminationTimeoutMillis
type:number
optional:true
default:21600000
(6 hours)
The default session termination timeout. Session termination is the maximum allowed time to pass since session start before the session is considered to be expired.
- Ignore Error Messages
key:ignoreErrorMessages
type:Array<RegExp>
optional:true
default:undefined
An array of error message regular expressions for which no data should be collected. - Wrap Event Handlers
key:wrapEventHandlers
type:boolean
optional:true
default:true
Whether we should automatically wrap DOM event handlers added via addEventlistener for improved uncaught error tracking. This results in improved uncaught error tracking for cross-origin errors, but may have adverse effects on website performance and stability. - Wrap Timers
key:wrapTimers
type:boolean
optional:true
default:true
Whether we should automatically wrap timers added via setTimeout / setInterval for improved uncaught error tracking. This results in improved uncaught error tracking for cross-origin errors, but may have adverse effects on website performance and stability.
- Propagate Trace Header Cors URLs
key:propagateTraceHeadersCorsURLs
type:Array<RegExp>
optional:true
default:undefined
An array of URL regular expressions for which trace context headers should be sent across origins by http client instrumentations. NOTE: Any cross origin endpoints allowed via this option need to includetraceparent
in theAccess-Control-Allow-Headers
response header. Misconfiguration will cause request failures! - Max Wait For Resource Timings
key:maxWaitForResourceTimingsMillis
type:number
optional:true
default:10000
How long to wait after an XMLHttpRequest or fetch request has finished for the retrieval of resource timing data. Performance timeline events are placed on the low priority task queue and therefore high values might be necessary. - Max Tolerance For Resource Timings
key:maxToleranceForResourceTimingsMillis
type:number
optional:true
default:3000
The number of milliseconds of tolerance between resolution of a http request promise and the end time of performanceEntries applied when matching a request to its respective performance entry. A higher value might increase match frequency at the cost of potential incorrect matches. Matching is performed based on request timing and url. - Headers to Capture
key:headersToCapture
type:Array<RegExp>
optional:true
default:undefined
A set of regular expressions that will be matched against HTTP request headers, to be captured inXMLHttpRequest
andfetch
Instrumentations. These headers will be transferred as span attributes.
- Provide Page Metadata
key:pageViewInstrumentation.generateMetadata
type:(url: URL) => PageViewMeta | undefined
optional:true
default:undefined
Allows websites to dynamically provide page metadata based on the current url. Metadata may include the page title and a set of attributes. See PageViewMeta for detailed type information. - Track Virtual Page Views
key:pageViewInstrumentation.trackVirtualPageViews
type:boolean
optional:true
default:true
Whether the sdk should track virtual page views by instrumenting the history api. Only relevant for websites utilizing virtual navigation. - Track Url Part Changes
key:pageViewInstrumentation.includeParts
type:Array<"HASH" | "SEARCH">
optional:true
default:[]
Additionally generate virtual page views when these url parts change.- "HASH" changes to the urls hash / fragment
- "SEARCH" changes to the urls search / query parameters
The SDK provides several API functions to help you customize telemetry collection and add contextual information to your signals.
Functions for managing custom attributes that are included with all signals.
Adds a signal attribute to be transmitted with every signal.
Parameters:
name
(string): The attribute namevalue
(AttributeValueType | AnyValue): The attribute value
Example:
import { addSignalAttribute } from "@dash0hq/sdk-web";
addSignalAttribute("environment", "production");
addSignalAttribute("version", "1.2.3");
Note: If you need to ensure attributes are included with signals transmitted on initial page load, use the additionalSignalAttributes
property in the init()
call instead.
Removes a previously added signal attribute.
Parameters:
name
(string): The attribute name to remove
Example:
import { removeSignalAttribute } from "@dash0hq/sdk-web";
removeSignalAttribute("environment");
Associates user information with telemetry signals. See OTEL User Attributes for the matching attributes
Parameters:
id
(string, optional): User identifieropts
(object, optional): Additional user informationname
(string, optional): Short name or login/username of the userfullName
(string, optional): User's full nameemail
(string, optional): User email addresshash
(string, optional): Unique user hash to correlate information for a user in anonymized form.roles
(string[], optional): User roles
Example:
import { identify } from "@dash0hq/sdk-web";
identify("user123", {
name: "johndoe",
fullName: "John Doe",
email: "john@example.com",
roles: ["admin", "user"],
});
Sends a custom event with optional data and attributes. Event name cannot be one of the event names internally used by the SDK. See Event Names
Parameters:
name
(string): Event nameopts
(object, optional): Event optionstitle
(string, optional): Human readable title for the event. Should summarize the event in a single short sentence.timestamp
(number | Date, optional): Event timestampdata
(AttributeValueType | AnyValue, optional): Event dataattributes
(Record<string, AttributeValueType | AnyValue>, optional): Event attributesseverity
(LOG_SEVERITY_TEXT, optional): Log severity level
Example:
import { sendEvent } from "@dash0hq/sdk-web";
sendEvent("user_action", {
data: "button_clicked",
attributes: {
buttonId: "submit-form",
page: "/checkout",
},
severity: "INFO",
});
Manually reports an error to be tracked in telemetry.
Parameters:
error
(string | ErrorLike): Error message or error objectopts
(object, optional): Error reporting optionscomponentStack
(string | null | undefined): Component stack trace for React errors
Example:
import { reportError } from "@dash0hq/sdk-web";
// Report a string error
reportError("Something went wrong in user flow");
// Report an Error object
try {
// Some operation
} catch (error) {
reportError(error);
}
// Report with component stack (useful for React)
reportError(error, {
componentStack: getComponentStack(),
});
Manually terminates the current user session.
Example:
import { terminateSession } from "@dash0hq/sdk-web";
// Terminate session on user logout
function handleLogout() {
terminateSession();
// Additional logout logic
}
Note: Sessions are automatically managed by the SDK based on inactivity and termination timeouts configured during initialization. Manual termination is typically only needed for explicit user logout scenarios.
This project follows the Semantic Versioning scheme MAJOR.MINOR.PATH
.
In this means:
MAJOR
versions are released for significant changes in operation or backward incompatible API changes.MINOR
versions add functionality in a backward compatible manner.PATCH
versions include bug and security fixes which do not break backward compatibility.
We automatically release new versions of this package whenever a PR is merged to main and the ci is able to detect a valid version increase from the merge commit. It uses conventional commits to calculate the version increase and to generate additional messaging such as changelogs. Please make sure PR merge commits are formatted accordingly, not matching messages will create a PATCH release, but no changelog entry. Examples:
-
A
PATCH
release:fix: Include missing user.name attribute
-
A
MINOR
release:feat: Add instrumentation for fetch() The sdk now supports automatic instrumentation of the fetch api
-
A
MAJOR
release:feat: Add version two of page-load instrumentation BREAKING CHANGE: This adds a new updated instrumentation for page-loads, it is no longer compatible with the previous version. For instructions on how to update see: https://example.com
or:
feat!: Add version two of page-load instrumentation This adds a new updated instrumentation for page-loads, it is no longer compatible with the previous version. For instructions on how to update see: https://example.com
-
NO changelog entry, PATCH release:
chore: Improve spelling of README
We run e2e tests via webdriverIO and lambda test.
They currently don't have a fully local setup, but tests can be executed locally targeting chrome headless via pnpm run test:e2e:local
.
- Get a labmda test account
- Create a
.env
file based on.env.example
and provide your lambda test credentials. - Run the tests via
pnpm run test:e2e
We need multiple ports to properly test cors behaviour.