Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineNuxtRouteMiddleware, navigateTo } from '#imports';

export default defineNuxtRouteMiddleware(() => navigateTo('/test-param/redirect-target'));
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script setup lang="ts">
import { definePageMeta } from '#imports';

definePageMeta({ middleware: 'redirect-to-param-page' });
</script>

<template>
<p>The route middleware of this page redirects before the page renders.</p>
</template>
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { HTTP_RESPONSE_STATUS_CODE, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_RESPONSE_STATUS_CODE, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForEnvelopeItem, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';
import {
collectStreamedSpansUntilSegment,
waitForEnvelopeItem,
waitForError,
waitForStreamedSpan,
} from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';

Expand Down Expand Up @@ -84,6 +89,33 @@ test.describe('page that fails during SSR', () => {
expect(rootSpan.attributes[HTTP_RESPONSE_STATUS_CODE]).toEqual({ type: 'integer', value: 500 });
});

test('sends a span for the failed render and a `renderErrorPage` span for the render of the error page', async ({
request,
}) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes[URL_PATH]?.value === SSR_ERROR_PATH,
span => span.name === 'renderErrorPage',
);

await request.get(SSR_ERROR_PATH);

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const renderSpans = spans
.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.function.nuxt.render')
.map(span => ({
name: span.name,
status: span.status,
isChildOfRoot: span.parent_span_id === rootSpan?.span_id,
}));

expect(renderSpans).toEqual([
{ name: 'renderPage', status: 'error', isChildOfRoot: true },
{ name: 'renderErrorPage', status: 'ok', isChildOfRoot: true },
]);
});

test('names the root span after the page route', async ({ request }) => {
test.fail(
true,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { waitForError, waitForTransaction } from '@sentry-internal/test-utils';

Expand All @@ -21,6 +22,23 @@ test('sends a server action transaction on pageload', async ({ page }) => {
);
});

test('sends a `renderPage` span for the page render as a child of the server transaction', async ({ request }) => {
const transactionPromise = waitForTransaction('nuxt-4', transactionEvent => {
return transactionEvent.contexts?.trace?.data?.[URL_PATH] === '/test-param/render-span';
});

await request.get('/test-param/render-span');

const transaction = await transactionPromise;
const renderSpans = transaction.spans?.filter(span => span.origin === 'auto.function.nuxt.render');

expect(renderSpans).toHaveLength(1);
expect(renderSpans?.[0]?.description).toBe('renderPage');
expect(renderSpans?.[0]?.op).toBe(FUNCTION);
expect(renderSpans?.[0]?.parent_span_id).toBe(transaction.contexts?.trace?.span_id);
expect(renderSpans?.[0]?.data[HTTP_ROUTE]).toBe('/test-param/:param()');
});

[
// Nuxt build output that the HTTP integration does not ignore.
'/_nuxt/builds/latest.json',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { URL_PATH } from '@sentry/conventions/attributes';
import { CODE_FUNCTION_NAME, ERROR_TYPE, HTTP_ROUTE, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import {
collectStreamedSpans,
collectStreamedSpansUntilSegment,
getSpanOp,
waitForStreamedSpan,
waitForStreamedSpans,
Expand All @@ -10,6 +12,8 @@ import { IMPORT_SURFACES } from './importSurfaces';
import { isViteServer, NITRO_ONLY } from './isViteServer';
import { SERVER_ORIGIN } from './runtime';

const RENDER_ORIGIN = 'auto.function.nuxt.render';

test('sends a server root span on pageload', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nuxt-4', span => {
return span.is_segment && span.name.includes('GET /test-param/');
Expand All @@ -23,6 +27,61 @@ test('sends a server root span on pageload', async ({ page }) => {
expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN);
});

test('sends a `renderPage` span for the page render as a child of the server root span', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes[URL_PATH]?.value === '/test-param/render-span',
span => span.name === 'renderPage',
);

await request.get('/test-param/render-span');

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const renderSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === RENDER_ORIGIN);

expect(renderSpans).toHaveLength(1);
expect(renderSpans[0]?.name).toBe('renderPage');
expect(renderSpans[0]?.status).toBe('ok');
expect(renderSpans[0]?.parent_span_id).toBe(rootSpan?.span_id);
expect(getSpanOp(renderSpans[0]!)).toBe(FUNCTION);
expect(renderSpans[0]?.attributes[CODE_FUNCTION_NAME]).toEqual({ type: 'string', value: 'renderPage' });
expect(renderSpans[0]?.attributes[HTTP_ROUTE]).toEqual({ type: 'string', value: '/test-param/:param()' });
});

test('keeps the ok status of the render span when a route middleware redirects', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes[URL_PATH]?.value === '/redirect-in-route-middleware',
span => span.name === 'renderPage',
);

const response = await request.get('/redirect-in-route-middleware', { maxRedirects: 0 });

const renderSpan = (await spansPromise).find(span => span.name === 'renderPage');

expect(response.status()).toBe(302);
expect(renderSpan?.status).toBe('ok');
expect(renderSpan?.attributes[ERROR_TYPE]).toBeUndefined();
// The router is already at the target of the redirect, so the span has no route.
expect(renderSpan?.attributes[HTTP_ROUTE]).toBeUndefined();
});

