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
30 changes: 20 additions & 10 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import type {} from '@nuxt/nitro-server';
import * as path from 'path';
import { NUXT_TUNNEL_BASE_PATH_GLOBAL } from './common/tunnel';
import type { SentryNuxtModuleOptions } from './common/types';
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 { findDefaultSdkInitFile, resolveServerApi } from './vite/utils';
import { findCloudflareOptionsFile, findDefaultSdkInitFile, resolveServerApi } from './vite/utils';
import { setupViteServer } from './vite/viteServer';
import { stringifyForCodeInjection } from '@sentry/core';

Expand Down Expand Up @@ -84,34 +85,39 @@ export default defineNuxtModule<ModuleOptions>({
}

const serverConfigFile = await findDefaultSdkInitFile('server', nuxt, moduleOptions);
const cloudflareOptionsFile = await findCloudflareOptionsFile(nuxt, moduleOptions);
const nuxtMajor = parseInt((nuxt as unknown as { _version: string })._version?.split('.')[0] ?? '3', 10);
const isMinNuxtV4 = nuxtMajor >= 4;

// 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 `sentryCloudflareNitroPlugin`). The
// (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.
setupOrchestrion(nuxt, !!serverConfigFile, moduleOptions.buildTimeInstrumentation);

if (serverConfigFile) {
if (serverApi === 'nuxt') {
if (cloudflareOptionsFile) {
setupCloudflareEntry(nuxt, cloudflareOptionsFile);
}

if (serverApi === 'nuxt') {
if (serverConfigFile) {
setupViteServer(nuxt, serverConfigFile, moduleOptions);
} else {
setupNitroServer(nuxt, serverApi, serverConfigFile, moduleOptions);
}
} else if (serverConfigFile || cloudflareOptionsFile) {
setupNitroServer(nuxt, serverApi, serverConfigFile, moduleOptions, !!cloudflareOptionsFile);
} else {
// The Cloudflare setup initializes the SDK from `sentryCloudflareNitroPlugin`, so it needs the tunnel too.
// `sentryCloudflareNitroPlugin` initializes the SDK without a config file, so it needs the tunnel too.
addTunnelPlugin(serverApi);
}

// Names the server spans of pages after their route, with the SDK set up from the server config or from
// `sentryCloudflareNitroPlugin`.
// Names the server spans of pages after their route, with the SDK set up from the server config, from
// `instrument.server.ts` or from `sentryCloudflareNitroPlugin`.
if (isMinNuxtV4) {
addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector.server'), mode: 'server' });
} else {
addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector-legacy.server'), mode: 'server' });
}

if (clientConfigFile || serverConfigFile) {
if (clientConfigFile || serverConfigFile || cloudflareOptionsFile) {
setupSourceMaps(moduleOptions, nuxt, addVitePlugin, !!clientConfigFile, serverApi === 'nuxt');
}

Expand Down Expand Up @@ -164,6 +170,10 @@ export default defineNuxtModule<ModuleOptions>({
const relativePath = path.relative(nuxt.options.buildDir, serverConfigFile);
tsConfig.include.push(relativePath);
}
if (cloudflareOptionsFile) {
const relativePath = path.relative(nuxt.options.buildDir, cloudflareOptionsFile);
tsConfig.include.push(relativePath);
}
});
},
});
21 changes: 21 additions & 0 deletions packages/nuxt/src/runtime/plugins/cloudflare-entry.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { getIsolationScope, stripUrlQueryAndFragment } from '@sentry/core';
import type { H3Event } from 'h3';
import type { NitroAppPlugin } from 'nitropack';
import { markCloudflareEntryWrapped } from '../utils/cloudflare-entry';

type H3V2Event = { req: { method: string }; url: { pathname: string } };

