### Install Dash0 Web SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/README.md
Add the SDK to your project dependencies using npm, yarn, or pnpm.
```sh
# npm
npm install @dash0/sdk-web
# yarn
yarn add @dash0/sdk-web
# pnpm
pnpm install @dash0/sdk-web
```
--------------------------------
### Install Dash0 Web SDK via npm or yarn
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Add the Dash0 Web SDK to your project dependencies using your preferred package manager.
```sh
# npm
npm install @dash0/sdk-web
# yarn
yarn add @dash0/sdk-web
```
--------------------------------
### Run E2E Tests
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Execute end-to-end tests using the configured setup. Requires a LambdaTest account and credentials in the .env file.
```bash
pnpm run test:e2e
```
--------------------------------
### Build All Project
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Build all components and packages within the project. This is typically the first step before testing or deployment.
```bash
pnpm run build
```
--------------------------------
### Initialize Dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/00-page-load/empty.html
Initializes the Dash0 SDK with service details, environment, and endpoint configuration. Use this to set up the SDK for tracking.
```javascript
function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("setActiveLogLevel", "debug");
dash0("init", {
serviceName: "dash0.com",
serviceVersion: "1.2.3",
environment: "prod",
additionalSignalAttributes: {
the_answer: 42,
},
endpoint: {
url: `http://${window.location.hostname}:8011?cors=true`,
authToken: "auth_abc123",
dataset: "production",
},
pageViewInstrumentation: {
generateMetadata: (url) => {
return {
title: url.search.includes("useCustomTitle") ? "this is a custom title" : undefined,
attributes: {
url_meta: "this is an url meta attribute",
},
};
},
},
});
```
--------------------------------
### Initialize Dash0 SDK with Script Tag
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/src/entrypoint/script-tag.html
Include this script in your HTML to initialize the Dash0 SDK. Configure it with your service name, version, environment, and endpoint details.
```javascript
(function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", { serviceName: "dash0.com", serviceVersion: "1.2.3", environment: "production", endpoint: { url: "https://ingress.eu-west-1.aws.dash0-dev.com", authToken: "auth_abc123", dataset: "production", }, });
```
--------------------------------
### Fetch With Request and Init
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a fetch request using both a Request object and an init object, demonstrating how they are merged.
```javascript
function onFetchWithRequestAndInit() {
const req = deepFreeze(new Request(`/ajax?cacheBust=${new Date().getTime()}`));
return fetch(
req,
deepFreeze({
method: "POST",
headers: new Headers({
"x-test-header": "is this test green or yellow?",
}),
})
);
}
```
--------------------------------
### Initialize dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/02-web-vitals/page.html
Initialize the dash0 SDK with service details and endpoint configuration. Ensure the serviceName, serviceVersion, and environment are correctly set. The endpoint URL is dynamically generated.
```javascript
web-vitals test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", { serviceName: "dash0.com", serviceVersion: "1.2.3", environment: "prod", endpoint: { url:
`http://${window.location.hostname}:8011?cors=true
`, authToken: "auth_abc123", dataset: "production", }, });
```
--------------------------------
### Initialize Dash0 Web SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/README.md
Initialize the SDK early in your application's lifecycle with service name and endpoint configuration. Ensure to replace placeholder values with your actual endpoint URL and auth token.
```ts
import { init } from "@dash0/sdk-web";
init({
serviceName: "my-website",
endpoint: {
// Replace this with the endpoint URL for your Dash0 region, that you retrieved earlier in "prerequisites"
url: "{OTLP via HTTP endpoint}",
// Replace this with your auth token you retrieved earlier in "prerequisites"
// Ideally, you will inject the value at build time in order not commit the token to git,
// even if its effectively public in the HTML you ship to the end user's browser
authToken: "{authToken}",
},
});
```
--------------------------------
### Initialize Dash0 SDK with Session Sampling
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/07-session-sampling/page.html
Initializes the Dash0 SDK with service details and configures session sampling based on a URL query parameter. Ensure the SDK is loaded before this script.
```javascript
session-sampling test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
const url = new URL(window.location.href);
const samplingRate = parseInt(url.searchParams.get("sampling-rate") || "100", 10);
dash0("init", {
serviceName: "dash0.com",
serviceVersion: "1.2.3",
environment: "prod",
endpoint: {
url: `http://${window.location.hostname}:8011?cors=true`,
authToken: "auth_abc123",
dataset: "production",
},
sessionSamplingRate: samplingRate,
});
```
--------------------------------
### Initialize Dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/04-events-api/page.html
Initializes the Dash0 SDK with service details and endpoint configuration. Ensure the endpoint URL is correctly formatted for your environment.
```javascript
events-api test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", { serviceName: "dash0.com", serviceVersion: "1.2.3", environment: "prod", endpoint: { url:
`http://${window.location.hostname}:8011?cors=true
`, authToken: "auth_abc123", dataset: "production", }, });
```
--------------------------------
### Initialize Dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/03-error-instrumentation/page.html
Initializes the Dash0 SDK with service details and endpoint configuration. Ensure the endpoint URL is correctly formatted for your environment.
```javascript
error-instrumentation test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", { serviceName: "dash0.com", serviceVersion: "1.2.3", environment: "prod", endpoint: { url:
`http://${window.location.hostname}:8011?cors=true
`, authToken: "auth_abc123", dataset: "production", }, });
```
--------------------------------
### Initialize Dash0 SDK with X-Ray Propagation
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Initializes the Dash0 SDK with service details, endpoint configuration, and specific propagators for X-Ray and W3C traceparent headers. Includes custom headers to capture.
```javascript
Project: /dash0hq/dash0-sdk-web
Content:
X-Ray propagation test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0"); dash0("init", { serviceName: "xray-test", serviceVersion: "1.0.0", environment: "test", endpoint: [ { url: `http://${window.location.hostname}:8011?cors=true`, authToken: "auth_xray123", dataset: "xray-testing", }, ], propagators: [ // X-Ray headers for AWS-like endpoints { type: "xray", match: [ new RegExp(`http:\/\/${window.location.hostname.replace(".", "\.")}:8012\/aws`), new RegExp(`http:\/\/${window.location.hostname.replace(".", "\.")}:8012\/aws/both`), ], }, // W3C headers for regular endpoints and cross-origin requests // Note: Same-origin requests automatically get ALL configured propagator types { type: "traceparent", match: [ new RegExp(`http:\/\/${window.location.hostname.replace(".", "\.")}:8012\/ajax`), new RegExp(`http:\/\/${window.location.hostname.replace(".", "\.")}:8012\/aws/both`), ], }, ], headersToCapture: [/x-test-header/] }); dash0("addSignalAttribute", "xray_test", true);
```
--------------------------------
### Initialize Dash0 Web SDK with Modules
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Initialize the Dash0 Web SDK early in your application's lifecycle. Ensure serviceName, endpoint URL, and authToken are correctly configured.
```javascript
import { init } from "@dash0/sdk-web";
init({
serviceName: "my-website",
endpoint: {
// Replace this with the endpoint url identified during preparation
url: "REPLACE THIS",
// Replace this with the auth token you created earlier
// Ideally, you will inject the value at build time in order to not commit the token to git,
// even if its effectively public in the HTML you ship to the end user's browser
authToken: "REPLACE THIS",
},
});
```
--------------------------------
### Initialize Dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Initializes the Dash0 SDK with service details, endpoint configuration, and various capture/ignore rules. Ensure this is called before any instrumented fetches.
```javascript
fetch instrumentation test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", {
serviceName: "dash0.com",
serviceVersion: "1.2.3",
environment: "prod",
endpoint: [
{
url: `http://${window.location.hostname}:8011?cors=true`,
authToken: "auth_abc123",
dataset: "production",
},
],
propagateTraceHeadersCorsURLs: [new RegExp(`http:\/\/${window.location.hostname.replace(".", "\\.")}:8012
)],
headersToCapture: [/x-test-header/],
ignoreUrls: [/you-cant-see-this/],
});
```
--------------------------------
### Initialize Dash0 SDK for Page View Tracking
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Initializes the Dash0 SDK with service details, environment, and page view instrumentation configuration. Includes custom logic for generating page metadata and handling URL parts.
```javascript
var d, a, s, h, z, e, r, o;
(d = window).dash0 || ((z = d[a] = function() {
h.push(arguments);
}), (z._t = new Date()), (z._v = 1), (h = z._q = []));
const url = new URL(window.location.href);
const includeParts = url.searchParams.get("include-parts")?.split(",");
const disablePageViewTracking = Boolean(url.searchParams.get("disable-page-view-tracking"));
dash0("init", {
serviceName: "dash0.com",
serviceVersion: "1.2.3",
environment: "prod",
additionalSignalAttributes: {
the_answer: 42,
},
endpoint: {
url: `http://${window.location.hostname}:8011?cors=true`,
authToken: "auth_abc123",
dataset: "production",
},
pageViewInstrumentation: {
includeParts,
trackVirtualPageViews: !disablePageViewTracking,
generateMetadata: (url) => {
return {
title: url.search.includes("useCustomTitle") ? "this is a custom title" : undefined,
attributes: {
url_meta: "this is an url meta attribute",
},
};
},
},
});
```
--------------------------------
### Initialize Dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/withZoneJs.html
Initializes the Dash0 SDK with service details and endpoint configuration. Ensure this is called early in your application's lifecycle.
```javascript
fetch with zonejs test (function (d, a, s, h, z, e, r, o) { d[a] || ((z = d[a] = function () { h.push(arguments); }), (z._t = new Date()), (z._v = 1), (h = z._q = [])); })(window, "dash0");
dash0("init", {
serviceName: "dash0.com",
serviceVersion: "1.2.3",
environment: "prod",
endpoint: [
{
url: `http://${window.location.hostname}:8011?cors=true`,
authToken: "auth_abc123",
dataset: "production",
},
],
propagateTraceHeadersCorsURLs: [new RegExp(`http:\/\/${window.location.hostname.replace(".", "\\.")}:8012`)]
});
```
--------------------------------
### Run All Unit Tests
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Execute all unit tests using the pnpm build command. This is useful for a comprehensive check of the codebase's current state.
```bash
pnpm run test:unit
```
--------------------------------
### Initialize Dash0 Web SDK with Session Sampling
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/README.md
Configure session sampling to control the percentage of user sessions that generate telemetry. Set `sessionSamplingRate` to a value between 0 and 100.
```ts
init({
serviceName: "my-website",
endpoint: { url: "{OTLP via HTTP endpoint}", authToken: "{authToken}" },
sessionSamplingRate: 50, // Only 50% of sessions will be recorded
});
```
--------------------------------
### Run Unit Tests with Coverage
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Execute unit tests and generate a code coverage report. This helps identify areas of the codebase that are not adequately tested.
```bash
pnpm run test:unit:coverage
```
--------------------------------
### Format Code with Prettier
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Format all code in the project using Prettier. This ensures consistent code style across the repository.
```bash
pnpm run prettier:all
```
--------------------------------
### Add Dash0 Web SDK via Script Tags (IIFE)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Include the Dash0 Web SDK using script tags for websites not using module builds. The API is accessed via the global `dash0` function. Configuration should be adjusted as needed.
```javascript
(function (d, a, s, h, z, e, r, o) {
d[a] ||
((z = d[a] =
function () {
h.push(arguments);
}),
(z._t = new Date()),
(z._v = 1),
(h = z._q = []));
})(window, "dash0");
dash0("init", {
serviceName: "my-website",
endpoint: {
// Replace this with the endpoint url identified during preparation
url: "REPLACE THIS",
// Replace this with the auth token you created earlier
// Ideally, you will inject the value at build time in order to not commit the token to git,
// even if its effectively public in the HTML you ship to the end user's browser
authToken: "REPLACE THIS",
},
});
```
```html
```
--------------------------------
### Fetch With Body From Init
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a POST fetch request with the body defined in the init object.
```javascript
function onFetchWithBodyFromInit() {
return fetch("/ajax?assert-body=this_is_an_important_message", {
method: "POST",
body: "this_is_an_important_message",
});
}
```
--------------------------------
### Navigate History using history.go
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Navigates the browser's history by a specified number of steps. A negative value moves back, and a positive value moves forward.
```javascript
function onGo() {
history.go(-1);
}
```
--------------------------------
### Zone.js Task Scheduling and Fetch
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/withZoneJs.html
Sets up a custom Zone for tracking scheduled tasks and performs a fetch request within that zone. Updates the UI with the count of scheduled tasks.
```javascript
addEventListener("load", () => {
window.tasksScheduled = 0;
window.testZone = Zone.current.fork({
name: "testZone",
onScheduleTask(delegate, current, target, task) {
window.tasksScheduled++;
delegate.scheduleTask(target, task);
},
});
});
function onDoAFetch() {
window.testZone.run(() => {
fetch(`/ajax?cacheBust=${new Date().getTime()}`);
document.getElementById("tasksScheduled").textContent = window.tasksScheduled;
});
return fetch("/ajax");
}
```
--------------------------------
### Run E2E Tests Locally
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Execute end-to-end tests locally targeting Chrome headless. Ensure you have the necessary environment variables set up.
```bash
pnpm run test:e2e:local
```
--------------------------------
### Configure Trace Context Propagators
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Configure trace context propagators for different URL patterns using W3C traceparent or AWS X-Ray headers. Supports regular expressions for matching URLs.
```javascript
init({
propagators: [
// W3C traceparent headers for internal APIs
{ type: "traceparent", match: [/.*\/api\/internal.*/] },
// AWS X-Ray headers for AWS services
{ type: "xray", match: [/.*\.amazonaws\.com.*/] },
// Send both headers to specific endpoints
{ type: "traceparent", match: [/.*\/api\/special.*/] },
{ type: "xray", match: [/.*\/api\/special.*/] },
],
});
```
--------------------------------
### Process.env Access for Frameworks
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Demonstrates the literal `process.env.NAME` accessor pattern required for environment variables to be substituted by build tools like Webpack or Next.js. Dynamic accessors will resolve to `undefined` in the browser bundle.
```typescript
process.env.NEXT_PUBLIC_MY_VAR
```
--------------------------------
### Fetch with Traceparent and X-Ray Headers
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Performs a fetch request to an endpoint configured to receive both X-Ray and W3C traceparent headers. This function tests the 'aws/both' matching pattern.
```javascript
function onTraceparentAndXrayFetch() {
// Should get W3C traceparent headers
return fetch(`http://${window.location.hostname}:8012/aws/both?test=traceparentAndXray&cors=true`, {
method: "GET",
});
}
```
--------------------------------
### Programmatic Page Transition using history.pushState
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Simulates a page transition by programmatically pushing a new state onto the browser's history stack. This is useful for single-page applications to manage navigation without full page reloads.
```javascript
function doATransition() {
history.pushState( undefined, "", new URL(`./virtual-page${window.location.search ? `${window.location.search}` : ""}`, window.location.href) );
}
```
--------------------------------
### Check Code Formatting
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Check if all code in the project adheres to the Prettier formatting rules. This is useful for CI pipelines.
```bash
pnpm run prettier:check
```
--------------------------------
### Run All E2E Tests Locally
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Execute all end-to-end tests locally for faster iteration. This bypasses remote runs and is suitable for quick checks.
```bash
pnpm run test:e2e:local
```
--------------------------------
### Fetch with No Specific Headers
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Performs a fetch request to an endpoint not explicitly configured for X-Ray or traceparent headers. This function demonstrates default behavior.
```javascript
function onNoHeadersFetch() {
// Should get W3C traceparent headers
return fetch(`http://${window.location.hostname}:8012/other?test=other`, {
method: "GET",
});
}
```
--------------------------------
### Run Specific Unit Test File
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Execute unit tests for a specific file, such as `src/utils/id_test.ts`. This allows for targeted testing during development.
```bash
pnpm run test:unit src/utils/id_test.ts
```
--------------------------------
### Fetch with Traceparent Headers
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Performs a fetch request to an endpoint configured to receive W3C traceparent headers. This function should trigger the 'traceparent' propagator.
```javascript
function onTraceparentFetch() {
// Should get W3C traceparent headers
return fetch(`http://${window.location.hostname}:8012/ajax?test=traceparent&cors=true`, {
method: "GET",
});
}
```
--------------------------------
### Fetch with X-Ray Headers
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Performs a fetch request to an endpoint configured to receive X-Ray headers. This function should trigger the 'xray' propagator.
```javascript
function onXRayFetch() {
// Should get X-Ray headers
return fetch(`http://${window.location.hostname}:8012/aws?test=xray&cors=true`, {
method: "GET",
});
}
```
--------------------------------
### Configure HTTP Request Propagators
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Define trace context propagators for different URL patterns. Use RegExp for specific cross-origin URL patterns. Multiple propagators can match the same URL to send both headers. Same-origin requests automatically receive traceparent headers plus headers for all other configured propagator types.
```javascript
propagators: [
// Use RegExp for specific cross-origin URL patterns
{ type: "traceparent", match: [/.*\/api\/internal.*/] },
{ type: "xray", match: [/.*\.amazonaws\.com.*/] },
// Multiple propagators can match the same URL to send both headers
{ type: "traceparent", match: [/.*\/api\/both.*/] },
{ type: "xray", match: [/.*\/api\/both.*/] },
]
```
--------------------------------
### Same Origin Fetch
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a fetch request to the same origin, including a custom header that should be captured by Dash0.
```javascript
function onSameOriginFetch() {
return fetch( "/ajax?thisIsA=test",
deepFreeze({
headers: new Headers({
"x-test-header": "this is a green test",
}),
})
);
}
```
--------------------------------
### Aborted Fetch Before Response
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Initiates a fetch request and aborts it using an AbortController before a response is received.
```javascript
function onAbortedFetchBeforeResponse() {
const controller = new AbortController();
const p = fetch("/delay-fetch?abort-before-response", {
signal: controller.signal,
}).catch(() => {});
controller.abort();
return p;
}
```
--------------------------------
### Navigate Forwards in History
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Simulates the user clicking the browser's forward button, navigating to the next page in the history.
```javascript
function onForward() {
history.forward();
}
```
--------------------------------
### Run Unit Tests in Watch Mode
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Execute unit tests with watch mode enabled, automatically re-running tests when file changes are detected. This speeds up the development feedback loop.
```bash
pnpm run:unit test:watch
```
--------------------------------
### Fetch With Request Object
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a fetch request using a Request object, including a custom header and cache-busting parameter.
```javascript
function onFetchWithRequest() {
return fetch(
deepFreeze(new Request(`/ajax?cacheBust=${new Date().getTime()}`, {
method: "POST",
headers: new Headers({
"x-test-header": "this is a yellow test",
}),
}))
);
}
```
--------------------------------
### Identify User (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Associates user information with telemetry signals. Supports user ID, name, full name, email, hash, and roles.
```javascript
import { identify } from "@dash0/sdk-web";
identify("user123", {
name: "johndoe",
fullName: "John Doe",
email: "john@example.com",
roles: ["admin", "user"],
});
```
--------------------------------
### Fetch With Body From Request
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a POST fetch request with the body defined within the Request object.
```javascript
function onFetchWithBodyFromRequest() {
const req = new Request("/ajax?assert-body=this_is_also_an_important_message", {
method: "POST",
body: "this_is_also_an_important_message",
});
return fetch(req);
}
```
--------------------------------
### Navigate Backwards in History
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Simulates the user clicking the browser's back button, navigating to the previous page in the history.
```javascript
function onBack() {
history.back();
}
```
--------------------------------
### Fetch With Ignored URL
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a fetch request to a URL that is configured to be ignored by Dash0 instrumentation.
```javascript
function onFetchWithIgnoredUrl() {
return fetch("/ajax?you-cant-see-this");
}
```
--------------------------------
### Conventional Commit for MINOR Release
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Use this format for adding new features in a backward-compatible manner. Includes an optional detailed description.
```git commit message
feat: Add instrumentation for fetch()
The sdk now supports automatic instrumentation of the fetch api
```
--------------------------------
### Fetch on Same Origin
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/06-xray-propagation/page.html
Performs a fetch request to a same-origin endpoint. This tests legacy behavior and ensures propagation still functions correctly.
```javascript
function onSameOriginFetch() {
// Same-origin request should still work with legacy behavior
return fetch("/ajax?test=same-origin", {
method: "GET",
});
}
```
--------------------------------
### Failing Fetch
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Initiates a fetch request to an invalid URL scheme, designed to fail and test error handling.
```javascript
function onFailingFetch() {
return fetch("boom://nothing-here");
}
```
--------------------------------
### Identify User (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Associates user information with telemetry signals. Supports user ID and optional additional information like name.
```javascript
dash0("identify", "user123", { name: "johndoe" });
```
--------------------------------
### identify(id, opts)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Associates user information with telemetry signals, allowing for user-centric analysis. This function can take a user ID and optional details like name, email, and roles.
```APIDOC
## identify(id, opts)
### Description
Associates user information with telemetry signals.
See [OTEL User Attributes](https://opentelemetry.io/docs/specs/semconv/registry/attributes/user/) for the matching attributes
### Parameters
#### Path Parameters
- **id** (string, optional) - User identifier
- **opts** (object, optional) - Additional user information
- **name** (string, optional) - Short name or login/username of the user
- **fullName** (string, optional) - User's full name
- **email** (string, optional) - User email address
- **hash** (string, optional) - Unique user hash to correlate information for a user in anonymized form.
- **roles** (string[], optional) - User roles
### Request Example
```javascript
// Module
import { identify } from "@dash0/sdk-web";
identify("user123", {
name: "johndoe",
fullName: "John Doe",
email: "john@example.com",
roles: ["admin", "user"],
});
// Script
dash0("identify", "user123", { name: "johndoe" });
```
```
--------------------------------
### Lint Code
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/CLAUDE.md
Run the linter to check for code quality issues and potential errors. This helps maintain code health.
```bash
pnpm run lint
```
--------------------------------
### Send Custom Event (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Sends a custom event with optional data, attributes, and severity. Event names used internally by the SDK are not permitted.
```javascript
import { sendEvent } from "@dash0/sdk-web";
sendEvent("user_action", {
data: "button_clicked",
attributes: {
buttonId: "submit-form",
page: "/checkout",
},
severity: "INFO",
});
```
--------------------------------
### Set Active Log Level
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Changes the active log level of this SDK. Defaults to 'warn'. Use 'debug' for more verbose logging during development.
```javascript
// Module
import { setActiveLogLevel } from "@dash0/sdk-web";
setActiveLogLevel("debug");
```
```javascript
// Script
dash0("setActiveLogLevel", "debug");
```
--------------------------------
### setActiveLogLevel
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Changes the active log level of this SDK. Defaults to 'warn'.
```APIDOC
## setActiveLogLevel(logLevel)
### Description
Changes the active log level of this SDK. Defaults to `warn`.
### Method
`setActiveLogLevel(logLevel: string)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Module
import { setActiveLogLevel } from "@dash0/sdk-web";
setActiveLogLevel("debug");
// Script
dash0("setActiveLogLevel", "debug");
```
### Response
None
```
--------------------------------
### Conventional Commit for NO Changelog Entry (PATCH)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Use this format for changes like documentation improvements or minor code refactors that do not warrant a changelog entry.
```git commit message
chore: Improve spelling of README
```
--------------------------------
### Send Custom Event (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Sends a custom event with optional data and severity. Event names used internally by the SDK are not permitted.
```javascript
dash0("sendEvent", "user_action", { data: "button_clicked", severity: "INFO" });
```
--------------------------------
### Cross Origin Fetch
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Performs a fetch request to a different origin, testing cross-origin request handling.
```javascript
function onCrossOriginFetch() {
return fetch(`http://${window.location.hostname}:8012/ajax?cors=true`, {
method: "POST",
});
}
```
--------------------------------
### Multi-Fetch With No Body Response
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Executes multiple fetch requests concurrently that are expected to return no content (204, 205, 304 status codes).
```javascript
function onFetchWithNoBodyResponse() {
return Promise.all([
fetch("/204"),
fetch("/205"),
fetch("/304"),
]);
}
```
--------------------------------
### Send Custom Event
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/04-events-api/page.html
Sends a custom event with specific data and attributes. Use this to report application-specific occurrences.
```javascript
function onSendEvent() {
dash0("sendEvent", "snacks_appeared", {
data: "This is an event",
attributes: {
"snack.kind": "ice cream",
},
severity: "INFO",
});
}
```
--------------------------------
### Aborted Fetch During Body Stream
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Initiates a fetch request with a streaming response and aborts it while reading the response body.
```javascript
function onAbortedFetchDuringBody() {
const controller = new AbortController();
return fetch("/stream-slowly?abort-during-body", {
signal: controller.signal,
}).then(async (response) => {
const reader = response.body.getReader();
await reader.read();
controller.abort();
try {
while (true) {
const { done } = await reader.read();
if (done) break;
}
} catch (_) {
// Expected: read rejects once the underlying transport is aborted.
}
});
}
```
--------------------------------
### sendEvent(name, opts)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Sends a custom event to track specific user actions or occurrences within the application. This function allows for detailed event data and attributes.
```APIDOC
## sendEvent(name, opts)
### Description
Sends a custom event with optional data and attributes.
Event name cannot be one of the event names internally used by the Dash0 Web SDK.
See [Event Names](https://github.com/dash0hq/dash0-sdk-web/blob/main/src/semantic-conventions.ts#L50)
### Parameters
#### Path Parameters
- **name** (string) - Required - Event name
- **opts** (object, optional) - Event options
- **title** (string, optional) - Human readable title for the event. Should summarize the event in a single short
sentence.
- **timestamp** (number | Date, optional) - Event timestamp
- **data** (AttributeValueType | AnyValue, optional) - Event data
- **attributes** (Record, optional) - Event attributes
- **severity** (LOG_SEVERITY_TEXT, optional) - Log severity level
### Request Example
```javascript
// Module
import { sendEvent } from "@dash0/sdk-web";
sendEvent("user_action", {
data: "button_clicked",
attributes: {
buttonId: "submit-form",
page: "/checkout",
},
severity: "INFO",
});
// Script
dash0("sendEvent", "user_action", { data: "button_clicked", severity: "INFO" });
```
```
--------------------------------
### Conventional Commit for MAJOR Release (BREAKING CHANGE)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Use this format for significant changes that may include backward incompatible API changes. Explicitly use 'BREAKING CHANGE:' or the '!' suffix.
```git commit message
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
```
```git commit message
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
```
--------------------------------
### Define Propagator Type and Match Patterns
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Defines the type of trace context propagator and the regular expressions to match URLs for propagation. Supported types are 'traceparent' and 'xray'.
```typescript
type PropagatorConfig = {
type: "traceparent" | "xray";
match: RegExp[];
};
```
--------------------------------
### Terminate Session (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually terminates the current user session. Typically used during user logout flows.
```javascript
import { terminateSession } from "@dash0/sdk-web";
// Terminate session on user logout
function handleLogout() {
terminateSession();
// Additional logout logic
}
```
--------------------------------
### Add Signal Attribute (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Use this to add a custom attribute that will be included with all transmitted signals. For initial page load attributes, use `additionalSignalAttributes` in `init()`.
```javascript
import { addSignalAttribute } from "@dash0/sdk-web";
addSignalAttribute("environment", "production");
addSignalAttribute("version", "1.2.3");
```
--------------------------------
### Function to Cause Unhandled Rejection
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/03-error-instrumentation/page.html
Defines a function that creates a Promise which rejects. This tests the capture of unhandled Promise rejections.
```javascript
function onUnhandledRejection() {
const p = new Promise((_, reject) => {
reject(new Error("This is a lava potato"));
});
p.then(console.log);
}
```
--------------------------------
### Add Signal Attribute (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Use this to add a custom attribute that will be included with all transmitted signals. For initial page load attributes, use `additionalSignalAttributes` in `init()`.
```javascript
dash0("addSignalAttribute", "environment", "production");
```
--------------------------------
### reportError(error, opts)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually reports an error to be tracked in telemetry. This is useful for capturing errors that might not be automatically detected by the SDK.
```APIDOC
## reportError(error, opts)
### Description
Manually reports an error to be tracked in telemetry.
### Parameters
#### Path Parameters
- **error** (string | ErrorLike) - Required - Error message or error object
- **opts** (object, optional) - Error reporting options
- **componentStack** (string | null | undefined, optional) - Component stack trace for React errors
- **attributes** (Record, optional) - Additional attributes to include with the
error report
### Request Example
```javascript
// Module
import { reportError } from "@dash0/sdk-web";
// Report a string error
reportError("Something went wrong in user flow");
// Report an Error object
try {
// Some operation
} catch (error) {
reportError(error);
}
reportError(error, {
// Report with component stack (useful for React)
componentStack: getComponentStack(),
// Additional attributes
attributes: {
"user.id": "user123",
},
});
// Script
dash0("reportError", "Something went wrong in user flow");
```
```
--------------------------------
### Report Error (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually reports an error as a string. This script version does not support reporting Error objects or additional options like component stack.
```javascript
dash0("reportError", "Something went wrong in user flow");
```
--------------------------------
### Terminate Session (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually terminates the current user session. Typically used during user logout flows.
```javascript
dash0("terminateSession");
```
--------------------------------
### terminateSession()
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually terminates the current user session. This is typically used during user logout to ensure session data is finalized.
```APIDOC
## terminateSession()
### Description
Manually terminates the current user session.
### Request Example
```javascript
// Module
import { terminateSession } from "@dash0/sdk-web";
// Terminate session on user logout
function handleLogout() {
terminateSession();
// Additional logout logic
}
// Script
dash0("terminateSession");
```
```
--------------------------------
### Conventional Commit for PATCH Release
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/DEVELOPMENT.md
Use this format for bug fixes and security patches that do not break backward compatibility.
```git commit message
fix: Include missing user.name attribute
```
--------------------------------
### Report Error (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Manually reports an error. Can accept a string or an Error object, with optional component stack and additional attributes.
```javascript
import { reportError } from "@dash0/sdk-web";
// Report a string error
reportError("Something went wrong in user flow");
// Report an Error object
try {
// Some operation
} catch (error) {
reportError(error);
}
reportError(error, {
// Report with component stack (useful for React)
componentStack: getComponentStack(),
// Additional attributes
attributes: {
"user.id": "user123",
},
});
```
--------------------------------
### Function to Throw Unhandled Error
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/03-error-instrumentation/page.html
Defines a function that explicitly throws an Error. This is used to test the capture of synchronous unhandled errors.
```javascript
function onThrowUnhandledError() {
throw new Error("This is a hot potato");
}
```
--------------------------------
### Function to Trigger Error in Timer
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/03-error-instrumentation/page.html
Schedules the execution of a function that throws an error using setTimeout. This tests error capture within asynchronous timer callbacks.
```javascript
function onTriggerErrorInTimer() {
setTimeout(onThrowUnhandledError);
}
```
--------------------------------
### addSignalAttribute(name, value)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Adds a custom attribute to be included with all outgoing telemetry signals. This is useful for adding consistent metadata like environment or version to every signal.
```APIDOC
## addSignalAttribute(name, value)
### Description
Adds a signal attribute to be transmitted with every signal.
### Parameters
#### Path Parameters
- **name** (string) - Required - The attribute name
- **value** (AttributeValueType | AnyValue) - Required - The attribute value
### Request Example
```javascript
// Module
import { addSignalAttribute } from "@dash0/sdk-web";
addSignalAttribute("environment", "production");
addSignalAttribute("version", "1.2.3");
// Script
dash0("addSignalAttribute", "environment", "production");
```
```
--------------------------------
### Change History State
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Updates the browser's history with custom state data using pushState. This allows associating arbitrary data with a specific history entry.
```javascript
function onChangeState() {
history.pushState({ foo: "bar" }, "", window.location.href);
}
```
--------------------------------
### Add Signal Attribute to dash0 SDK
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/02-web-vitals/page.html
Add a custom signal attribute to the dash0 SDK. This is useful for attaching specific data points to your web vital measurements.
```javascript
dash0("addSignalAttribute", "the_answer", 42);
```
--------------------------------
### Add Signal Attribute
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
Adds a custom attribute to be associated with signals. This can be used for adding context to captured data.
```javascript
dash0("addSignalAttribute", "the_answer", 42);
```
--------------------------------
### Deep Freeze Utility
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/01-fetch-instrumentation/page.html
A utility function to recursively freeze an object, making it immutable. This is used to ensure request objects are not modified unexpectedly.
```javascript
const deepFreeze = (obj) => {
if (obj && typeof obj === "object" && !Object.isFrozen(obj)) {
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach((prop) => deepFreeze(obj[prop]));
}
return obj;
};
```
--------------------------------
### Event Listener for Error in Click Handler
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/03-error-instrumentation/page.html
Attaches an event listener to a button click that triggers an unhandled error. This tests error capture within user-initiated event handlers.
```javascript
window.addEventListener("load", function () {
document.getElementById("event-handler-button").addEventListener("click", onThrowUnhandledError);
});
```
--------------------------------
### Replace Current History State
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Replaces the current entry in the browser's history stack with a new URL. This is useful for scenarios where you want to update the URL without creating a new history entry, such as after form submission.
```javascript
function onReplaceState() {
history.replaceState( undefined, "", new URL(`./virtual-page${window.location.search ? `${window.location.search}` : ""}`, window.location.href) );
}
```
--------------------------------
### Modify URL Fragment
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Changes the URL fragment (hash) and updates the browser's history without a full page reload. This is often used for in-page navigation or bookmarking specific sections.
```javascript
function onChangeFragment() {
const target = new URL(window.location.href);
target.hash = "someNewFragment";
history.pushState(undefined, "", target);
}
```
--------------------------------
### Remove Signal Attribute (Module)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Removes a previously added signal attribute. Ensure the attribute name matches the one added.
```javascript
import { removeSignalAttribute } from "@dash0/sdk-web";
removeSignalAttribute("environment");
```
--------------------------------
### Modify URL Query Parameters
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/test/e2e/spec/05-page-transition/page.html
Appends a query parameter to the current URL and updates the browser's history. This is commonly used to track specific user interactions or states within a page.
```javascript
function onChangeQuery() {
const target = new URL(window.location.href);
target.searchParams.append("ice-cream", "true");
history.pushState(undefined, "", target);
}
```
--------------------------------
### removeSignalAttribute(name)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Removes a previously added signal attribute, preventing it from being included in subsequent telemetry signals.
```APIDOC
## removeSignalAttribute(name)
### Description
Removes a previously added signal attribute.
### Parameters
#### Path Parameters
- **name** (string) - Required - The attribute name to remove
### Request Example
```javascript
// Module
import { removeSignalAttribute } from "@dash0/sdk-web";
removeSignalAttribute("environment");
// Script
dash0("removeSignalAttribute", "environment");
```
```
--------------------------------
### Remove Signal Attribute (Script)
Source: https://github.com/dash0hq/dash0-sdk-web/blob/main/INSTALL.md
Removes a previously added signal attribute. Ensure the attribute name matches the one added.
```javascript
dash0("removeSignalAttribute", "environment");
```