@dash0hq/sdk-web
v0.6.1
Published
Dash0's Web SDK to collect telemetry from end-users' web browsers
Readme
Dash0 Web SDK
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
Getting Started
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 [email protected].
Before you begin
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.
Installation
Via package
Add the SDK to your dependencies
# npm npm install @dash0hq/sdk-web # yarn yarn add @dash0hq/sdk-webInitialize the sdk In order to initialize the sdk you'll need to call the
initfunction 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", }, });
Configuration
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
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
OPTIONSrequests and includetraceparentin theirAccess-Control-Allow-Headersresponse header. - Include a regex matching the endpoint you want to enable in the propagateTraceHeadersCorsURLs configuration option.
Configuration auto detection
Certain configuration values can be auto-detected if using the module version of the SDK in combination with certain cloud providers.
Vercel
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 |
Configuration Overview
General
- Ignore URLs
key:
ignoreUrlstype:Array<RegExp>optional:truedefault:undefinedAn 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.
Website Details and Attributes
- Service Name
key:
serviceNametype:stringoptional:falseThe logical name or your website, maps to the service.name otel attribute. - Service Version
key:
serviceVersiontype:stringoptional:truedefault:undefinedThe current version of your website, maps to the service.version otel attribute. - Environment
key:
environmenttype:stringoptional:truedefault:undefinedName 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:
deploymentNametype:stringoptional:truedefault:undefinedName of the deployment, maps to the deployment.name otel attribute. This value is auto detected in certain build environments. - Deployment Id
key:
deploymentIdtype:stringoptional:truedefault:undefinedId of the deployment, aps to the deployment.id otel attribute. This value is auto detected in certain build environments. - Additional Signal Attributes
key:
additionalSignalAttributestype:Record<string, AttributeValueType | AnyValue>optional:truedefault:undefinedAllows the configuration of additional attributes to be included with any transmitted event. See AttributeValueType and AnyValue for detailed types.
OTLP Endpoint
- Endpoint
key:
endpointtype:Endpoint | Endpoint[]optional:falseThe OTLP to which the generated telemtetry should be sent. Supports multiple endpoints in parallel if an array is provided. - Endpoint URL
key:
endpoint.urltype:stringoptional:falseThe OTLP HTTP URL of the endpoint, not including the/v1/*part of the path - Endpoint Auth Token
key:
endpoint.authTokentype:stringoptional:falseThe auth token used for the endpoint. Will be placed intoAuthorization: Bearer {auth_token}header. - Endpoint Dataset
key:
endpoint.datasettype:stringoptional:trueOptionally specify what dataset should be placed into. Can also be configured within Dash0 through the auth token.
Session Tracking
- Session Inactivity Timeout
key:
sessionInactivityTimeoutMillistype:numberoptional:truedefault: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:
sessionTerminationTimeoutMillistype:numberoptional:truedefault: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.
Error tracking
- Ignore Error Messages
key:
ignoreErrorMessagestype:Array<RegExp>optional:truedefault:undefinedAn array of error message regular expressions for which no data should be collected. - Wrap Event Handlers
key:
wrapEventHandlerstype:booleanoptional:truedefault:trueWhether 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:
wrapTimerstype:booleanoptional:truedefault:trueWhether 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.
HTTP request instrumentation
- Propagate Trace Header Cors URLs
key:
propagateTraceHeadersCorsURLstype:Array<RegExp>optional:truedefault:undefinedAn 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 includetraceparentin theAccess-Control-Allow-Headersresponse header. Misconfiguration will cause request failures! - Max Wait For Resource Timings
key:
maxWaitForResourceTimingsMillistype:numberoptional:truedefault:10000How 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:
maxToleranceForResourceTimingsMillistype:numberoptional:truedefault:3000The 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:
headersToCapturetype:Array<RegExp>optional:truedefault:undefinedA set of regular expressions that will be matched against HTTP request headers, to be captured inXMLHttpRequestandfetchInstrumentations. These headers will be transferred as span attributes.
Page view instrumentation
- Provide Page Metadata
key:
pageViewInstrumentation.generateMetadatatype:(url: URL) => PageViewMeta | undefinedoptional:truedefault:undefinedAllows 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.trackVirtualPageViewstype:booleanoptional:truedefault:trueWhether 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.includePartstype:Array<"HASH" | "SEARCH">optional:truedefault:[]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
API
The SDK provides several API functions to help you customize telemetry collection and add contextual information to your signals.
Signal attributes
Functions for managing custom attributes that are included with all signals.
addSignalAttribute(name, value)
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.
removeSignalAttribute(name)
Removes a previously added signal attribute.
Parameters:
name(string): The attribute name to remove
Example:
import { removeSignalAttribute } from "@dash0hq/sdk-web";
removeSignalAttribute("environment");User identification
identify(id, opts)
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: "[email protected]",
roles: ["admin", "user"],
});Custom Events
sendEvent(name, opts)
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",
});Error Reporting
reportError(error, opts)
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(),
});Session Management
terminateSession()
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.
Development
Releases
This project follows the Semantic Versioning scheme MAJOR.MINOR.PATH.
In this means:
MAJORversions are released for significant changes in operation or backward incompatible API changes.MINORversions add functionality in a backward compatible manner.PATCHversions 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
PATCHrelease:fix: Include missing user.name attributeA
MINORrelease:feat: Add instrumentation for fetch() The sdk now supports automatic instrumentation of the fetch apiA
MAJORrelease: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.comor:
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.comNO changelog entry, PATCH release:
chore: Improve spelling of README
E2E Tests
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.
Setup
- Get a labmda test account
- Create a
.envfile based on.env.exampleand provide your lambda test credentials. - Run the tests via
pnpm run test:e2e
Why do tests run on ports 8010, 8011 and 8012?
We need multiple ports to properly test cors behaviour.