export default (nitroApp => {
// This plugin runs before the plugins of the app, so a `sentryCloudflareNitroPlugin` there sees the flag.
markCloudflareEntryWrapped();
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved

// `withSentry` sets no transaction name, so errors captured during the request would have none.
// This is the same best-effort name the Node SDK sets when a request starts.
nitroApp.hooks.hook('request', (event: H3Event) => {
// h3 v1 (Nitro 2) has the method and the path on the event, h3 v2 (Nitro 3) on `event.req` and `event.url`.
const { req, url } = event as unknown as Partial<H3V2Event>;
const method = event.method ?? req?.method;
const path = event.path ?? url?.pathname;
getIsolationScope().setTransactionName(`${method} ${stripUrlQueryAndFragment(path)}`);
});
}) satisfies NitroAppPlugin;
1 change: 1 addition & 0 deletions packages/nuxt/src/runtime/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
// oxlint-disable-next-line typescript/no-deprecated -- supported until removal
export { sentryCloudflareNitroPlugin } from './sentry-cloudflare.server';
25 changes: 25 additions & 0 deletions packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { wrapRequestHandler } from '@sentry/cloudflare/request';
import {
_INTERNAL_captureOptionsSetByUser,
applySdkMetadata,
consoleSandbox,
debug,
getDefaultIsolationScope,
getIsolationScope,
Expand All @@ -20,6 +21,7 @@ import type { NitroApp, NitroAppPlugin } from 'nitropack';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse';
import { isCloudflareEntryWrapped } from '../utils/cloudflare-entry';
import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check';
import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags';

Expand Down Expand Up @@ -66,10 +68,33 @@ function getRequestHandlerOptions(cloudflareOptions: CloudflareOptions): Cloudfl
* debug: nitroApp.h3App.options.debug
* })));
* ```
*
* @deprecated Add an `instrument.server.ts` file to the root of the Nuxt app instead. Its default export returns the
* options of `@sentry/cloudflare`, and the Sentry Nuxt module wraps the Worker with `withSentry`.
*
* ```ts
* // instrument.server.ts
* import { defineCloudflareOptions } from '@sentry/cloudflare';
*
* export default defineCloudflareOptions(env => ({
* dsn: env.SENTRY_DSN,
* }));
* ```
*/
// TODO(v12): Remove `sentryCloudflareNitroPlugin`.
export const sentryCloudflareNitroPlugin =
(optionsOrFn: CloudflareOptions | ((nitroApp: NitroApp) => CloudflareOptions)): NitroAppPlugin =>
(nitroApp: NitroApp): void => {
if (isCloudflareEntryWrapped()) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[Sentry] `sentryCloudflareNitroPlugin` does nothing, because Sentry sets up the SDK from `instrument.server.ts`. Remove the plugin.',
);
});
return;
}

const traceDataMap = new WeakMap<object, ReturnType<typeof getTraceData>>();

// Nitro v3 (Nuxt 5) has no `localFetch`. It hands the Worker's own request to `fetch`, with `ctx` on it.
Expand Down
15 changes: 15 additions & 0 deletions packages/nuxt/src/runtime/utils/cloudflare-entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { GLOBAL_OBJ } from '@sentry/core';

const CLOUDFLARE_ENTRY_WRAPPED_FLAG = '__SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__';

type GlobalWithCloudflareEntryFlag = typeof GLOBAL_OBJ & { [CLOUDFLARE_ENTRY_WRAPPED_FLAG]?: boolean };

/** Records that the Sentry Nuxt module wrapped the Worker entry with `withSentry`. */
export function markCloudflareEntryWrapped(): void {
(GLOBAL_OBJ as GlobalWithCloudflareEntryFlag)[CLOUDFLARE_ENTRY_WRAPPED_FLAG] = true;
}

/** Whether the Sentry Nuxt module wrapped the Worker entry with `withSentry`. */
export function isCloudflareEntryWrapped(): boolean {
return (GLOBAL_OBJ as GlobalWithCloudflareEntryFlag)[CLOUDFLARE_ENTRY_WRAPPED_FLAG] === true;
}
7 changes: 7 additions & 0 deletions packages/nuxt/src/runtime/utils/cloudflareWorkers.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// `@cloudflare/workers-types` declares this module, but pulling it in would also add Workers globals
// that clash with the DOM lib the client half of this package is checked against. Only the export
// the SDK reads is declared here; the declaration is build-time only and never emitted.
declare module 'cloudflare:workers' {
// workerd versions from before March 2025 have no `withEnv`.
export const withEnv: (<T>(env: unknown, callback: () => T) => T) | undefined;
}
75 changes: 75 additions & 0 deletions packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { DurableObjectState, ExecutionContext, ExportedHandler } from '@cloudflare/workers-types';
import type { CloudflareOptions } from '@sentry/cloudflare';
import { instrumentDurableObjectWithSentry, withSentry } from '@sentry/cloudflare';
import { applySdkMetadata } from '@sentry/core';
// A namespace import keeps a missing `withEnv` export a missing property instead of a module linking error.
import * as cloudflareWorkers from 'cloudflare:workers';

type OptionsCallback = (env: unknown) => CloudflareOptions;
type NitroDurableObjectClass = new (state: DurableObjectState, env: unknown) => object;
type Method = (this: unknown, ...args: unknown[]) => unknown;

/**
* Wraps the default export of the Nitro Worker entry with `withSentry`. Each handler runs with the `env` that
* `withSentry` instruments as the `env` of `cloudflare:workers`, so db0 of Nitro 3 reads instrumented D1 bindings.
*/
export function wrapNitroCloudflareEntryWithSentry<Handler extends ExportedHandler>(
optionsCallback: OptionsCallback,
handler: Handler,
): Handler {
const handlerWithEnv = Object.fromEntries(
Object.entries(handler).map(([name, value]) => [
name,
typeof value === 'function'
? (event: unknown, env: unknown, context: ExecutionContext): unknown =>
runWithEnv(env, () => (value as Method).call(handler, event, env, context))
: value,
]),
) as Handler;

return withSentry(withNuxtSdkMetadata(optionsCallback), handlerWithEnv);
}

/**
* Wraps the Durable Object class of the Nitro Worker entry with `instrumentDurableObjectWithSentry`. Each method runs
* with the instrumented `this.env` as the `env` of `cloudflare:workers`.
*/
export function wrapNitroDurableObjectWithSentry(
optionsCallback: OptionsCallback,
NitroDurableObject: NitroDurableObjectClass,
): NitroDurableObjectClass {
class NitroDurableObjectWithEnv extends NitroDurableObject {}

for (const name of Object.getOwnPropertyNames(NitroDurableObject.prototype)) {
const method: unknown = Object.getOwnPropertyDescriptor(NitroDurableObject.prototype, name)?.value;
if (name === 'constructor' || typeof method !== 'function') {
continue;
}

// Frameworks can read the name of a method, so the wrapper keeps it.
const { [name]: methodWithEnv } = {
[name](this: { env?: unknown }, ...args: unknown[]): unknown {
return runWithEnv(this.env, () => (method as Method).apply(this, args));
},
};
Object.defineProperty(NitroDurableObjectWithEnv.prototype, name, {
value: methodWithEnv,
writable: true,
configurable: true,
});
}

return instrumentDurableObjectWithSentry(withNuxtSdkMetadata(optionsCallback), NitroDurableObjectWithEnv);
}

function runWithEnv(env: unknown, callback: () => unknown): unknown {
return cloudflareWorkers.withEnv && env !== undefined ? cloudflareWorkers.withEnv(env, callback) : callback();
}

function withNuxtSdkMetadata(optionsCallback: OptionsCallback): OptionsCallback {
return env => {
const options = { ...optionsCallback(env) };
applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']);
return options;
};
}
17 changes: 14 additions & 3 deletions packages/nuxt/src/vite/addServerConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,16 @@ export function addSentryTopImport(moduleOptions: SentryNuxtModuleOptions, nitro
/**
* Registers a Nitro plugin that statically imports the Sentry server config, so the SDK initializes
* at server startup without a `node --import` preload.
*
* On a Cloudflare preset, it removes the plugin again. It warns then only when the app has no `instrument.server`
* file (`hasCloudflareOptionsFile`), because an app with both files can build for Node and for Cloudflare.
*/
export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLegacyNitro: boolean): void {
export function addServerConfigPlugin(
nuxt: Nuxt,
serverConfigFile: string,
isLegacyNitro: boolean,
hasCloudflareOptionsFile: boolean,
): void {
const configPath = createResolver(nuxt.options.rootDir).resolve(serverConfigFile);
const runtimeFlagsTemplate = addRuntimeFlagsTemplate();

Expand Down Expand Up @@ -156,18 +164,21 @@ export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLe
}
});

// On Cloudflare the SDK is set up through `sentryCloudflareNitroPlugin`; the Node SDK config
// On Cloudflare `withSentry` sets up the SDK with the options of `instrument.server.ts`; the Node SDK config
// must not end up in the worker bundle. `nitro.options.preset` is resolved here.
nuxt.hook('nitro:init', nitro => {
if (nuxt.options._prepare || !isCloudflarePreset(nitro.options.preset)) {
return;
}

nitro.options.plugins = (nitro.options.plugins ?? []).filter(plugin => plugin !== configPluginTemplate.dst);
if (hasCloudflareOptionsFile) {
return;
}
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
`[Sentry] Found \`${basename(configPath)}\`, but the Nitro preset targets Cloudflare, where this file is not used. Set up the SDK with \`sentryCloudflareNitroPlugin\` instead: https://docs.sentry.io/platforms/javascript/guides/nuxt/install/cloudflare-workers/`,
`[Sentry] Found \`${basename(configPath)}\`, but the Nitro preset targets Cloudflare, where this file is not used. Set up the SDK in \`instrument.server.ts\` instead: https://docs.sentry.io/platforms/javascript/guides/nuxt/install/cloudflare-workers/`,
);
});
});
Expand Down
Loading
Loading