From 4b2768a937d8c04b890f04b4782b482aaac5dbfb Mon Sep 17 00:00:00 2001
From: s1gr1d <32902192+s1gr1d@users.noreply.github.com>
Date: Fri, 27 Nov 2026 15:12:31 +0100
Subject: [PATCH] feat(nuxt): Add spans for useFetch and useAsyncData
Each data composable call on the server (`useFetch`, `useAsyncData`
and the lazy variants) now has a span, as a child of the render span.
The spans come from the `nuxt.data` tracing channel of Nuxt.
A production build of Nuxt sends the composable name only for
`useLazyAsyncData`, so all other spans have the name `useAsyncData`.
With span streaming, a key that the app sets is the span description.
---
.../nuxt-4/app/pages/data-fetching.vue | 14 +
.../nuxt-4/server/api/data-fetching.ts | 9 +
.../data-fetching.static-lifecycle.test.ts | 22 ++
.../data-fetching.streaming-lifecycle.test.ts | 154 +++++++++++
.../nuxt-5/app/pages/data-fetching.vue | 14 +
.../nuxt-5/server/api/data-fetching.ts | 11 +
.../nuxt-5/tests/data-fetching.test.ts | 150 +++++++++++
.../utils/nuxtTracingChannelIntegration.ts | 79 +++++-
.../nuxtTracingChannelIntegration.test.ts | 251 +++++++++++++++++-
9 files changed, 694 insertions(+), 10 deletions(-)
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/data-fetching.vue
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-4/server/api/data-fetching.ts
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.static-lifecycle.test.ts
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.streaming-lifecycle.test.ts
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/data-fetching.vue
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-5/server/api/data-fetching.ts
create mode 100644 dev-packages/e2e-tests/test-applications/nuxt-5/tests/data-fetching.test.ts
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/data-fetching.vue b/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/data-fetching.vue
new file mode 100644
index 000000000000..0a9902eef861
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/data-fetching.vue
@@ -0,0 +1,14 @@
+
+
+
+ {{ keyed?.success }}
+ {{ keyless?.success }}
+ {{ orderCount }}
+
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/data-fetching.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/data-fetching.ts
new file mode 100644
index 000000000000..12862d24474a
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/data-fetching.ts
@@ -0,0 +1,9 @@
+import { defineEventHandler, useDatabase, useStorage } from '#imports';
+
+// The page `/data-fetching` fetches this route while it renders on the server.
+export default defineEventHandler(async () => {
+ await useStorage('test-storage').setItem('data-fetching:visits', 1);
+ await useDatabase().exec('CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, page TEXT)');
+
+ return { success: true };
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.static-lifecycle.test.ts
new file mode 100644
index 000000000000..32824b62506a
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.static-lifecycle.test.ts
@@ -0,0 +1,22 @@
+import { SENTRY_DESCRIPTION, URL_PATH } from '@sentry/conventions/attributes';
+import { FUNCTION } from '@sentry/conventions/op';
+import { expect, test } from '@playwright/test';
+import { waitForTransaction } from '@sentry-internal/test-utils';
+
+test('sends a span for each data composable as a child of the render span', async ({ request }) => {
+ const transactionPromise = waitForTransaction('nuxt-4', transactionEvent => {
+ return transactionEvent.contexts?.trace?.data?.[URL_PATH] === '/data-fetching';
+ });
+
+ await request.get('/data-fetching');
+
+ const transaction = await transactionPromise;
+ const renderSpan = transaction.spans?.find(span => span.origin === 'auto.function.nuxt.render');
+ const dataSpans = (transaction.spans ?? []).filter(span => span.origin === 'auto.function.nuxt.data');
+
+ expect(dataSpans.map(span => span.description).sort()).toEqual(['useAsyncData', 'useAsyncData', 'useLazyAsyncData']);
+ expect(dataSpans.map(span => span.op)).toEqual([FUNCTION, FUNCTION, FUNCTION]);
+ // Relay replaces the description of a transaction span with the span name, so the SDK sends no key.
+ expect(dataSpans.map(span => span.data[SENTRY_DESCRIPTION])).toEqual([undefined, undefined, undefined]);
+ expect(dataSpans.map(span => span.parent_span_id)).toEqual(Array(3).fill(renderSpan?.span_id));
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.streaming-lifecycle.test.ts
new file mode 100644
index 000000000000..c325a96dcd6a
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/data-fetching.streaming-lifecycle.test.ts
@@ -0,0 +1,154 @@
+import type { APIRequestContext } from '@playwright/test';
+import { CODE_FUNCTION_NAME, SENTRY_DESCRIPTION, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
+import { CACHE_PUT, DB_QUERY, FUNCTION, MIDDLEWARE } from '@sentry/conventions/op';
+import { expect, test } from '@playwright/test';
+import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
+import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
+import { isViteServer, NITRO_ONLY } from './isViteServer';
+import { DB_ORIGIN } from './runtime';
+
+const DATA_ORIGIN = 'auto.function.nuxt.data';
+const STORAGE_ORIGIN = 'auto.cache.nuxt';
+
+const hasOrigin = (origin: string) => (span: SerializedStreamedSpan) =>
+ span.attributes[SENTRY_ORIGIN]?.value === origin;
+
+/**
+ * Requests the page and returns the spans of that request. On Cloudflare, the spans of one request can arrive in more
+ * than one envelope and in any order, so each test names the spans that it waits for.
+ */
+async function requestPage(
+ request: APIRequestContext,
+ hasSpansUnderTest: (spans: SerializedStreamedSpan[]) => boolean,
+): Promise {
+ const spansPromise = collectStreamedSpans(
+ 'nuxt-4',
+ spans =>
+ spans.some(span => span.is_segment && span.attributes[URL_PATH]?.value === '/data-fetching') &&
+ hasSpansUnderTest(spans),
+ );
+
+ await request.get('/data-fetching');
+
+ return spansPromise;
+}
+
+/** On the Vite server, the fetch of an API route renders a page inside the data span, so the name alone is not enough. */
+function getPageRenderSpan(spans: SerializedStreamedSpan[]): SerializedStreamedSpan | undefined {
+ const rootSpan = spans.find(span => span.is_segment);
+
+ return spans.find(span => span.name === 'renderPage' && span.parent_span_id === rootSpan?.span_id);
+}
+
+/** The spans of the two `useFetch` calls of the page. */
+function getFetchSpans(spans: SerializedStreamedSpan[]): SerializedStreamedSpan[] {
+ return spans.filter(span => hasOrigin(DATA_ORIGIN)(span) && span.name === 'useAsyncData');
+}
+
+const hasBothFetchSpans = (spans: SerializedStreamedSpan[]) => getFetchSpans(spans).length >= 2;
+const getSpanIds = (spans: SerializedStreamedSpan[]) => spans.map(span => span.span_id).sort();
+const getParentSpanIds = (spans: SerializedStreamedSpan[]) => spans.map(span => span.parent_span_id).sort();
+
+test('sends a span for `useLazyAsyncData` as a child of the render span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => !!getPageRenderSpan(spans) && spans.some(span => span.name === 'useLazyAsyncData'),
+ );
+
+ const lazySpans = spans.filter(span => span.name === 'useLazyAsyncData');
+
+ expect(lazySpans).toHaveLength(1);
+ expect(lazySpans[0]?.status).toBe('ok');
+ expect(lazySpans[0]?.parent_span_id).toBe(getPageRenderSpan(spans)?.span_id);
+ expect(getSpanOp(lazySpans[0]!)).toBe(FUNCTION);
+ expect(lazySpans[0]?.attributes[SENTRY_ORIGIN]).toEqual({ type: 'string', value: DATA_ORIGIN });
+ expect(lazySpans[0]?.attributes[CODE_FUNCTION_NAME]).toEqual({ type: 'string', value: 'useLazyAsyncData' });
+ expect(lazySpans[0]?.attributes[SENTRY_DESCRIPTION]).toEqual({ type: 'string', value: 'order-count' });
+});
+
+// A production build of Nuxt sends the name of the composable only for `useLazyAsyncData`.
+test('names the span of a `useFetch` call `useAsyncData`', async ({ request }) => {
+ const spans = await requestPage(request, spans => spans.filter(hasOrigin(DATA_ORIGIN)).length >= 3);
+
+ const dataSpans = spans.filter(hasOrigin(DATA_ORIGIN));
+
+ expect(dataSpans.map(span => span.name).sort()).toEqual(['useAsyncData', 'useAsyncData', 'useLazyAsyncData']);
+ expect(dataSpans.map(span => span.attributes[CODE_FUNCTION_NAME]?.value).sort()).toEqual([
+ 'useAsyncData',
+ 'useAsyncData',
+ 'useLazyAsyncData',
+ ]);
+});
+
+test('adds the key as the description only for a `useFetch` call with a key', async ({ request }) => {
+ const spans = await requestPage(request, hasBothFetchSpans);
+
+ const descriptions = getFetchSpans(spans).map(span => span.attributes[SENTRY_DESCRIPTION]?.value);
+
+ expect(descriptions).toHaveLength(2);
+ expect(descriptions).toContain('visits');
+ expect(descriptions).toContain(undefined);
+});
+
+test('makes each `useFetch` span a child of the render span', async ({ request }) => {
+ const spans = await requestPage(request, spans => !!getPageRenderSpan(spans) && hasBothFetchSpans(spans));
+
+ const renderSpanId = getPageRenderSpan(spans)?.span_id;
+
+ expect(getParentSpanIds(getFetchSpans(spans))).toEqual([renderSpanId, renderSpanId]);
+});
+
+test.describe('spans of the API route that a `useFetch` call fetches on the server', () => {
+ test.skip(isViteServer, NITRO_ONLY);
+
+ test('makes the storage span a child of the `useFetch` span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => hasBothFetchSpans(spans) && spans.filter(hasOrigin(STORAGE_ORIGIN)).length >= 2,
+ );
+
+ const storageSpans = spans.filter(hasOrigin(STORAGE_ORIGIN));
+
+ expect(getParentSpanIds(storageSpans)).toEqual(getSpanIds(getFetchSpans(spans)));
+ expect(storageSpans.map(span => span.name)).toEqual(['cache.put', 'cache.put']);
+ expect(storageSpans.map(getSpanOp)).toEqual([CACHE_PUT, CACHE_PUT]);
+ });
+
+ test('makes the database span a child of the `useFetch` span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => hasBothFetchSpans(spans) && spans.filter(hasOrigin(DB_ORIGIN)).length >= 2,
+ );
+
+ const dbSpans = spans.filter(hasOrigin(DB_ORIGIN));
+
+ expect(getParentSpanIds(dbSpans)).toEqual(getSpanIds(getFetchSpans(spans)));
+ expect(dbSpans.map(span => span.name)).toEqual(['CREATE TABLE visits', 'CREATE TABLE visits']);
+ expect(dbSpans.map(getSpanOp)).toEqual([DB_QUERY, DB_QUERY]);
+ });
+
+ // The server middleware runs for the page request and for each fetch of the API route.
+ test('makes the server middleware spans children of the `useFetch` span', async ({ request }) => {
+ const getMiddlewareNames = (spans: SerializedStreamedSpan[], parentSpanId: string | undefined) =>
+ spans
+ .filter(span => getSpanOp(span) === MIDDLEWARE && span.parent_span_id === parentSpanId)
+ .map(span => `${span.name} (${span.attributes[SENTRY_ORIGIN]?.value})`)
+ .sort();
+ const getMiddlewareNamesOfPage = (spans: SerializedStreamedSpan[]) =>
+ getMiddlewareNames(spans, spans.find(span => span.is_segment)?.span_id);
+ const getMiddlewareNamesOfFetches = (spans: SerializedStreamedSpan[]) =>
+ getFetchSpans(spans).map(fetchSpan => getMiddlewareNames(spans, fetchSpan.span_id));
+ const spans = await requestPage(
+ request,
+ spans =>
+ hasBothFetchSpans(spans) &&
+ getMiddlewareNamesOfFetches(spans).every(names => names.length >= getMiddlewareNamesOfPage(spans).length),
+ );
+
+ const namesOfPage = getMiddlewareNamesOfPage(spans);
+
+ expect(namesOfPage.length).toBeGreaterThan(0);
+ expect(namesOfPage.every(name => name.endsWith('(auto.middleware.nuxt)'))).toBe(true);
+ expect(getMiddlewareNamesOfFetches(spans)).toEqual([namesOfPage, namesOfPage]);
+ });
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/data-fetching.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/data-fetching.vue
new file mode 100644
index 000000000000..0a9902eef861
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/data-fetching.vue
@@ -0,0 +1,14 @@
+
+
+
+ {{ keyed?.success }}
+ {{ keyless?.success }}
+ {{ orderCount }}
+
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/data-fetching.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/data-fetching.ts
new file mode 100644
index 000000000000..0d45cc1d0217
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/data-fetching.ts
@@ -0,0 +1,11 @@
+import { defineHandler } from 'nitro';
+import { useDatabase } from 'nitro/database';
+import { useStorage } from 'nitro/storage';
+
+// The page `/data-fetching` fetches this route while it renders on the server.
+export default defineHandler(async () => {
+ await useStorage('test-storage').setItem('data-fetching:visits', 1);
+ await useDatabase().exec('CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, page TEXT)');
+
+ return { success: true };
+});
diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/data-fetching.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/data-fetching.test.ts
new file mode 100644
index 000000000000..84aea6319c1e
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/data-fetching.test.ts
@@ -0,0 +1,150 @@
+import type { APIRequestContext } from '@playwright/test';
+import { CODE_FUNCTION_NAME, SENTRY_DESCRIPTION, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
+import { CACHE_PUT, DB_QUERY, FUNCTION, MIDDLEWARE } from '@sentry/conventions/op';
+import { expect, test } from '@playwright/test';
+import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
+import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
+import { DB_ORIGIN } from './runtime';
+
+const DATA_ORIGIN = 'auto.function.nuxt.data';
+const STORAGE_ORIGIN = 'auto.cache.nuxt';
+
+const hasOrigin = (origin: string) => (span: SerializedStreamedSpan) =>
+ span.attributes[SENTRY_ORIGIN]?.value === origin;
+
+/**
+ * Requests the page and returns the spans of that request. On Cloudflare, the spans of one request can arrive in more
+ * than one envelope and in any order, so each test names the spans that it waits for.
+ */
+async function requestPage(
+ request: APIRequestContext,
+ hasSpansUnderTest: (spans: SerializedStreamedSpan[]) => boolean,
+): Promise {
+ const spansPromise = collectStreamedSpans(
+ 'nuxt-5',
+ spans =>
+ spans.some(span => span.is_segment && span.attributes[URL_PATH]?.value === '/data-fetching') &&
+ hasSpansUnderTest(spans),
+ );
+
+ await request.get('/data-fetching');
+
+ return spansPromise;
+}
+
+function getPageRenderSpan(spans: SerializedStreamedSpan[]): SerializedStreamedSpan | undefined {
+ const rootSpan = spans.find(span => span.is_segment);
+
+ return spans.find(span => span.name === 'renderPage' && span.parent_span_id === rootSpan?.span_id);
+}
+
+/** The spans of the two `useFetch` calls of the page. */
+function getFetchSpans(spans: SerializedStreamedSpan[]): SerializedStreamedSpan[] {
+ return spans.filter(span => hasOrigin(DATA_ORIGIN)(span) && span.name === 'useAsyncData');
+}
+
+const hasBothFetchSpans = (spans: SerializedStreamedSpan[]) => getFetchSpans(spans).length >= 2;
+const getSpanIds = (spans: SerializedStreamedSpan[]) => spans.map(span => span.span_id).sort();
+const getParentSpanIds = (spans: SerializedStreamedSpan[]) => spans.map(span => span.parent_span_id).sort();
+
+test('sends a span for `useLazyAsyncData` as a child of the render span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => !!getPageRenderSpan(spans) && spans.some(span => span.name === 'useLazyAsyncData'),
+ );
+
+ const lazySpans = spans.filter(span => span.name === 'useLazyAsyncData');
+
+ expect(lazySpans).toHaveLength(1);
+ expect(lazySpans[0]?.status).toBe('ok');
+ expect(lazySpans[0]?.parent_span_id).toBe(getPageRenderSpan(spans)?.span_id);
+ expect(getSpanOp(lazySpans[0]!)).toBe(FUNCTION);
+ expect(lazySpans[0]?.attributes[SENTRY_ORIGIN]).toEqual({ type: 'string', value: DATA_ORIGIN });
+ expect(lazySpans[0]?.attributes[CODE_FUNCTION_NAME]).toEqual({ type: 'string', value: 'useLazyAsyncData' });
+ expect(lazySpans[0]?.attributes[SENTRY_DESCRIPTION]).toEqual({ type: 'string', value: 'order-count' });
+});
+
+// A production build of Nuxt sends the name of the composable only for `useLazyAsyncData`.
+test('names the span of a `useFetch` call `useAsyncData`', async ({ request }) => {
+ const spans = await requestPage(request, spans => spans.filter(hasOrigin(DATA_ORIGIN)).length >= 3);
+
+ const dataSpans = spans.filter(hasOrigin(DATA_ORIGIN));
+
+ expect(dataSpans.map(span => span.name).sort()).toEqual(['useAsyncData', 'useAsyncData', 'useLazyAsyncData']);
+ expect(dataSpans.map(span => span.attributes[CODE_FUNCTION_NAME]?.value).sort()).toEqual([
+ 'useAsyncData',
+ 'useAsyncData',
+ 'useLazyAsyncData',
+ ]);
+});
+
+test('adds the key as the description only for a `useFetch` call with a key', async ({ request }) => {
+ const spans = await requestPage(request, hasBothFetchSpans);
+
+ const descriptions = getFetchSpans(spans).map(span => span.attributes[SENTRY_DESCRIPTION]?.value);
+
+ expect(descriptions).toHaveLength(2);
+ expect(descriptions).toContain('visits');
+ expect(descriptions).toContain(undefined);
+});
+
+test('makes each `useFetch` span a child of the render span', async ({ request }) => {
+ const spans = await requestPage(request, spans => !!getPageRenderSpan(spans) && hasBothFetchSpans(spans));
+
+ const renderSpanId = getPageRenderSpan(spans)?.span_id;
+
+ expect(getParentSpanIds(getFetchSpans(spans))).toEqual([renderSpanId, renderSpanId]);
+});
+
+test.describe('spans of the API route that a `useFetch` call fetches on the server', () => {
+ test('makes the storage span a child of the `useFetch` span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => hasBothFetchSpans(spans) && spans.filter(hasOrigin(STORAGE_ORIGIN)).length >= 2,
+ );
+
+ const storageSpans = spans.filter(hasOrigin(STORAGE_ORIGIN));
+
+ expect(getParentSpanIds(storageSpans)).toEqual(getSpanIds(getFetchSpans(spans)));
+ expect(storageSpans.map(span => span.name)).toEqual(['cache.put', 'cache.put']);
+ expect(storageSpans.map(getSpanOp)).toEqual([CACHE_PUT, CACHE_PUT]);
+ });
+
+ test('makes the database span a child of the `useFetch` span', async ({ request }) => {
+ const spans = await requestPage(
+ request,
+ spans => hasBothFetchSpans(spans) && spans.filter(hasOrigin(DB_ORIGIN)).length >= 2,
+ );
+
+ const dbSpans = spans.filter(hasOrigin(DB_ORIGIN));
+
+ expect(getParentSpanIds(dbSpans)).toEqual(getSpanIds(getFetchSpans(spans)));
+ expect(dbSpans.map(span => span.name)).toEqual(['CREATE TABLE visits', 'CREATE TABLE visits']);
+ expect(dbSpans.map(getSpanOp)).toEqual([DB_QUERY, DB_QUERY]);
+ });
+
+ // The server middleware runs for the page request and for each fetch of the API route.
+ test('makes the server middleware spans children of the `useFetch` span', async ({ request }) => {
+ const getMiddlewareNames = (spans: SerializedStreamedSpan[], parentSpanId: string | undefined) =>
+ spans
+ .filter(span => getSpanOp(span) === MIDDLEWARE && span.parent_span_id === parentSpanId)
+ .map(span => `${span.name} (${span.attributes[SENTRY_ORIGIN]?.value})`)
+ .sort();
+ const getMiddlewareNamesOfPage = (spans: SerializedStreamedSpan[]) =>
+ getMiddlewareNames(spans, spans.find(span => span.is_segment)?.span_id);
+ const getMiddlewareNamesOfFetches = (spans: SerializedStreamedSpan[]) =>
+ getFetchSpans(spans).map(fetchSpan => getMiddlewareNames(spans, fetchSpan.span_id));
+ const spans = await requestPage(
+ request,
+ spans =>
+ hasBothFetchSpans(spans) &&
+ getMiddlewareNamesOfFetches(spans).every(names => names.length >= getMiddlewareNamesOfPage(spans).length),
+ );
+
+ const namesOfPage = getMiddlewareNamesOfPage(spans);
+
+ expect(namesOfPage.length).toBeGreaterThan(0);
+ expect(namesOfPage.every(name => name.endsWith('(auto.middleware.nuxt)'))).toBe(true);
+ expect(getMiddlewareNamesOfFetches(spans)).toEqual([namesOfPage, namesOfPage]);
+ });
+});
diff --git a/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts b/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts
index 780725490579..c35510149321 100644
--- a/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts
+++ b/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts
@@ -1,7 +1,25 @@
-import { CODE_FUNCTION_NAME, ERROR_TYPE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
+import {
+ CODE_FUNCTION_NAME,
+ ERROR_TYPE,
+ HTTP_ROUTE,
+ SENTRY_DESCRIPTION,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';
import type { Integration, Options, Span } from '@sentry/core';
-import { defineIntegration, getActiveSpan, SPAN_STATUS_ERROR, SPAN_STATUS_OK, startInactiveSpan } from '@sentry/core';
+import {
+ defineIntegration,
+ getActiveSpan,
+ getClient,
+ getSpanStatusFromHttpCode,
+ hasSpanStreamingEnabled,
+ isObjectLike,
+ isString,
+ SPAN_STATUS_ERROR,
+ SPAN_STATUS_OK,
+ startInactiveSpan,
+} from '@sentry/core';
import type { TracingChannelPayloadWithSpan } from '@sentry/server-utils';
import { bindTracingChannelToSpan, diagnosticsTracingChannel } from '@sentry/server-utils';
@@ -17,6 +35,12 @@ interface NuxtRenderPayload {
};
}
+/** What the SDK reads from the `nuxt.data` payload. */
+interface NuxtDataPayload {
+ key?: unknown;
+ functionName?: unknown;
+}
+
const INTEGRATION_NAME = 'NuxtTracingChannel';
function isErrorPageRender({ ssrContext }: NuxtRenderPayload): boolean {
@@ -86,6 +110,53 @@ function setRenderResult(span: Span, data: TracingChannelPayloadWithSpan): void {
+ if (!('error' in data)) {
+ return;
+ }
+
+ const error: { name?: unknown; status?: unknown; statusCode?: unknown } = isObjectLike(data.error) ? data.error : {};
+
+ // Nuxt aborts a handler when a new call with the same key replaces it, and does not treat that as an error.
+ if (error.name === 'AbortError') {
+ span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });
+ span.setAttribute(ERROR_TYPE, undefined);
+ return;
+ }
+
+ // Replaces the error message in the status. The message of a failed `useFetch` has the URL with its query string.
+ span.setStatus(getSpanStatusFromHttpCode(Number(error.status ?? error.statusCode)));
+}
+
/** Makes spans from the `nuxt.*` tracing channels. Nuxt publishes nothing when the `nuxt` channel group is off. */
export const nuxtTracingChannelIntegration = defineIntegration(() => ({
name: INTEGRATION_NAME,
@@ -99,6 +170,10 @@ export const nuxtTracingChannelIntegration = defineIntegration(() => ({
bindTracingChannelToSpan(diagnosticsTracingChannel('nuxt.render'), startRenderSpan, {
beforeSpanEnd: setRenderResult,
});
+
+ bindTracingChannelToSpan(diagnosticsTracingChannel('nuxt.data'), startDataSpan, {
+ beforeSpanEnd: setDataResult,
+ });
},
}));
diff --git a/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts b/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts
index b1f14acbce71..dc6a1b38bd07 100644
--- a/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts
+++ b/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts
@@ -2,8 +2,16 @@
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { pathToFileURL } from 'node:url';
-import { CODE_FUNCTION_NAME, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
-import { FUNCTION, HTTP_CLIENT, HTTP_SERVER } from '@sentry/conventions/op';
+import {
+ CODE_FUNCTION_NAME,
+ ERROR_TYPE,
+ HTTP_ROUTE,
+ SENTRY_DESCRIPTION,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+ SENTRY_STATUS_MESSAGE,
+} from '@sentry/conventions/attributes';
+import { DB, FUNCTION, HTTP_CLIENT, HTTP_SERVER } from '@sentry/conventions/op';
import type { Client, Integration, StreamedSpanJSON } from '@sentry/core';
import { createTransport, getActiveSpan, getCurrentScope, spanToJSON, startNewTrace, startSpan } from '@sentry/core';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
@@ -22,27 +30,41 @@ async function importNuxtTraceAsync(): Promise {
}
const RENDER_ORIGIN = 'auto.function.nuxt.render';
+const DATA_ORIGIN = 'auto.function.nuxt.data';
function renderSpanAttributes(name: string): Record {
return { [SENTRY_OP]: FUNCTION, [SENTRY_ORIGIN]: RENDER_ORIGIN, [CODE_FUNCTION_NAME]: name };
}
+function dataSpanAttributes(name: string): Record {
+ return { [SENTRY_OP]: FUNCTION, [SENTRY_ORIGIN]: DATA_ORIGIN, [CODE_FUNCTION_NAME]: name };
+}
+
+/** The error that `$fetch` rejects with. ofetch sets `status` and `statusCode`; the tests set one of them. */
+function fetchError(response: { status?: number; statusCode?: number }): Error {
+ const message = '[GET] "https://api.example.com/sessions?token=secret-token": request failed';
+ return Object.assign(new Error(message), { name: 'FetchError' }, response);
+}
+
+type PublishOptions = { rejects?: boolean };
+
// All tests share one client, because the channel subscribers of an integration stay for the whole process.
describe('nuxtTracingChannelIntegration', () => {
let client: Client;
let traceAsync: TraceAsync;
const endedSpans: StreamedSpanJSON[] = [];
- /** Publishes a `nuxt.render` event inside an `http.server` root span. Returns the ended spans of that request. */
- async function render(
+ /** Publishes an event on a `nuxt.*` channel inside an `http.server` root span. Returns the ended spans of that request. */
+ async function publish(
+ channel: string,
payload: object,
- renderToString: () => Promise = () => Promise.resolve({ html: '' }),
- { rejects = false }: { rejects?: boolean } = {},
+ operation: () => Promise,
+ { rejects = false }: PublishOptions = {},
): Promise {
const traceId = await startNewTrace(() =>
startSpan({ name: 'GET', op: HTTP_SERVER }, async rootSpan => {
- const rendered = traceAsync('nuxt.render', payload, renderToString);
- await (rejects ? rendered.catch(() => undefined) : rendered);
+ const settled = traceAsync(channel, payload, operation);
+ await (rejects ? settled.catch(() => undefined) : settled);
return spanToJSON(rootSpan).trace_id;
}),
);
@@ -50,6 +72,23 @@ describe('nuxtTracingChannelIntegration', () => {
return endedSpans.filter(span => span.trace_id === traceId);
}
+ function render(
+ payload: object,
+ renderToString: () => Promise = () => Promise.resolve({ html: '' }),
+ options?: PublishOptions,
+ ): Promise {
+ return publish('nuxt.render', payload, renderToString, options);
+ }
+
+ /** `useAsyncData` publishes `nuxt.data` around the handler of the composable. */
+ function loadData(
+ payload: object,
+ handler: () => Promise = () => Promise.resolve({ sessions: [] }),
+ options?: PublishOptions,
+ ): Promise {
+ return publish('nuxt.data', payload, handler, options);
+ }
+
function getParent(span: StreamedSpanJSON | undefined, spans: StreamedSpanJSON[]): StreamedSpanJSON | undefined {
return spans.find(candidate => candidate.span_id === span?.parent_span_id);
}
@@ -293,6 +332,202 @@ describe('nuxtTracingChannelIntegration', () => {
expect(activeSpans).toEqual([undefined]);
});
});
+
+ describe('nuxt.data', () => {
+ // Only a dev build of Nuxt sends `useFetch` and `useLazyFetch`. A production build sends `useLazyAsyncData`.
+ it.each(['useFetch', 'useLazyFetch', 'useLazyAsyncData'])(
+ 'names the span `%s` after the composable in the payload',
+ async functionName => {
+ const spans = await loadData({ key: 'active-sessions', functionName });
+
+ const dataSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpans).toHaveLength(1);
+ expect(dataSpans[0]?.name).toBe(functionName);
+ expect(dataSpans[0]?.attributes).toEqual({
+ ...dataSpanAttributes(functionName),
+ [SENTRY_DESCRIPTION]: 'active-sessions',
+ });
+ },
+ );
+
+ it('creates the data span with the ok status as a child of the request root span', async () => {
+ const spans = await loadData({ key: 'active-sessions', functionName: 'useAsyncData' });
+
+ const dataSpan = spans.find(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpan?.status).toBe('ok');
+ expect(getParent(dataSpan, spans)?.attributes[SENTRY_OP]).toBe(HTTP_SERVER);
+ });
+
+ it.each([
+ { description: 'no function name, as in a production build', functionName: undefined },
+ { description: 'an empty function name', functionName: '' },
+ { description: 'a function name that is no string', functionName: { name: 'useFetch' } },
+ ])('names the span `useAsyncData` for a payload with $description', async ({ functionName }) => {
+ const spans = await loadData({ key: 'active-sessions', functionName });
+
+ const dataSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpans).toHaveLength(1);
+ expect(dataSpans[0]?.name).toBe('useAsyncData');
+ expect(dataSpans[0]?.attributes).toEqual({
+ ...dataSpanAttributes('useAsyncData'),
+ [SENTRY_DESCRIPTION]: 'active-sessions',
+ });
+ });
+
+ it.each([
+ { description: 'no key', key: undefined },
+ { description: 'an empty key', key: '' },
+ { description: 'a key that is no string', key: { value: 'active-sessions' } },
+ { description: 'the key that Nuxt makes for a call without a key', key: '$f2221v9rwjvsw2' },
+ ])('adds no description for a payload with $description', async ({ key }) => {
+ const spans = await loadData({ key, functionName: 'useAsyncData' });
+
+ const dataSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpans).toHaveLength(1);
+ expect(dataSpans[0]?.attributes).toEqual(dataSpanAttributes('useAsyncData'));
+ });
+
+ it('adds no description in the static trace lifecycle, where Relay replaces it with the span name', async () => {
+ vi.spyOn(client, 'getOptions').mockReturnValue({ ...client.getOptions(), traceLifecycle: 'static' });
+
+ const spans = await loadData({ key: 'active-sessions', functionName: 'useAsyncData' });
+
+ const dataSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpans).toHaveLength(1);
+ expect(dataSpans[0]?.attributes).toEqual(dataSpanAttributes('useAsyncData'));
+ });
+
+ it('puts the data span between the render span and a span of the handler', async () => {
+ const spans = await render({ ssrContext: { error: false }, streaming: false }, () =>
+ traceAsync('nuxt.data', { key: 'user-42', functionName: 'useFetch' }, () =>
+ startSpan({ name: 'GET https://api.example.com/users/42', op: HTTP_CLIENT }, () => Promise.resolve()),
+ ),
+ );
+
+ const fetchSpan = spans.find(span => span.attributes[SENTRY_OP] === HTTP_CLIENT);
+ const dataSpan = getParent(fetchSpan, spans);
+
+ expect(fetchSpan).toBeDefined();
+ expect(dataSpan?.name).toBe('useFetch');
+ expect(getParent(dataSpan, spans)?.name).toBe('renderPage');
+ });
+
+ it('gives each of two parallel data loads its own span', async () => {
+ const spans = await render({ ssrContext: { error: false }, streaming: false }, () =>
+ Promise.all(
+ ['user-42', 'active-sessions'].map(key =>
+ traceAsync('nuxt.data', { key, functionName: 'useAsyncData' }, () =>
+ startSpan({ name: `SELECT ${key}`, op: DB }, () => new Promise(resolve => setTimeout(resolve, 5))),
+ ),
+ ),
+ ),
+ );
+
+ const dbSpans = spans.filter(span => span.attributes[SENTRY_OP] === DB);
+
+ expect(dbSpans.map(span => [span.name, getParent(span, spans)?.attributes[SENTRY_DESCRIPTION]])).toEqual([
+ ['SELECT user-42', 'user-42'],
+ ['SELECT active-sessions', 'active-sessions'],
+ ]);
+ });
+
+ it('ends the span when the handler settles, not when the handler returns its promise', async () => {
+ const activeSpansAfterAwait: Array> = [];
+
+ await loadData({ key: 'active-sessions', functionName: 'useAsyncData' }, async () => {
+ await new Promise(resolve => setTimeout(resolve, 5));
+ const { name, end_timestamp } = spanToJSON(getActiveSpan()!);
+ activeSpansAfterAwait.push({ name, end_timestamp });
+ });
+
+ expect(activeSpansAfterAwait).toEqual([{ name: 'useAsyncData', end_timestamp: undefined }]);
+ });
+
+ it('sets the error status on the span of a handler that rejects', async () => {
+ const spans = await loadData(
+ { key: 'active-sessions', functionName: 'useAsyncData' },
+ () => Promise.reject(new Error('[GET] "/api/sessions": 500 Internal Server Error')),
+ { rejects: true },
+ );
+
+ expect(spans.find(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN)?.status).toBe('error');
+ });
+
+ // The message of a failed `useFetch` has the URL with its query string, so it must not reach the span.
+ it.each([
+ { description: 'a 404 response', error: fetchError({ statusCode: 404 }), statusMessage: 'not_found' },
+ { description: 'a 401 response', error: fetchError({ status: 401 }), statusMessage: 'unauthenticated' },
+ { description: 'a 503 response', error: fetchError({ statusCode: 503 }), statusMessage: 'unavailable' },
+ { description: 'a request with no response', error: fetchError({}), statusMessage: 'internal_error' },
+ {
+ description: 'a timeout',
+ error: new DOMException('The operation was aborted due to timeout', 'TimeoutError'),
+ statusMessage: 'internal_error',
+ },
+ { description: 'a rejection with no error object', error: 'no session', statusMessage: 'internal_error' },
+ ])('sets the status message `$statusMessage` for $description', async ({ error, statusMessage }) => {
+ const spans = await loadData(
+ { key: 'active-sessions', functionName: 'useAsyncData' },
+ () => Promise.reject(error),
+ {
+ rejects: true,
+ },
+ );
+
+ const dataSpan = spans.find(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpan?.status).toBe('error');
+ expect(dataSpan?.attributes[SENTRY_STATUS_MESSAGE]).toBe(statusMessage);
+ });
+
+ it('keeps the ok status for a handler that Nuxt aborts, because a new call with the same key replaced it', async () => {
+ const spans = await loadData(
+ { key: 'active-sessions', functionName: 'useAsyncData' },
+ () => Promise.reject(new DOMException('AsyncData request cancelled by deduplication', 'AbortError')),
+ { rejects: true },
+ );
+
+ const dataSpan = spans.find(span => span.attributes[SENTRY_ORIGIN] === DATA_ORIGIN);
+
+ expect(dataSpan?.status).toBe('ok');
+ expect(dataSpan?.attributes[ERROR_TYPE]).toBeUndefined();
+ });
+
+ it('captures no error for a handler that rejects, because Nuxt gives the error to the app', async () => {
+ const captureException = vi.spyOn(client, 'captureException');
+
+ await loadData(
+ { key: 'active-sessions', functionName: 'useAsyncData' },
+ () => Promise.reject(new Error('[GET] "/api/sessions": 500 Internal Server Error')),
+ { rejects: true },
+ );
+
+ expect(captureException).not.toHaveBeenCalled();
+ });
+
+ it('creates no span for a data load outside a request root span', async () => {
+ const endedSpanCount = endedSpans.length;
+
+ await traceAsync('nuxt.data', { key: 'active-sessions', functionName: 'useAsyncData' }, () => Promise.resolve());
+
+ expect(endedSpans).toHaveLength(endedSpanCount);
+ });
+
+ it('sets no active span for a data load outside a request root span', async () => {
+ const activeSpans: unknown[] = [];
+
+ await traceAsync('nuxt.data', { key: 'active-sessions', functionName: 'useAsyncData' }, async () => {
+ activeSpans.push(getActiveSpan());
+ });
+
+ expect(activeSpans).toEqual([undefined]);
+ });
+ });
});
describe('withNuxtTracingChannelIntegration', () => {