test('keeps the ok status of the render span for a URL that matches no page', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes[URL_PATH]?.value === '/no-page-for-this-url',
span => span.name === 'renderPage',
);

const response = await request.get('/no-page-for-this-url');

const renderSpan = (await spansPromise).find(span => span.name === 'renderPage');

expect(response.status()).toBe(404);
expect(renderSpan?.status).toBe('ok');
});

[
// Nuxt build output that the HTTP integration does not ignore.
'/_nuxt/builds/latest.json',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineNuxtRouteMiddleware, navigateTo } from '#imports';

export default defineNuxtRouteMiddleware(() => navigateTo('/test-param/redirect-target'));
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script setup lang="ts">
import { definePageMeta } from '#imports';

definePageMeta({ middleware: 'redirect-to-param-page' });
</script>

<template>
<p>The route middleware of this page redirects before the page renders.</p>
</template>
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { HTTP_RESPONSE_STATUS_CODE, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_RESPONSE_STATUS_CODE, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForEnvelopeItem, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';
import {
collectStreamedSpansUntilSegment,
waitForEnvelopeItem,
waitForError,
waitForStreamedSpan,
} from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';

type EnvelopeItem = Parameters<Parameters<typeof waitForEnvelopeItem>[1]>[0];
Expand Down Expand Up @@ -79,6 +84,33 @@ test.describe('page that fails during SSR', () => {
expect(rootSpan.attributes[HTTP_RESPONSE_STATUS_CODE]).toEqual({ type: 'integer', value: 500 });
});

test('sends a span for the failed render and a `renderErrorPage` span for the render of the error page', async ({
request,
}) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes[URL_PATH]?.value === SSR_ERROR_PATH,
span => span.name === 'renderErrorPage',
);

await request.get(SSR_ERROR_PATH);

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const renderSpans = spans
.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.function.nuxt.render')
.map(span => ({
name: span.name,
status: span.status,
isChildOfRoot: span.parent_span_id === rootSpan?.span_id,
}));

expect(renderSpans).toEqual([
{ name: 'renderPage', status: 'error', isChildOfRoot: true },
{ name: 'renderErrorPage', status: 'ok', isChildOfRoot: true },
]);
});

test('names the root span after the page route', async ({ request }) => {
test.fail(true, 'Known bug: the root span of a failed render gets no page route, so its name is `GET`');

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { URL_PATH } from '@sentry/conventions/attributes';
import { CODE_FUNCTION_NAME, ERROR_TYPE, HTTP_ROUTE, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import {
collectStreamedSpans,
collectStreamedSpansUntilSegment,
getSpanOp,
waitForStreamedSpan,
waitForStreamedSpans,
} from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
import { SERVER_ORIGIN } from './runtime';

const RENDER_ORIGIN = 'auto.function.nuxt.render';

test('sends a server root span on pageload', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nuxt-5', span => {
return span.is_segment && span.name.includes('GET /test-param/');
Expand All @@ -22,6 +26,61 @@ test('sends a server root span on pageload', async ({ page }) => {
expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN);
});

test('sends a `renderPage` span for the page render as a child of the server root span', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes[URL_PATH]?.value === '/test-param/render-span',
span => span.name === 'renderPage',
);

await request.get('/test-param/render-span');

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const renderSpans = spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === RENDER_ORIGIN);

expect(renderSpans).toHaveLength(1);
expect(renderSpans[0]?.name).toBe('renderPage');
expect(renderSpans[0]?.status).toBe('ok');
expect(renderSpans[0]?.parent_span_id).toBe(rootSpan?.span_id);
expect(getSpanOp(renderSpans[0]!)).toBe(FUNCTION);
expect(renderSpans[0]?.attributes[CODE_FUNCTION_NAME]).toEqual({ type: 'string', value: 'renderPage' });
expect(renderSpans[0]?.attributes[HTTP_ROUTE]).toEqual({ type: 'string', value: '/test-param/:param()' });
});

test('keeps the ok status of the render span when a route middleware redirects', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes[URL_PATH]?.value === '/redirect-in-route-middleware',
span => span.name === 'renderPage',
);

const response = await request.get('/redirect-in-route-middleware', { maxRedirects: 0 });

const renderSpan = (await spansPromise).find(span => span.name === 'renderPage');

