Skip to content

Commit 7f46250

Browse files
isaacsclaude
andcommitted
fix(nuxt): Answer managed tunnel requests on Cloudflare
`sentryCloudflareNitroPlugin` matched the tunnel before `wrapRequestHandler` created the client. No client was current, so the match always failed, the tunnel request got no body, and the app answered it instead of the SDK. The plugin now matches the tunnel inside the `wrapRequestHandler` callback, where the client exists, and passes the body Nitro read only to the tunnel handler. Other requests still get no body, so their bodies stay off their events. The `nuxt-4-cloudflare` tunnel e2e test only checked for a 200, which the app returns too. It now waits for the forwarded envelope, and it fails without this fix. Closes #26364 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 32ee1da commit 7f46250

3 files changed

Lines changed: 59 additions & 14 deletions

File tree

‎dev-packages/e2e-tests/test-applications/nuxt-4/package.json‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,7 @@
8787
"build-command": "pnpm test:build:cloudflare",
8888
"assert-command": "pnpm test:prod",
8989
"label": "nuxt-4 (cloudflare)"
90-
}
91-
],
92-
"optionalVariants": [
90+
},
9391
{
9492
"runtime": "cloudflare",
9593
"build-command": "pnpm test:build:tunnel-basepath-cloudflare",

‎packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import {
99
getTraceData,
1010
stripUrlQueryAndFragment,
1111
} from '@sentry/core';
12-
import { _INTERNAL_isServedTunnelRequest as isServedTunnelRequest } from '@sentry/core/server';
12+
import {
13+
_INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
14+
_INTERNAL_isServedTunnelRequest as isServedTunnelRequest,
15+
} from '@sentry/core/server';
1316
import type { H3Event } from 'h3';
1417
import type { NitroApp, NitroAppPlugin } from 'nitropack';
1518
import type { NuxtRenderHTMLContext } from 'nuxt/app';
@@ -106,12 +109,11 @@ export const sentryCloudflareNitroPlugin =
106109
} else {
107110
// Usually, the protocol already includes ":"
108111
const url = `${event.protocol}${event.protocol.endsWith(':') ? '' : ':'}//${event.host}${pathname}`;
112+
// Nitro read the body before calling `localFetch`. This request has no body, so other requests' bodies
113+
// don't end up on events. Only the managed tunnel needs it, see below.
109114
const request = new Request(url, {
110115
method: event.method,
111116
headers: event.headers,
112-
// Nitro read the body before calling `localFetch`. Only the managed tunnel answers from this request, so
113-
// only its requests get the body, and other requests' bodies don't end up on events.
114-
body: isServedTunnelRequest({ method: event.method, url: pathname }) ? event.body : undefined,
115117
// @ts-expect-error - 'cf' is a valid property in the RequestInit type for Cloudflare
116118
cf: getCfProperties(event),
117119
});
@@ -129,6 +131,17 @@ export const sentryCloudflareNitroPlugin =
129131
};
130132

131133
return wrapRequestHandler(requestHandlerOptions, () => {
134+
// The served tunnel belongs to the client `wrapRequestHandler` creates, so it can only match from here.
135+
// The wrapper records no span, session or body for a tunnel request.
136+
if (event.body && isServedTunnelRequest(request)) {
137+
const tunnelResponse = handleServedTunnelRequest(
138+
new Request(url, { method: event.method, headers: event.headers, body: event.body }),
139+
);
140+
if (tunnelResponse) {
141+
return tunnelResponse;
142+
}
143+
}
144+
132145
setRequestTransactionName(event.method, pathname);
133146

134147
const isolationScope = getIsolationScope();

‎packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import type { CloudflareOptions } from '@sentry/cloudflare';
2+
import { serveTunnelIntegration } from '@sentry/cloudflare';
23
import { wrapRequestHandler } from '@sentry/cloudflare/request';
4+
import { getTunnelPath } from '@sentry/core';
35
import type { NitroApp } from 'nitropack';
4-
import { beforeEach, describe, expect, it, vi } from 'vitest';
6+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
57
import { sentryCloudflareNitroPlugin } from '../../../src/runtime/plugins/sentry-cloudflare.server';
68

79
vi.mock('@sentry/cloudflare/request', () => ({
@@ -10,25 +12,36 @@ vi.mock('@sentry/cloudflare/request', () => ({
1012

1113
const DSN = 'https://public@dsn.ingest.sentry.io/1337';
1214

13-
async function handleRequest(options: CloudflareOptions): Promise<void> {
14-
const nitroApp = { localFetch: vi.fn(), hooks: { hook: vi.fn() } } as unknown as NitroApp;
15+
async function handleRequest(
16+
options: CloudflareOptions,
17+
{ path = '/api/db-mysql', method = 'GET', body }: { path?: string; method?: string; body?: string } = {},
18+
): Promise<{ response: unknown; localFetch: ReturnType<typeof vi.fn> }> {
19+
const localFetch = vi.fn(() => new Response('app'));
20+
const nitroApp = { localFetch, hooks: { hook: vi.fn() } } as unknown as NitroApp;
1521
sentryCloudflareNitroPlugin(options)(nitroApp);
1622

1723
const event = {
1824
protocol: 'https:',
1925
host: 'example.com',
20-
method: 'GET',
21-
headers: {},
22-
context: { cf: {}, cloudflare: { context: {} } },
26+
method,
27+
headers: body ? { 'content-length': String(body.length) } : {},
28+
body,
29+
context: { cf: {}, cloudflare: { context: { waitUntil: vi.fn(), passThroughOnException: vi.fn() } } },
2330
};
24-
await nitroApp.localFetch('/api/db-mysql', event as unknown as RequestInit);
31+
const response = await nitroApp.localFetch(path, event as unknown as RequestInit);
32+
33+
return { response, localFetch };
2534
}
2635

2736
describe('sentryCloudflareNitroPlugin', () => {
2837
beforeEach(() => {
2938
vi.mocked(wrapRequestHandler).mockClear();
3039
});
3140

41+
afterEach(() => {
42+
vi.restoreAllMocks();
43+
});
44+
3245
it('passes a defaultIntegrations list that extends the SDK defaults', async () => {
3346
await handleRequest({ dsn: DSN });
3447

@@ -53,4 +66,25 @@ describe('sentryCloudflareNitroPlugin', () => {
5366
expect.any(Function),
5467
);
5568
});
69+
70+
it('answers a managed tunnel request with the body Nitro read', async () => {
71+
const actual = await vi.importActual<{ wrapRequestHandler: typeof wrapRequestHandler }>(
72+
'@sentry/cloudflare/request',
73+
);
74+
vi.mocked(wrapRequestHandler).mockImplementationOnce(actual.wrapRequestHandler);
75+
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));
76+
const envelope = `${JSON.stringify({ dsn: DSN })}\n${JSON.stringify({ type: 'event' })}\n{}`;
77+
78+
const { response, localFetch } = await handleRequest(
79+
{ dsn: DSN, integrations: [serveTunnelIntegration()] },
80+
{ path: getTunnelPath(DSN), method: 'POST', body: envelope },
81+
);
82+
83+
expect((response as Response).status).toBe(200);
84+
expect(fetchSpy).toHaveBeenCalledWith(
85+
expect.stringContaining('dsn.ingest.sentry.io/api/1337/envelope/'),
86+
expect.objectContaining({ method: 'POST' }),
87+
);
88+
expect(localFetch).not.toHaveBeenCalled();
89+
});
5690
});

0 commit comments

Comments
 (0)