expect(response.status()).toBe(302);
expect(renderSpan?.status).toBe('ok');
expect(renderSpan?.attributes[ERROR_TYPE]).toBeUndefined();
// The router is already at the target of the redirect, so the span has no route.
expect(renderSpan?.attributes[HTTP_ROUTE]).toBeUndefined();
});

test('keeps the ok status of the render span for a URL that matches no page', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes[URL_PATH]?.value === '/no-page-for-this-url',
span => span.name === 'renderPage',
);

const response = await request.get('/no-page-for-this-url');

const renderSpan = (await spansPromise).find(span => span.name === 'renderPage');

expect(response.status()).toBe(404);
expect(renderSpan?.status).toBe('ok');
});

[
// Nuxt build output that the HTTP integration does not ignore.
'/_nuxt/builds/latest.json',
Expand Down
6 changes: 6 additions & 0 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { setupCloudflareEntry } from './vite/cloudflare';
import { addTunnelPlugin, setupNitroServer } from './vite/nitroServer';
import { setupOrchestrion } from './vite/orchestrion';
import { NUXT_RELEASE_RUNTIME_CONFIG_KEY, setupSourceMaps } from './vite/sourceMaps';
import { enableNuxtTracingChannels } from './vite/tracingChannel';
import { findCloudflareOptionsFile, findDefaultSdkInitFile, resolveServerApi } from './vite/utils';
import { setupViteServer } from './vite/viteServer';
import { stringifyForCodeInjection, warnOnConflictingSourceMapOptions } from '@sentry/core';
Expand Down Expand Up @@ -92,6 +93,11 @@ export default defineNuxtModule<ModuleOptions>({
const nuxtMajor = parseInt((nuxt as unknown as { _version: string })._version?.split('.')[0] ?? '3', 10);
const isMinNuxtV4 = nuxtMajor >= 4;

// Only when the module also sets up the server SDK, which subscribes to the channels.
if (serverConfigFile || cloudflareOptionsFile) {
await enableNuxtTracingChannels(nuxt, serverApi);
}

// Orchestrion runs on both the Node path (gated on a server config file) and the Cloudflare path
// (which has no server config file, the SDK is set up via `withSentry` or `sentryCloudflareNitroPlugin`). The
// Cloudflare detection happens inside, keyed off the resolved Nitro preset.
Expand Down
53 changes: 53 additions & 0 deletions packages/nuxt/src/vite/tracingChannel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { hasNuxtCompatibility } from '@nuxt/kit';
import type { Nuxt, NuxtConfig } from '@nuxt/schema';
import type { ServerApi } from './utils';

type TracingChannelValue = NuxtConfig['tracingChannel'];

// The SDK's own instrumentation makes these spans. It also works on Nitro v2, which has no channels.
const NITRO_CHANNEL_GROUPS_OFF = { srvx: false, h3: false, unstorage: false, db0: false };

/**
* Turns on the `nuxt.*` tracing channels for `nuxtTracingChannelIntegration`.
* A `tracingChannel` value in the Nuxt config of the app wins.
*/
export async function enableNuxtTracingChannels(nuxt: Nuxt, serverApi: ServerApi): Promise<void> {
// The option exists since Nuxt 4.5, but the `nuxt.request` channel came in 4.7.
if (!(await hasNuxtCompatibility({ nuxt: '>=4.7.0' }, nuxt))) {
return;
}

// The resolved option is `false` for both "not set" and `false`. Only the raw layer config tells them apart.
const layerConfigs = nuxt.options._layers.map(layer => layer.config);
const userValue = mergeLayerValues(layerConfigs.map(config => config?.tracingChannel));
// oxlint-disable-next-line typescript/no-deprecated -- Nuxt still reads it
const deprecatedUserValue = mergeLayerValues(layerConfigs.map(config => config?.nitro?.tracingChannel));

if (typeof userValue === 'boolean' || typeof deprecatedUserValue === 'boolean') {
return;
}

// Another module or a CLI override set the option. Keep that value.
if (!userValue && !deprecatedUserValue && nuxt.options.tracingChannel) {
return;
}

nuxt.options.tracingChannel = {
nuxt: true,
// Only Nitro v3 has these groups.
...(serverApi === 'nitro3' && NITRO_CHANNEL_GROUPS_OFF),
...userValue,
...deprecatedUserValue,
};
}

/** Merges the layer values as Nuxt does. The first layer that sets a key wins, and the app is the first layer. */
function mergeLayerValues(values: TracingChannelValue[]): TracingChannelValue {
return values.reduce((merged, value) => {
if (typeof merged === 'object' && typeof value === 'object') {
return { ...value, ...merged };
}

return merged ?? value;
}, undefined);
}
Loading
Loading